source: trunk/packages/xen-3.1/xen-3.1/linux-2.6-xen-sparse/arch/ia64/kernel/perfmon.c @ 34

Last change on this file since 34 was 34, checked in by hartmans, 18 years ago

Add xen and xen-common

File size: 171.4 KB
Line 
1/*
2 * This file implements the perfmon-2 subsystem which is used
3 * to program the IA-64 Performance Monitoring Unit (PMU).
4 *
5 * The initial version of perfmon.c was written by
6 * Ganesh Venkitachalam, IBM Corp.
7 *
8 * Then it was modified for perfmon-1.x by Stephane Eranian and
9 * David Mosberger, Hewlett Packard Co.
10 *
11 * Version Perfmon-2.x is a rewrite of perfmon-1.x
12 * by Stephane Eranian, Hewlett Packard Co.
13 *
14 * Copyright (C) 1999-2005  Hewlett Packard Co
15 *               Stephane Eranian <eranian@hpl.hp.com>
16 *               David Mosberger-Tang <davidm@hpl.hp.com>
17 *
18 * More information about perfmon available at:
19 *      http://www.hpl.hp.com/research/linux/perfmon
20 */
21
22#include <linux/module.h>
23#include <linux/kernel.h>
24#include <linux/sched.h>
25#include <linux/interrupt.h>
26#include <linux/smp_lock.h>
27#include <linux/proc_fs.h>
28#include <linux/seq_file.h>
29#include <linux/init.h>
30#include <linux/vmalloc.h>
31#include <linux/mm.h>
32#include <linux/sysctl.h>
33#include <linux/list.h>
34#include <linux/file.h>
35#include <linux/poll.h>
36#include <linux/vfs.h>
37#include <linux/pagemap.h>
38#include <linux/mount.h>
39#include <linux/bitops.h>
40#include <linux/capability.h>
41#include <linux/rcupdate.h>
42#include <linux/completion.h>
43
44#include <asm/errno.h>
45#include <asm/intrinsics.h>
46#include <asm/page.h>
47#include <asm/perfmon.h>
48#include <asm/processor.h>
49#include <asm/signal.h>
50#include <asm/system.h>
51#include <asm/uaccess.h>
52#include <asm/delay.h>
53
54#ifdef CONFIG_PERFMON
55#ifdef CONFIG_XEN
56//#include <xen/xenoprof.h>
57#include <xen/interface/xenoprof.h>
58
59static int xenoprof_is_primary = 0;
60#define init_xenoprof_primary(is_primary)  (xenoprof_is_primary = (is_primary))
61#define is_xenoprof_primary()   (xenoprof_is_primary)
62#define XEN_NOT_SUPPORTED_YET                                           \
63        do {                                                            \
64                if (is_running_on_xen()) {                              \
65                        printk("%s is not supported yet under xen.\n",  \
66                               __func__);                               \
67                        return -ENOSYS;                                 \
68                }                                                       \
69        } while (0)
70#else
71#define init_xenoprof_primary(is_primary)       do { } while (0)
72#define is_xenoprof_primary()                   (0)
73#define XEN_NOT_SUPPORTED_YET                   do { } while (0)
74#define HYPERVISOR_perfmon_op(cmd, arg, count)  do { } while (0)
75#endif
76
77/*
78 * perfmon context state
79 */
80#define PFM_CTX_UNLOADED        1       /* context is not loaded onto any task */
81#define PFM_CTX_LOADED          2       /* context is loaded onto a task */
82#define PFM_CTX_MASKED          3       /* context is loaded but monitoring is masked due to overflow */
83#define PFM_CTX_ZOMBIE          4       /* owner of the context is closing it */
84
85#define PFM_INVALID_ACTIVATION  (~0UL)
86
87/*
88 * depth of message queue
89 */
90#define PFM_MAX_MSGS            32
91#define PFM_CTXQ_EMPTY(g)       ((g)->ctx_msgq_head == (g)->ctx_msgq_tail)
92
93/*
94 * type of a PMU register (bitmask).
95 * bitmask structure:
96 *      bit0   : register implemented
97 *      bit1   : end marker
98 *      bit2-3 : reserved
99 *      bit4   : pmc has pmc.pm
100 *      bit5   : pmc controls a counter (has pmc.oi), pmd is used as counter
101 *      bit6-7 : register type
102 *      bit8-31: reserved
103 */
104#define PFM_REG_NOTIMPL         0x0 /* not implemented at all */
105#define PFM_REG_IMPL            0x1 /* register implemented */
106#define PFM_REG_END             0x2 /* end marker */
107#define PFM_REG_MONITOR         (0x1<<4|PFM_REG_IMPL) /* a PMC with a pmc.pm field only */
108#define PFM_REG_COUNTING        (0x2<<4|PFM_REG_MONITOR) /* a monitor + pmc.oi+ PMD used as a counter */
109#define PFM_REG_CONTROL         (0x4<<4|PFM_REG_IMPL) /* PMU control register */
110#define PFM_REG_CONFIG          (0x8<<4|PFM_REG_IMPL) /* configuration register */
111#define PFM_REG_BUFFER          (0xc<<4|PFM_REG_IMPL) /* PMD used as buffer */
112
113#define PMC_IS_LAST(i)  (pmu_conf->pmc_desc[i].type & PFM_REG_END)
114#define PMD_IS_LAST(i)  (pmu_conf->pmd_desc[i].type & PFM_REG_END)
115
116#define PMC_OVFL_NOTIFY(ctx, i) ((ctx)->ctx_pmds[i].flags &  PFM_REGFL_OVFL_NOTIFY)
117
118/* i assumed unsigned */
119#define PMC_IS_IMPL(i)    (i< PMU_MAX_PMCS && (pmu_conf->pmc_desc[i].type & PFM_REG_IMPL))
120#define PMD_IS_IMPL(i)    (i< PMU_MAX_PMDS && (pmu_conf->pmd_desc[i].type & PFM_REG_IMPL))
121
122/* XXX: these assume that register i is implemented */
123#define PMD_IS_COUNTING(i) ((pmu_conf->pmd_desc[i].type & PFM_REG_COUNTING) == PFM_REG_COUNTING)
124#define PMC_IS_COUNTING(i) ((pmu_conf->pmc_desc[i].type & PFM_REG_COUNTING) == PFM_REG_COUNTING)
125#define PMC_IS_MONITOR(i)  ((pmu_conf->pmc_desc[i].type & PFM_REG_MONITOR)  == PFM_REG_MONITOR)
126#define PMC_IS_CONTROL(i)  ((pmu_conf->pmc_desc[i].type & PFM_REG_CONTROL)  == PFM_REG_CONTROL)
127
128#define PMC_DFL_VAL(i)     pmu_conf->pmc_desc[i].default_value
129#define PMC_RSVD_MASK(i)   pmu_conf->pmc_desc[i].reserved_mask
130#define PMD_PMD_DEP(i)     pmu_conf->pmd_desc[i].dep_pmd[0]
131#define PMC_PMD_DEP(i)     pmu_conf->pmc_desc[i].dep_pmd[0]
132
133#define PFM_NUM_IBRS      IA64_NUM_DBG_REGS
134#define PFM_NUM_DBRS      IA64_NUM_DBG_REGS
135
136#define CTX_OVFL_NOBLOCK(c)     ((c)->ctx_fl_block == 0)
137#define CTX_HAS_SMPL(c)         ((c)->ctx_fl_is_sampling)
138#define PFM_CTX_TASK(h)         (h)->ctx_task
139
140#define PMU_PMC_OI              5 /* position of pmc.oi bit */
141
142/* XXX: does not support more than 64 PMDs */
143#define CTX_USED_PMD(ctx, mask) (ctx)->ctx_used_pmds[0] |= (mask)
144#define CTX_IS_USED_PMD(ctx, c) (((ctx)->ctx_used_pmds[0] & (1UL << (c))) != 0UL)
145
146#define CTX_USED_MONITOR(ctx, mask) (ctx)->ctx_used_monitors[0] |= (mask)
147
148#define CTX_USED_IBR(ctx,n)     (ctx)->ctx_used_ibrs[(n)>>6] |= 1UL<< ((n) % 64)
149#define CTX_USED_DBR(ctx,n)     (ctx)->ctx_used_dbrs[(n)>>6] |= 1UL<< ((n) % 64)
150#define CTX_USES_DBREGS(ctx)    (((pfm_context_t *)(ctx))->ctx_fl_using_dbreg==1)
151#define PFM_CODE_RR     0       /* requesting code range restriction */
152#define PFM_DATA_RR     1       /* requestion data range restriction */
153
154#define PFM_CPUINFO_CLEAR(v)    pfm_get_cpu_var(pfm_syst_info) &= ~(v)
155#define PFM_CPUINFO_SET(v)      pfm_get_cpu_var(pfm_syst_info) |= (v)
156#define PFM_CPUINFO_GET()       pfm_get_cpu_var(pfm_syst_info)
157
158#define RDEP(x) (1UL<<(x))
159
160/*
161 * context protection macros
162 * in SMP:
163 *      - we need to protect against CPU concurrency (spin_lock)
164 *      - we need to protect against PMU overflow interrupts (local_irq_disable)
165 * in UP:
166 *      - we need to protect against PMU overflow interrupts (local_irq_disable)
167 *
168 * spin_lock_irqsave()/spin_lock_irqrestore():
169 *      in SMP: local_irq_disable + spin_lock
170 *      in UP : local_irq_disable
171 *
172 * spin_lock()/spin_lock():
173 *      in UP : removed automatically
174 *      in SMP: protect against context accesses from other CPU. interrupts
175 *              are not masked. This is useful for the PMU interrupt handler
176 *              because we know we will not get PMU concurrency in that code.
177 */
178#define PROTECT_CTX(c, f) \
179        do {  \
180                DPRINT(("spinlock_irq_save ctx %p by [%d]\n", c, current->pid)); \
181                spin_lock_irqsave(&(c)->ctx_lock, f); \
182                DPRINT(("spinlocked ctx %p  by [%d]\n", c, current->pid)); \
183        } while(0)
184
185#define UNPROTECT_CTX(c, f) \
186        do { \
187                DPRINT(("spinlock_irq_restore ctx %p by [%d]\n", c, current->pid)); \
188                spin_unlock_irqrestore(&(c)->ctx_lock, f); \
189        } while(0)
190
191#define PROTECT_CTX_NOPRINT(c, f) \
192        do {  \
193                spin_lock_irqsave(&(c)->ctx_lock, f); \
194        } while(0)
195
196
197#define UNPROTECT_CTX_NOPRINT(c, f) \
198        do { \
199                spin_unlock_irqrestore(&(c)->ctx_lock, f); \
200        } while(0)
201
202
203#define PROTECT_CTX_NOIRQ(c) \
204        do {  \
205                spin_lock(&(c)->ctx_lock); \
206        } while(0)
207
208#define UNPROTECT_CTX_NOIRQ(c) \
209        do { \
210                spin_unlock(&(c)->ctx_lock); \
211        } while(0)
212
213
214#ifdef CONFIG_SMP
215
216#define GET_ACTIVATION()        pfm_get_cpu_var(pmu_activation_number)
217#define INC_ACTIVATION()        pfm_get_cpu_var(pmu_activation_number)++
218#define SET_ACTIVATION(c)       (c)->ctx_last_activation = GET_ACTIVATION()
219
220#else /* !CONFIG_SMP */
221#define SET_ACTIVATION(t)       do {} while(0)
222#define GET_ACTIVATION(t)       do {} while(0)
223#define INC_ACTIVATION(t)       do {} while(0)
224#endif /* CONFIG_SMP */
225
226#define SET_PMU_OWNER(t, c)     do { pfm_get_cpu_var(pmu_owner) = (t); pfm_get_cpu_var(pmu_ctx) = (c); } while(0)
227#define GET_PMU_OWNER()         pfm_get_cpu_var(pmu_owner)
228#define GET_PMU_CTX()           pfm_get_cpu_var(pmu_ctx)
229
230#define LOCK_PFS(g)             spin_lock_irqsave(&pfm_sessions.pfs_lock, g)
231#define UNLOCK_PFS(g)           spin_unlock_irqrestore(&pfm_sessions.pfs_lock, g)
232
233#define PFM_REG_RETFLAG_SET(flags, val) do { flags &= ~PFM_REG_RETFL_MASK; flags |= (val); } while(0)
234
235/*
236 * cmp0 must be the value of pmc0
237 */
238#define PMC0_HAS_OVFL(cmp0)  (cmp0 & ~0x1UL)
239
240#define PFMFS_MAGIC 0xa0b4d889
241
242/*
243 * debugging
244 */
245#define PFM_DEBUGGING 1
246#ifdef PFM_DEBUGGING
247#define DPRINT(a) \
248        do { \
249                if (unlikely(pfm_sysctl.debug >0)) { printk("%s.%d: CPU%d [%d] ", __FUNCTION__, __LINE__, smp_processor_id(), current->pid); printk a; } \
250        } while (0)
251
252#define DPRINT_ovfl(a) \
253        do { \
254                if (unlikely(pfm_sysctl.debug > 0 && pfm_sysctl.debug_ovfl >0)) { printk("%s.%d: CPU%d [%d] ", __FUNCTION__, __LINE__, smp_processor_id(), current->pid); printk a; } \
255        } while (0)
256#endif
257
258/*
259 * 64-bit software counter structure
260 *
261 * the next_reset_type is applied to the next call to pfm_reset_regs()
262 */
263typedef struct {
264        unsigned long   val;            /* virtual 64bit counter value */
265        unsigned long   lval;           /* last reset value */
266        unsigned long   long_reset;     /* reset value on sampling overflow */
267        unsigned long   short_reset;    /* reset value on overflow */
268        unsigned long   reset_pmds[4];  /* which other pmds to reset when this counter overflows */
269        unsigned long   smpl_pmds[4];   /* which pmds are accessed when counter overflow */
270        unsigned long   seed;           /* seed for random-number generator */
271        unsigned long   mask;           /* mask for random-number generator */
272        unsigned int    flags;          /* notify/do not notify */
273        unsigned long   eventid;        /* overflow event identifier */
274} pfm_counter_t;
275
276/*
277 * context flags
278 */
279typedef struct {
280        unsigned int block:1;           /* when 1, task will blocked on user notifications */
281        unsigned int system:1;          /* do system wide monitoring */
282        unsigned int using_dbreg:1;     /* using range restrictions (debug registers) */
283        unsigned int is_sampling:1;     /* true if using a custom format */
284        unsigned int excl_idle:1;       /* exclude idle task in system wide session */
285        unsigned int going_zombie:1;    /* context is zombie (MASKED+blocking) */
286        unsigned int trap_reason:2;     /* reason for going into pfm_handle_work() */
287        unsigned int no_msg:1;          /* no message sent on overflow */
288        unsigned int can_restart:1;     /* allowed to issue a PFM_RESTART */
289        unsigned int reserved:22;
290} pfm_context_flags_t;
291
292#define PFM_TRAP_REASON_NONE            0x0     /* default value */
293#define PFM_TRAP_REASON_BLOCK           0x1     /* we need to block on overflow */
294#define PFM_TRAP_REASON_RESET           0x2     /* we need to reset PMDs */
295
296
297/*
298 * perfmon context: encapsulates all the state of a monitoring session
299 */
300
301typedef struct pfm_context {
302        spinlock_t              ctx_lock;               /* context protection */
303
304        pfm_context_flags_t     ctx_flags;              /* bitmask of flags  (block reason incl.) */
305        unsigned int            ctx_state;              /* state: active/inactive (no bitfield) */
306
307        struct task_struct      *ctx_task;              /* task to which context is attached */
308
309        unsigned long           ctx_ovfl_regs[4];       /* which registers overflowed (notification) */
310
311        struct completion       ctx_restart_done;       /* use for blocking notification mode */
312
313        unsigned long           ctx_used_pmds[4];       /* bitmask of PMD used            */
314        unsigned long           ctx_all_pmds[4];        /* bitmask of all accessible PMDs */
315        unsigned long           ctx_reload_pmds[4];     /* bitmask of force reload PMD on ctxsw in */
316
317        unsigned long           ctx_all_pmcs[4];        /* bitmask of all accessible PMCs */
318        unsigned long           ctx_reload_pmcs[4];     /* bitmask of force reload PMC on ctxsw in */
319        unsigned long           ctx_used_monitors[4];   /* bitmask of monitor PMC being used */
320
321        unsigned long           ctx_pmcs[IA64_NUM_PMC_REGS];    /*  saved copies of PMC values */
322
323        unsigned int            ctx_used_ibrs[1];               /* bitmask of used IBR (speedup ctxsw in) */
324        unsigned int            ctx_used_dbrs[1];               /* bitmask of used DBR (speedup ctxsw in) */
325        unsigned long           ctx_dbrs[IA64_NUM_DBG_REGS];    /* DBR values (cache) when not loaded */
326        unsigned long           ctx_ibrs[IA64_NUM_DBG_REGS];    /* IBR values (cache) when not loaded */
327
328        pfm_counter_t           ctx_pmds[IA64_NUM_PMD_REGS]; /* software state for PMDS */
329
330        u64                     ctx_saved_psr_up;       /* only contains psr.up value */
331
332        unsigned long           ctx_last_activation;    /* context last activation number for last_cpu */
333        unsigned int            ctx_last_cpu;           /* CPU id of current or last CPU used (SMP only) */
334        unsigned int            ctx_cpu;                /* cpu to which perfmon is applied (system wide) */
335
336        int                     ctx_fd;                 /* file descriptor used my this context */
337        pfm_ovfl_arg_t          ctx_ovfl_arg;           /* argument to custom buffer format handler */
338
339        pfm_buffer_fmt_t        *ctx_buf_fmt;           /* buffer format callbacks */
340        void                    *ctx_smpl_hdr;          /* points to sampling buffer header kernel vaddr */
341        unsigned long           ctx_smpl_size;          /* size of sampling buffer */
342        void                    *ctx_smpl_vaddr;        /* user level virtual address of smpl buffer */
343
344        wait_queue_head_t       ctx_msgq_wait;
345        pfm_msg_t               ctx_msgq[PFM_MAX_MSGS];
346        int                     ctx_msgq_head;
347        int                     ctx_msgq_tail;
348        struct fasync_struct    *ctx_async_queue;
349
350        wait_queue_head_t       ctx_zombieq;            /* termination cleanup wait queue */
351} pfm_context_t;
352
353/*
354 * magic number used to verify that structure is really
355 * a perfmon context
356 */
357#define PFM_IS_FILE(f)          ((f)->f_op == &pfm_file_ops)
358
359#define PFM_GET_CTX(t)          ((pfm_context_t *)(t)->thread.pfm_context)
360
361#ifdef CONFIG_SMP
362#define SET_LAST_CPU(ctx, v)    (ctx)->ctx_last_cpu = (v)
363#define GET_LAST_CPU(ctx)       (ctx)->ctx_last_cpu
364#else
365#define SET_LAST_CPU(ctx, v)    do {} while(0)
366#define GET_LAST_CPU(ctx)       do {} while(0)
367#endif
368
369
370#define ctx_fl_block            ctx_flags.block
371#define ctx_fl_system           ctx_flags.system
372#define ctx_fl_using_dbreg      ctx_flags.using_dbreg
373#define ctx_fl_is_sampling      ctx_flags.is_sampling
374#define ctx_fl_excl_idle        ctx_flags.excl_idle
375#define ctx_fl_going_zombie     ctx_flags.going_zombie
376#define ctx_fl_trap_reason      ctx_flags.trap_reason
377#define ctx_fl_no_msg           ctx_flags.no_msg
378#define ctx_fl_can_restart      ctx_flags.can_restart
379
380#define PFM_SET_WORK_PENDING(t, v)      do { (t)->thread.pfm_needs_checking = v; } while(0);
381#define PFM_GET_WORK_PENDING(t)         (t)->thread.pfm_needs_checking
382
383/*
384 * global information about all sessions
385 * mostly used to synchronize between system wide and per-process
386 */
387typedef struct {
388        spinlock_t              pfs_lock;                  /* lock the structure */
389
390        unsigned int            pfs_task_sessions;         /* number of per task sessions */
391        unsigned int            pfs_sys_sessions;          /* number of per system wide sessions */
392        unsigned int            pfs_sys_use_dbregs;        /* incremented when a system wide session uses debug regs */
393        unsigned int            pfs_ptrace_use_dbregs;     /* incremented when a process uses debug regs */
394        struct task_struct      *pfs_sys_session[NR_CPUS]; /* point to task owning a system-wide session */
395} pfm_session_t;
396
397/*
398 * information about a PMC or PMD.
399 * dep_pmd[]: a bitmask of dependent PMD registers
400 * dep_pmc[]: a bitmask of dependent PMC registers
401 */
402typedef int (*pfm_reg_check_t)(struct task_struct *task, pfm_context_t *ctx, unsigned int cnum, unsigned long *val, struct pt_regs *regs);
403typedef struct {
404        unsigned int            type;
405        int                     pm_pos;
406        unsigned long           default_value;  /* power-on default value */
407        unsigned long           reserved_mask;  /* bitmask of reserved bits */
408        pfm_reg_check_t         read_check;
409        pfm_reg_check_t         write_check;
410        unsigned long           dep_pmd[4];
411        unsigned long           dep_pmc[4];
412} pfm_reg_desc_t;
413
414/* assume cnum is a valid monitor */
415#define PMC_PM(cnum, val)       (((val) >> (pmu_conf->pmc_desc[cnum].pm_pos)) & 0x1)
416
417/*
418 * This structure is initialized at boot time and contains
419 * a description of the PMU main characteristics.
420 *
421 * If the probe function is defined, detection is based
422 * on its return value:
423 *      - 0 means recognized PMU
424 *      - anything else means not supported
425 * When the probe function is not defined, then the pmu_family field
426 * is used and it must match the host CPU family such that:
427 *      - cpu->family & config->pmu_family != 0
428 */
429typedef struct {
430        unsigned long  ovfl_val;        /* overflow value for counters */
431
432        pfm_reg_desc_t *pmc_desc;       /* detailed PMC register dependencies descriptions */
433        pfm_reg_desc_t *pmd_desc;       /* detailed PMD register dependencies descriptions */
434
435        unsigned int   num_pmcs;        /* number of PMCS: computed at init time */
436        unsigned int   num_pmds;        /* number of PMDS: computed at init time */
437        unsigned long  impl_pmcs[4];    /* bitmask of implemented PMCS */
438        unsigned long  impl_pmds[4];    /* bitmask of implemented PMDS */
439
440        char          *pmu_name;        /* PMU family name */
441        unsigned int  pmu_family;       /* cpuid family pattern used to identify pmu */
442        unsigned int  flags;            /* pmu specific flags */
443        unsigned int  num_ibrs;         /* number of IBRS: computed at init time */
444        unsigned int  num_dbrs;         /* number of DBRS: computed at init time */
445        unsigned int  num_counters;     /* PMC/PMD counting pairs : computed at init time */
446        int           (*probe)(void);   /* customized probe routine */
447        unsigned int  use_rr_dbregs:1;  /* set if debug registers used for range restriction */
448} pmu_config_t;
449/*
450 * PMU specific flags
451 */
452#define PFM_PMU_IRQ_RESEND      1       /* PMU needs explicit IRQ resend */
453
454/*
455 * debug register related type definitions
456 */
457typedef struct {
458        unsigned long ibr_mask:56;
459        unsigned long ibr_plm:4;
460        unsigned long ibr_ig:3;
461        unsigned long ibr_x:1;
462} ibr_mask_reg_t;
463
464typedef struct {
465        unsigned long dbr_mask:56;
466        unsigned long dbr_plm:4;
467        unsigned long dbr_ig:2;
468        unsigned long dbr_w:1;
469        unsigned long dbr_r:1;
470} dbr_mask_reg_t;
471
472typedef union {
473        unsigned long  val;
474        ibr_mask_reg_t ibr;
475        dbr_mask_reg_t dbr;
476} dbreg_t;
477
478
479/*
480 * perfmon command descriptions
481 */
482typedef struct {
483        int             (*cmd_func)(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs);
484        char            *cmd_name;
485        int             cmd_flags;
486        unsigned int    cmd_narg;
487        size_t          cmd_argsize;
488        int             (*cmd_getsize)(void *arg, size_t *sz);
489} pfm_cmd_desc_t;
490
491#define PFM_CMD_FD              0x01    /* command requires a file descriptor */
492#define PFM_CMD_ARG_READ        0x02    /* command must read argument(s) */
493#define PFM_CMD_ARG_RW          0x04    /* command must read/write argument(s) */
494#define PFM_CMD_STOP            0x08    /* command does not work on zombie context */
495
496
497#define PFM_CMD_NAME(cmd)       pfm_cmd_tab[(cmd)].cmd_name
498#define PFM_CMD_READ_ARG(cmd)   (pfm_cmd_tab[(cmd)].cmd_flags & PFM_CMD_ARG_READ)
499#define PFM_CMD_RW_ARG(cmd)     (pfm_cmd_tab[(cmd)].cmd_flags & PFM_CMD_ARG_RW)
500#define PFM_CMD_USE_FD(cmd)     (pfm_cmd_tab[(cmd)].cmd_flags & PFM_CMD_FD)
501#define PFM_CMD_STOPPED(cmd)    (pfm_cmd_tab[(cmd)].cmd_flags & PFM_CMD_STOP)
502
503#define PFM_CMD_ARG_MANY        -1 /* cannot be zero */
504
505typedef struct {
506        unsigned long pfm_spurious_ovfl_intr_count;     /* keep track of spurious ovfl interrupts */
507        unsigned long pfm_replay_ovfl_intr_count;       /* keep track of replayed ovfl interrupts */
508        unsigned long pfm_ovfl_intr_count;              /* keep track of ovfl interrupts */
509        unsigned long pfm_ovfl_intr_cycles;             /* cycles spent processing ovfl interrupts */
510        unsigned long pfm_ovfl_intr_cycles_min;         /* min cycles spent processing ovfl interrupts */
511        unsigned long pfm_ovfl_intr_cycles_max;         /* max cycles spent processing ovfl interrupts */
512        unsigned long pfm_smpl_handler_calls;
513        unsigned long pfm_smpl_handler_cycles;
514        char pad[SMP_CACHE_BYTES] ____cacheline_aligned;
515} pfm_stats_t;
516
517/*
518 * perfmon internal variables
519 */
520static pfm_stats_t              pfm_stats[NR_CPUS];
521static pfm_session_t            pfm_sessions;   /* global sessions information */
522
523static DEFINE_SPINLOCK(pfm_alt_install_check);
524static pfm_intr_handler_desc_t  *pfm_alt_intr_handler;
525
526static struct proc_dir_entry    *perfmon_dir;
527static pfm_uuid_t               pfm_null_uuid = {0,};
528
529static spinlock_t               pfm_buffer_fmt_lock;
530static LIST_HEAD(pfm_buffer_fmt_list);
531
532static pmu_config_t             *pmu_conf;
533
534/* sysctl() controls */
535pfm_sysctl_t pfm_sysctl;
536EXPORT_SYMBOL(pfm_sysctl);
537
538static ctl_table pfm_ctl_table[]={
539        {1, "debug", &pfm_sysctl.debug, sizeof(int), 0666, NULL, &proc_dointvec, NULL,},
540        {2, "debug_ovfl", &pfm_sysctl.debug_ovfl, sizeof(int), 0666, NULL, &proc_dointvec, NULL,},
541        {3, "fastctxsw", &pfm_sysctl.fastctxsw, sizeof(int), 0600, NULL, &proc_dointvec, NULL,},
542        {4, "expert_mode", &pfm_sysctl.expert_mode, sizeof(int), 0600, NULL, &proc_dointvec, NULL,},
543        { 0, },
544};
545static ctl_table pfm_sysctl_dir[] = {
546        {1, "perfmon", NULL, 0, 0755, pfm_ctl_table, },
547        {0,},
548};
549static ctl_table pfm_sysctl_root[] = {
550        {1, "kernel", NULL, 0, 0755, pfm_sysctl_dir, },
551        {0,},
552};
553static struct ctl_table_header *pfm_sysctl_header;
554
555static int pfm_context_unload(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs);
556
557#define pfm_get_cpu_var(v)              __ia64_per_cpu_var(v)
558#define pfm_get_cpu_data(a,b)           per_cpu(a, b)
559
560static inline void
561pfm_put_task(struct task_struct *task)
562{
563        if (task != current) put_task_struct(task);
564}
565
566static inline void
567pfm_set_task_notify(struct task_struct *task)
568{
569        struct thread_info *info;
570
571        info = (struct thread_info *) ((char *) task + IA64_TASK_SIZE);
572        set_bit(TIF_NOTIFY_RESUME, &info->flags);
573}
574
575static inline void
576pfm_clear_task_notify(void)
577{
578        clear_thread_flag(TIF_NOTIFY_RESUME);
579}
580
581static inline void
582pfm_reserve_page(unsigned long a)
583{
584        SetPageReserved(vmalloc_to_page((void *)a));
585}
586static inline void
587pfm_unreserve_page(unsigned long a)
588{
589        ClearPageReserved(vmalloc_to_page((void*)a));
590}
591
592static inline unsigned long
593pfm_protect_ctx_ctxsw(pfm_context_t *x)
594{
595        spin_lock(&(x)->ctx_lock);
596        return 0UL;
597}
598
599static inline void
600pfm_unprotect_ctx_ctxsw(pfm_context_t *x, unsigned long f)
601{
602        spin_unlock(&(x)->ctx_lock);
603}
604
605static inline unsigned int
606pfm_do_munmap(struct mm_struct *mm, unsigned long addr, size_t len, int acct)
607{
608        return do_munmap(mm, addr, len);
609}
610
611static inline unsigned long 
612pfm_get_unmapped_area(struct file *file, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags, unsigned long exec)
613{
614        return get_unmapped_area(file, addr, len, pgoff, flags);
615}
616
617
618static int
619pfmfs_get_sb(struct file_system_type *fs_type, int flags, const char *dev_name, void *data,
620             struct vfsmount *mnt)
621{
622        return get_sb_pseudo(fs_type, "pfm:", NULL, PFMFS_MAGIC, mnt);
623}
624
625static struct file_system_type pfm_fs_type = {
626        .name     = "pfmfs",
627        .get_sb   = pfmfs_get_sb,
628        .kill_sb  = kill_anon_super,
629};
630
631DEFINE_PER_CPU(unsigned long, pfm_syst_info);
632DEFINE_PER_CPU(struct task_struct *, pmu_owner);
633DEFINE_PER_CPU(pfm_context_t  *, pmu_ctx);
634DEFINE_PER_CPU(unsigned long, pmu_activation_number);
635EXPORT_PER_CPU_SYMBOL_GPL(pfm_syst_info);
636
637
638/* forward declaration */
639static struct file_operations pfm_file_ops;
640
641/*
642 * forward declarations
643 */
644#ifndef CONFIG_SMP
645static void pfm_lazy_save_regs (struct task_struct *ta);
646#endif
647
648void dump_pmu_state(const char *);
649static int pfm_write_ibr_dbr(int mode, pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs);
650
651#include "perfmon_itanium.h"
652#include "perfmon_mckinley.h"
653#include "perfmon_montecito.h"
654#include "perfmon_generic.h"
655
656static pmu_config_t *pmu_confs[]={
657        &pmu_conf_mont,
658        &pmu_conf_mck,
659        &pmu_conf_ita,
660        &pmu_conf_gen, /* must be last */
661        NULL
662};
663
664
665static int pfm_end_notify_user(pfm_context_t *ctx);
666
667static inline void
668pfm_clear_psr_pp(void)
669{
670        ia64_rsm(IA64_PSR_PP);
671        ia64_srlz_i();
672}
673
674static inline void
675pfm_set_psr_pp(void)
676{
677        ia64_ssm(IA64_PSR_PP);
678        ia64_srlz_i();
679}
680
681static inline void
682pfm_clear_psr_up(void)
683{
684        ia64_rsm(IA64_PSR_UP);
685        ia64_srlz_i();
686}
687
688static inline void
689pfm_set_psr_up(void)
690{
691        ia64_ssm(IA64_PSR_UP);
692        ia64_srlz_i();
693}
694
695static inline unsigned long
696pfm_get_psr(void)
697{
698        unsigned long tmp;
699        tmp = ia64_getreg(_IA64_REG_PSR);
700        ia64_srlz_i();
701        return tmp;
702}
703
704static inline void
705pfm_set_psr_l(unsigned long val)
706{
707        ia64_setreg(_IA64_REG_PSR_L, val);
708        ia64_srlz_i();
709}
710
711static inline void
712pfm_freeze_pmu(void)
713{
714        ia64_set_pmc(0,1UL);
715        ia64_srlz_d();
716}
717
718static inline void
719pfm_unfreeze_pmu(void)
720{
721        ia64_set_pmc(0,0UL);
722        ia64_srlz_d();
723}
724
725static inline void
726pfm_restore_ibrs(unsigned long *ibrs, unsigned int nibrs)
727{
728        int i;
729
730        for (i=0; i < nibrs; i++) {
731                ia64_set_ibr(i, ibrs[i]);
732                ia64_dv_serialize_instruction();
733        }
734        ia64_srlz_i();
735}
736
737static inline void
738pfm_restore_dbrs(unsigned long *dbrs, unsigned int ndbrs)
739{
740        int i;
741
742        for (i=0; i < ndbrs; i++) {
743                ia64_set_dbr(i, dbrs[i]);
744                ia64_dv_serialize_data();
745        }
746        ia64_srlz_d();
747}
748
749/*
750 * PMD[i] must be a counter. no check is made
751 */
752static inline unsigned long
753pfm_read_soft_counter(pfm_context_t *ctx, int i)
754{
755        return ctx->ctx_pmds[i].val + (ia64_get_pmd(i) & pmu_conf->ovfl_val);
756}
757
758/*
759 * PMD[i] must be a counter. no check is made
760 */
761static inline void
762pfm_write_soft_counter(pfm_context_t *ctx, int i, unsigned long val)
763{
764        unsigned long ovfl_val = pmu_conf->ovfl_val;
765
766        ctx->ctx_pmds[i].val = val  & ~ovfl_val;
767        /*
768         * writing to unimplemented part is ignore, so we do not need to
769         * mask off top part
770         */
771        ia64_set_pmd(i, val & ovfl_val);
772}
773
774static pfm_msg_t *
775pfm_get_new_msg(pfm_context_t *ctx)
776{
777        int idx, next;
778
779        next = (ctx->ctx_msgq_tail+1) % PFM_MAX_MSGS;
780
781        DPRINT(("ctx_fd=%p head=%d tail=%d\n", ctx, ctx->ctx_msgq_head, ctx->ctx_msgq_tail));
782        if (next == ctx->ctx_msgq_head) return NULL;
783
784        idx =   ctx->ctx_msgq_tail;
785        ctx->ctx_msgq_tail = next;
786
787        DPRINT(("ctx=%p head=%d tail=%d msg=%d\n", ctx, ctx->ctx_msgq_head, ctx->ctx_msgq_tail, idx));
788
789        return ctx->ctx_msgq+idx;
790}
791
792static pfm_msg_t *
793pfm_get_next_msg(pfm_context_t *ctx)
794{
795        pfm_msg_t *msg;
796
797        DPRINT(("ctx=%p head=%d tail=%d\n", ctx, ctx->ctx_msgq_head, ctx->ctx_msgq_tail));
798
799        if (PFM_CTXQ_EMPTY(ctx)) return NULL;
800
801        /*
802         * get oldest message
803         */
804        msg = ctx->ctx_msgq+ctx->ctx_msgq_head;
805
806        /*
807         * and move forward
808         */
809        ctx->ctx_msgq_head = (ctx->ctx_msgq_head+1) % PFM_MAX_MSGS;
810
811        DPRINT(("ctx=%p head=%d tail=%d type=%d\n", ctx, ctx->ctx_msgq_head, ctx->ctx_msgq_tail, msg->pfm_gen_msg.msg_type));
812
813        return msg;
814}
815
816static void
817pfm_reset_msgq(pfm_context_t *ctx)
818{
819        ctx->ctx_msgq_head = ctx->ctx_msgq_tail = 0;
820        DPRINT(("ctx=%p msgq reset\n", ctx));
821}
822
823static void *
824pfm_rvmalloc(unsigned long size)
825{
826        void *mem;
827        unsigned long addr;
828
829        size = PAGE_ALIGN(size);
830        mem  = vmalloc(size);
831        if (mem) {
832                //printk("perfmon: CPU%d pfm_rvmalloc(%ld)=%p\n", smp_processor_id(), size, mem);
833                memset(mem, 0, size);
834                addr = (unsigned long)mem;
835                while (size > 0) {
836                        pfm_reserve_page(addr);
837                        addr+=PAGE_SIZE;
838                        size-=PAGE_SIZE;
839                }
840        }
841        return mem;
842}
843
844static void
845pfm_rvfree(void *mem, unsigned long size)
846{
847        unsigned long addr;
848
849        if (mem) {
850                DPRINT(("freeing physical buffer @%p size=%lu\n", mem, size));
851                addr = (unsigned long) mem;
852                while ((long) size > 0) {
853                        pfm_unreserve_page(addr);
854                        addr+=PAGE_SIZE;
855                        size-=PAGE_SIZE;
856                }
857                vfree(mem);
858        }
859        return;
860}
861
862static pfm_context_t *
863pfm_context_alloc(void)
864{
865        pfm_context_t *ctx;
866
867        /*
868         * allocate context descriptor
869         * must be able to free with interrupts disabled
870         */
871        ctx = kmalloc(sizeof(pfm_context_t), GFP_KERNEL);
872        if (ctx) {
873                memset(ctx, 0, sizeof(pfm_context_t));
874                DPRINT(("alloc ctx @%p\n", ctx));
875        }
876        return ctx;
877}
878
879static void
880pfm_context_free(pfm_context_t *ctx)
881{
882        if (ctx) {
883                DPRINT(("free ctx @%p\n", ctx));
884                kfree(ctx);
885        }
886}
887
888static void
889pfm_mask_monitoring(struct task_struct *task)
890{
891        pfm_context_t *ctx = PFM_GET_CTX(task);
892        struct thread_struct *th = &task->thread;
893        unsigned long mask, val, ovfl_mask;
894        int i;
895
896        DPRINT_ovfl(("masking monitoring for [%d]\n", task->pid));
897
898        ovfl_mask = pmu_conf->ovfl_val;
899        /*
900         * monitoring can only be masked as a result of a valid
901         * counter overflow. In UP, it means that the PMU still
902         * has an owner. Note that the owner can be different
903         * from the current task. However the PMU state belongs
904         * to the owner.
905         * In SMP, a valid overflow only happens when task is
906         * current. Therefore if we come here, we know that
907         * the PMU state belongs to the current task, therefore
908         * we can access the live registers.
909         *
910         * So in both cases, the live register contains the owner's
911         * state. We can ONLY touch the PMU registers and NOT the PSR.
912         *
913         * As a consequence to this call, the thread->pmds[] array
914         * contains stale information which must be ignored
915         * when context is reloaded AND monitoring is active (see
916         * pfm_restart).
917         */
918        mask = ctx->ctx_used_pmds[0];
919        for (i = 0; mask; i++, mask>>=1) {
920                /* skip non used pmds */
921                if ((mask & 0x1) == 0) continue;
922                val = ia64_get_pmd(i);
923
924                if (PMD_IS_COUNTING(i)) {
925                        /*
926                         * we rebuild the full 64 bit value of the counter
927                         */
928                        ctx->ctx_pmds[i].val += (val & ovfl_mask);
929                } else {
930                        ctx->ctx_pmds[i].val = val;
931                }
932                DPRINT_ovfl(("pmd[%d]=0x%lx hw_pmd=0x%lx\n",
933                        i,
934                        ctx->ctx_pmds[i].val,
935                        val & ovfl_mask));
936        }
937        /*
938         * mask monitoring by setting the privilege level to 0
939         * we cannot use psr.pp/psr.up for this, it is controlled by
940         * the user
941         *
942         * if task is current, modify actual registers, otherwise modify
943         * thread save state, i.e., what will be restored in pfm_load_regs()
944         */
945        mask = ctx->ctx_used_monitors[0] >> PMU_FIRST_COUNTER;
946        for(i= PMU_FIRST_COUNTER; mask; i++, mask>>=1) {
947                if ((mask & 0x1) == 0UL) continue;
948                ia64_set_pmc(i, th->pmcs[i] & ~0xfUL);
949                th->pmcs[i] &= ~0xfUL;
950                DPRINT_ovfl(("pmc[%d]=0x%lx\n", i, th->pmcs[i]));
951        }
952        /*
953         * make all of this visible
954         */
955        ia64_srlz_d();
956}
957
958/*
959 * must always be done with task == current
960 *
961 * context must be in MASKED state when calling
962 */
963static void
964pfm_restore_monitoring(struct task_struct *task)
965{
966        pfm_context_t *ctx = PFM_GET_CTX(task);
967        struct thread_struct *th = &task->thread;
968        unsigned long mask, ovfl_mask;
969        unsigned long psr, val;
970        int i, is_system;
971
972        is_system = ctx->ctx_fl_system;
973        ovfl_mask = pmu_conf->ovfl_val;
974
975        if (task != current) {
976                printk(KERN_ERR "perfmon.%d: invalid task[%d] current[%d]\n", __LINE__, task->pid, current->pid);
977                return;
978        }
979        if (ctx->ctx_state != PFM_CTX_MASKED) {
980                printk(KERN_ERR "perfmon.%d: task[%d] current[%d] invalid state=%d\n", __LINE__,
981                        task->pid, current->pid, ctx->ctx_state);
982                return;
983        }
984        psr = pfm_get_psr();
985        /*
986         * monitoring is masked via the PMC.
987         * As we restore their value, we do not want each counter to
988         * restart right away. We stop monitoring using the PSR,
989         * restore the PMC (and PMD) and then re-establish the psr
990         * as it was. Note that there can be no pending overflow at
991         * this point, because monitoring was MASKED.
992         *
993         * system-wide session are pinned and self-monitoring
994         */
995        if (is_system && (PFM_CPUINFO_GET() & PFM_CPUINFO_DCR_PP)) {
996                /* disable dcr pp */
997                ia64_setreg(_IA64_REG_CR_DCR, ia64_getreg(_IA64_REG_CR_DCR) & ~IA64_DCR_PP);
998                pfm_clear_psr_pp();
999        } else {
1000                pfm_clear_psr_up();
1001        }
1002        /*
1003         * first, we restore the PMD
1004         */
1005        mask = ctx->ctx_used_pmds[0];
1006        for (i = 0; mask; i++, mask>>=1) {
1007                /* skip non used pmds */
1008                if ((mask & 0x1) == 0) continue;
1009
1010                if (PMD_IS_COUNTING(i)) {
1011                        /*
1012                         * we split the 64bit value according to
1013                         * counter width
1014                         */
1015                        val = ctx->ctx_pmds[i].val & ovfl_mask;
1016                        ctx->ctx_pmds[i].val &= ~ovfl_mask;
1017                } else {
1018                        val = ctx->ctx_pmds[i].val;
1019                }
1020                ia64_set_pmd(i, val);
1021
1022                DPRINT(("pmd[%d]=0x%lx hw_pmd=0x%lx\n",
1023                        i,
1024                        ctx->ctx_pmds[i].val,
1025                        val));
1026        }
1027        /*
1028         * restore the PMCs
1029         */
1030        mask = ctx->ctx_used_monitors[0] >> PMU_FIRST_COUNTER;
1031        for(i= PMU_FIRST_COUNTER; mask; i++, mask>>=1) {
1032                if ((mask & 0x1) == 0UL) continue;
1033                th->pmcs[i] = ctx->ctx_pmcs[i];
1034                ia64_set_pmc(i, th->pmcs[i]);
1035                DPRINT(("[%d] pmc[%d]=0x%lx\n", task->pid, i, th->pmcs[i]));
1036        }
1037        ia64_srlz_d();
1038
1039        /*
1040         * must restore DBR/IBR because could be modified while masked
1041         * XXX: need to optimize
1042         */
1043        if (ctx->ctx_fl_using_dbreg) {
1044                pfm_restore_ibrs(ctx->ctx_ibrs, pmu_conf->num_ibrs);
1045                pfm_restore_dbrs(ctx->ctx_dbrs, pmu_conf->num_dbrs);
1046        }
1047
1048        /*
1049         * now restore PSR
1050         */
1051        if (is_system && (PFM_CPUINFO_GET() & PFM_CPUINFO_DCR_PP)) {
1052                /* enable dcr pp */
1053                ia64_setreg(_IA64_REG_CR_DCR, ia64_getreg(_IA64_REG_CR_DCR) | IA64_DCR_PP);
1054                ia64_srlz_i();
1055        }
1056        pfm_set_psr_l(psr);
1057}
1058
1059static inline void
1060pfm_save_pmds(unsigned long *pmds, unsigned long mask)
1061{
1062        int i;
1063
1064        ia64_srlz_d();
1065
1066        for (i=0; mask; i++, mask>>=1) {
1067                if (mask & 0x1) pmds[i] = ia64_get_pmd(i);
1068        }
1069}
1070
1071/*
1072 * reload from thread state (used for ctxw only)
1073 */
1074static inline void
1075pfm_restore_pmds(unsigned long *pmds, unsigned long mask)
1076{
1077        int i;
1078        unsigned long val, ovfl_val = pmu_conf->ovfl_val;
1079
1080        for (i=0; mask; i++, mask>>=1) {
1081                if ((mask & 0x1) == 0) continue;
1082                val = PMD_IS_COUNTING(i) ? pmds[i] & ovfl_val : pmds[i];
1083                ia64_set_pmd(i, val);
1084        }
1085        ia64_srlz_d();
1086}
1087
1088/*
1089 * propagate PMD from context to thread-state
1090 */
1091static inline void
1092pfm_copy_pmds(struct task_struct *task, pfm_context_t *ctx)
1093{
1094        struct thread_struct *thread = &task->thread;
1095        unsigned long ovfl_val = pmu_conf->ovfl_val;
1096        unsigned long mask = ctx->ctx_all_pmds[0];
1097        unsigned long val;
1098        int i;
1099
1100        DPRINT(("mask=0x%lx\n", mask));
1101
1102        for (i=0; mask; i++, mask>>=1) {
1103
1104                val = ctx->ctx_pmds[i].val;
1105
1106                /*
1107                 * We break up the 64 bit value into 2 pieces
1108                 * the lower bits go to the machine state in the
1109                 * thread (will be reloaded on ctxsw in).
1110                 * The upper part stays in the soft-counter.
1111                 */
1112                if (PMD_IS_COUNTING(i)) {
1113                        ctx->ctx_pmds[i].val = val & ~ovfl_val;
1114                         val &= ovfl_val;
1115                }
1116                thread->pmds[i] = val;
1117
1118                DPRINT(("pmd[%d]=0x%lx soft_val=0x%lx\n",
1119                        i,
1120                        thread->pmds[i],
1121                        ctx->ctx_pmds[i].val));
1122        }
1123}
1124
1125/*
1126 * propagate PMC from context to thread-state
1127 */
1128static inline void
1129pfm_copy_pmcs(struct task_struct *task, pfm_context_t *ctx)
1130{
1131        struct thread_struct *thread = &task->thread;
1132        unsigned long mask = ctx->ctx_all_pmcs[0];
1133        int i;
1134
1135        DPRINT(("mask=0x%lx\n", mask));
1136
1137        for (i=0; mask; i++, mask>>=1) {
1138                /* masking 0 with ovfl_val yields 0 */
1139                thread->pmcs[i] = ctx->ctx_pmcs[i];
1140                DPRINT(("pmc[%d]=0x%lx\n", i, thread->pmcs[i]));
1141        }
1142}
1143
1144
1145
1146static inline void
1147pfm_restore_pmcs(unsigned long *pmcs, unsigned long mask)
1148{
1149        int i;
1150
1151        for (i=0; mask; i++, mask>>=1) {
1152                if ((mask & 0x1) == 0) continue;
1153                ia64_set_pmc(i, pmcs[i]);
1154        }
1155        ia64_srlz_d();
1156}
1157
1158static inline int
1159pfm_uuid_cmp(pfm_uuid_t a, pfm_uuid_t b)
1160{
1161        return memcmp(a, b, sizeof(pfm_uuid_t));
1162}
1163
1164static inline int
1165pfm_buf_fmt_exit(pfm_buffer_fmt_t *fmt, struct task_struct *task, void *buf, struct pt_regs *regs)
1166{
1167        int ret = 0;
1168        if (fmt->fmt_exit) ret = (*fmt->fmt_exit)(task, buf, regs);
1169        return ret;
1170}
1171
1172static inline int
1173pfm_buf_fmt_getsize(pfm_buffer_fmt_t *fmt, struct task_struct *task, unsigned int flags, int cpu, void *arg, unsigned long *size)
1174{
1175        int ret = 0;
1176        if (fmt->fmt_getsize) ret = (*fmt->fmt_getsize)(task, flags, cpu, arg, size);
1177        return ret;
1178}
1179
1180
1181static inline int
1182pfm_buf_fmt_validate(pfm_buffer_fmt_t *fmt, struct task_struct *task, unsigned int flags,
1183                     int cpu, void *arg)
1184{
1185        int ret = 0;
1186        if (fmt->fmt_validate) ret = (*fmt->fmt_validate)(task, flags, cpu, arg);
1187        return ret;
1188}
1189
1190static inline int
1191pfm_buf_fmt_init(pfm_buffer_fmt_t *fmt, struct task_struct *task, void *buf, unsigned int flags,
1192                     int cpu, void *arg)
1193{
1194        int ret = 0;
1195        if (fmt->fmt_init) ret = (*fmt->fmt_init)(task, buf, flags, cpu, arg);
1196        return ret;
1197}
1198
1199static inline int
1200pfm_buf_fmt_restart(pfm_buffer_fmt_t *fmt, struct task_struct *task, pfm_ovfl_ctrl_t *ctrl, void *buf, struct pt_regs *regs)
1201{
1202        int ret = 0;
1203        if (fmt->fmt_restart) ret = (*fmt->fmt_restart)(task, ctrl, buf, regs);
1204        return ret;
1205}
1206
1207static inline int
1208pfm_buf_fmt_restart_active(pfm_buffer_fmt_t *fmt, struct task_struct *task, pfm_ovfl_ctrl_t *ctrl, void *buf, struct pt_regs *regs)
1209{
1210        int ret = 0;
1211        if (fmt->fmt_restart_active) ret = (*fmt->fmt_restart_active)(task, ctrl, buf, regs);
1212        return ret;
1213}
1214
1215static pfm_buffer_fmt_t *
1216__pfm_find_buffer_fmt(pfm_uuid_t uuid)
1217{
1218        struct list_head * pos;
1219        pfm_buffer_fmt_t * entry;
1220
1221        list_for_each(pos, &pfm_buffer_fmt_list) {
1222                entry = list_entry(pos, pfm_buffer_fmt_t, fmt_list);
1223                if (pfm_uuid_cmp(uuid, entry->fmt_uuid) == 0)
1224                        return entry;
1225        }
1226        return NULL;
1227}
1228 
1229/*
1230 * find a buffer format based on its uuid
1231 */
1232static pfm_buffer_fmt_t *
1233pfm_find_buffer_fmt(pfm_uuid_t uuid)
1234{
1235        pfm_buffer_fmt_t * fmt;
1236        spin_lock(&pfm_buffer_fmt_lock);
1237        fmt = __pfm_find_buffer_fmt(uuid);
1238        spin_unlock(&pfm_buffer_fmt_lock);
1239        return fmt;
1240}
1241 
1242int
1243pfm_register_buffer_fmt(pfm_buffer_fmt_t *fmt)
1244{
1245        int ret = 0;
1246
1247        /* some sanity checks */
1248        if (fmt == NULL || fmt->fmt_name == NULL) return -EINVAL;
1249
1250        /* we need at least a handler */
1251        if (fmt->fmt_handler == NULL) return -EINVAL;
1252
1253        /*
1254         * XXX: need check validity of fmt_arg_size
1255         */
1256
1257        spin_lock(&pfm_buffer_fmt_lock);
1258
1259        if (__pfm_find_buffer_fmt(fmt->fmt_uuid)) {
1260                printk(KERN_ERR "perfmon: duplicate sampling format: %s\n", fmt->fmt_name);
1261                ret = -EBUSY;
1262                goto out;
1263        } 
1264        list_add(&fmt->fmt_list, &pfm_buffer_fmt_list);
1265        printk(KERN_INFO "perfmon: added sampling format %s\n", fmt->fmt_name);
1266
1267out:
1268        spin_unlock(&pfm_buffer_fmt_lock);
1269        return ret;
1270}
1271EXPORT_SYMBOL(pfm_register_buffer_fmt);
1272
1273int
1274pfm_unregister_buffer_fmt(pfm_uuid_t uuid)
1275{
1276        pfm_buffer_fmt_t *fmt;
1277        int ret = 0;
1278
1279        spin_lock(&pfm_buffer_fmt_lock);
1280
1281        fmt = __pfm_find_buffer_fmt(uuid);
1282        if (!fmt) {
1283                printk(KERN_ERR "perfmon: cannot unregister format, not found\n");
1284                ret = -EINVAL;
1285                goto out;
1286        }
1287        list_del_init(&fmt->fmt_list);
1288        printk(KERN_INFO "perfmon: removed sampling format: %s\n", fmt->fmt_name);
1289
1290out:
1291        spin_unlock(&pfm_buffer_fmt_lock);
1292        return ret;
1293
1294}
1295EXPORT_SYMBOL(pfm_unregister_buffer_fmt);
1296
1297extern void update_pal_halt_status(int);
1298
1299static int
1300pfm_reserve_session(struct task_struct *task, int is_syswide, unsigned int cpu)
1301{
1302        unsigned long flags;
1303        /*
1304         * validy checks on cpu_mask have been done upstream
1305         */
1306        LOCK_PFS(flags);
1307
1308        DPRINT(("in sys_sessions=%u task_sessions=%u dbregs=%u syswide=%d cpu=%u\n",
1309                pfm_sessions.pfs_sys_sessions,
1310                pfm_sessions.pfs_task_sessions,
1311                pfm_sessions.pfs_sys_use_dbregs,
1312                is_syswide,
1313                cpu));
1314
1315        if (is_syswide) {
1316                /*
1317                 * cannot mix system wide and per-task sessions
1318                 */
1319                if (pfm_sessions.pfs_task_sessions > 0UL) {
1320                        DPRINT(("system wide not possible, %u conflicting task_sessions\n",
1321                                pfm_sessions.pfs_task_sessions));
1322                        goto abort;
1323                }
1324
1325                if (pfm_sessions.pfs_sys_session[cpu]) goto error_conflict;
1326
1327                DPRINT(("reserving system wide session on CPU%u currently on CPU%u\n", cpu, smp_processor_id()));
1328
1329                pfm_sessions.pfs_sys_session[cpu] = task;
1330
1331                pfm_sessions.pfs_sys_sessions++ ;
1332
1333        } else {
1334                if (pfm_sessions.pfs_sys_sessions) goto abort;
1335                pfm_sessions.pfs_task_sessions++;
1336        }
1337
1338        DPRINT(("out sys_sessions=%u task_sessions=%u dbregs=%u syswide=%d cpu=%u\n",
1339                pfm_sessions.pfs_sys_sessions,
1340                pfm_sessions.pfs_task_sessions,
1341                pfm_sessions.pfs_sys_use_dbregs,
1342                is_syswide,
1343                cpu));
1344
1345        /*
1346         * disable default_idle() to go to PAL_HALT
1347         */
1348        update_pal_halt_status(0);
1349
1350        UNLOCK_PFS(flags);
1351
1352        return 0;
1353
1354error_conflict:
1355        DPRINT(("system wide not possible, conflicting session [%d] on CPU%d\n",
1356                pfm_sessions.pfs_sys_session[cpu]->pid,
1357                cpu));
1358abort:
1359        UNLOCK_PFS(flags);
1360
1361        return -EBUSY;
1362
1363}
1364
1365static int
1366pfm_unreserve_session(pfm_context_t *ctx, int is_syswide, unsigned int cpu)
1367{
1368        unsigned long flags;
1369        /*
1370         * validy checks on cpu_mask have been done upstream
1371         */
1372        LOCK_PFS(flags);
1373
1374        DPRINT(("in sys_sessions=%u task_sessions=%u dbregs=%u syswide=%d cpu=%u\n",
1375                pfm_sessions.pfs_sys_sessions,
1376                pfm_sessions.pfs_task_sessions,
1377                pfm_sessions.pfs_sys_use_dbregs,
1378                is_syswide,
1379                cpu));
1380
1381
1382        if (is_syswide) {
1383                pfm_sessions.pfs_sys_session[cpu] = NULL;
1384                /*
1385                 * would not work with perfmon+more than one bit in cpu_mask
1386                 */
1387                if (ctx && ctx->ctx_fl_using_dbreg) {
1388                        if (pfm_sessions.pfs_sys_use_dbregs == 0) {
1389                                printk(KERN_ERR "perfmon: invalid release for ctx %p sys_use_dbregs=0\n", ctx);
1390                        } else {
1391                                pfm_sessions.pfs_sys_use_dbregs--;
1392                        }
1393                }
1394                pfm_sessions.pfs_sys_sessions--;
1395        } else {
1396                pfm_sessions.pfs_task_sessions--;
1397        }
1398        DPRINT(("out sys_sessions=%u task_sessions=%u dbregs=%u syswide=%d cpu=%u\n",
1399                pfm_sessions.pfs_sys_sessions,
1400                pfm_sessions.pfs_task_sessions,
1401                pfm_sessions.pfs_sys_use_dbregs,
1402                is_syswide,
1403                cpu));
1404
1405        /*
1406         * if possible, enable default_idle() to go into PAL_HALT
1407         */
1408        if (pfm_sessions.pfs_task_sessions == 0 && pfm_sessions.pfs_sys_sessions == 0)
1409                update_pal_halt_status(1);
1410
1411        UNLOCK_PFS(flags);
1412
1413        return 0;
1414}
1415
1416/*
1417 * removes virtual mapping of the sampling buffer.
1418 * IMPORTANT: cannot be called with interrupts disable, e.g. inside
1419 * a PROTECT_CTX() section.
1420 */
1421static int
1422pfm_remove_smpl_mapping(struct task_struct *task, void *vaddr, unsigned long size)
1423{
1424        int r;
1425
1426        /* sanity checks */
1427        if (task->mm == NULL || size == 0UL || vaddr == NULL) {
1428                printk(KERN_ERR "perfmon: pfm_remove_smpl_mapping [%d] invalid context mm=%p\n", task->pid, task->mm);
1429                return -EINVAL;
1430        }
1431
1432        DPRINT(("smpl_vaddr=%p size=%lu\n", vaddr, size));
1433
1434        /*
1435         * does the actual unmapping
1436         */
1437        down_write(&task->mm->mmap_sem);
1438
1439        DPRINT(("down_write done smpl_vaddr=%p size=%lu\n", vaddr, size));
1440
1441        r = pfm_do_munmap(task->mm, (unsigned long)vaddr, size, 0);
1442
1443        up_write(&task->mm->mmap_sem);
1444        if (r !=0) {
1445                printk(KERN_ERR "perfmon: [%d] unable to unmap sampling buffer @%p size=%lu\n", task->pid, vaddr, size);
1446        }
1447
1448        DPRINT(("do_unmap(%p, %lu)=%d\n", vaddr, size, r));
1449
1450        return 0;
1451}
1452
1453/*
1454 * free actual physical storage used by sampling buffer
1455 */
1456#if 0
1457static int
1458pfm_free_smpl_buffer(pfm_context_t *ctx)
1459{
1460        pfm_buffer_fmt_t *fmt;
1461
1462        if (ctx->ctx_smpl_hdr == NULL) goto invalid_free;
1463
1464        /*
1465         * we won't use the buffer format anymore
1466         */
1467        fmt = ctx->ctx_buf_fmt;
1468
1469        DPRINT(("sampling buffer @%p size %lu vaddr=%p\n",
1470                ctx->ctx_smpl_hdr,
1471                ctx->ctx_smpl_size,
1472                ctx->ctx_smpl_vaddr));
1473
1474        pfm_buf_fmt_exit(fmt, current, NULL, NULL);
1475
1476        /*
1477         * free the buffer
1478         */
1479        pfm_rvfree(ctx->ctx_smpl_hdr, ctx->ctx_smpl_size);
1480
1481        ctx->ctx_smpl_hdr  = NULL;
1482        ctx->ctx_smpl_size = 0UL;
1483
1484        return 0;
1485
1486invalid_free:
1487        printk(KERN_ERR "perfmon: pfm_free_smpl_buffer [%d] no buffer\n", current->pid);
1488        return -EINVAL;
1489}
1490#endif
1491
1492static inline void
1493pfm_exit_smpl_buffer(pfm_buffer_fmt_t *fmt)
1494{
1495        if (fmt == NULL) return;
1496
1497        pfm_buf_fmt_exit(fmt, current, NULL, NULL);
1498
1499}
1500
1501/*
1502 * pfmfs should _never_ be mounted by userland - too much of security hassle,
1503 * no real gain from having the whole whorehouse mounted. So we don't need
1504 * any operations on the root directory. However, we need a non-trivial
1505 * d_name - pfm: will go nicely and kill the special-casing in procfs.
1506 */
1507static struct vfsmount *pfmfs_mnt;
1508
1509static int __init
1510init_pfm_fs(void)
1511{
1512        int err = register_filesystem(&pfm_fs_type);
1513        if (!err) {
1514                pfmfs_mnt = kern_mount(&pfm_fs_type);
1515                err = PTR_ERR(pfmfs_mnt);
1516                if (IS_ERR(pfmfs_mnt))
1517                        unregister_filesystem(&pfm_fs_type);
1518                else
1519                        err = 0;
1520        }
1521        return err;
1522}
1523
1524static void __exit
1525exit_pfm_fs(void)
1526{
1527        unregister_filesystem(&pfm_fs_type);
1528        mntput(pfmfs_mnt);
1529}
1530
1531static ssize_t
1532pfm_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)
1533{
1534        pfm_context_t *ctx;
1535        pfm_msg_t *msg;
1536        ssize_t ret;
1537        unsigned long flags;
1538        DECLARE_WAITQUEUE(wait, current);
1539        XEN_NOT_SUPPORTED_YET;
1540        if (PFM_IS_FILE(filp) == 0) {
1541                printk(KERN_ERR "perfmon: pfm_poll: bad magic [%d]\n", current->pid);
1542                return -EINVAL;
1543        }
1544
1545        ctx = (pfm_context_t *)filp->private_data;
1546        if (ctx == NULL) {
1547                printk(KERN_ERR "perfmon: pfm_read: NULL ctx [%d]\n", current->pid);
1548                return -EINVAL;
1549        }
1550
1551        /*
1552         * check even when there is no message
1553         */
1554        if (size < sizeof(pfm_msg_t)) {
1555                DPRINT(("message is too small ctx=%p (>=%ld)\n", ctx, sizeof(pfm_msg_t)));
1556                return -EINVAL;
1557        }
1558
1559        PROTECT_CTX(ctx, flags);
1560
1561        /*
1562         * put ourselves on the wait queue
1563         */
1564        add_wait_queue(&ctx->ctx_msgq_wait, &wait);
1565
1566
1567        for(;;) {
1568                /*
1569                 * check wait queue
1570                 */
1571
1572                set_current_state(TASK_INTERRUPTIBLE);
1573
1574                DPRINT(("head=%d tail=%d\n", ctx->ctx_msgq_head, ctx->ctx_msgq_tail));
1575
1576                ret = 0;
1577                if(PFM_CTXQ_EMPTY(ctx) == 0) break;
1578
1579                UNPROTECT_CTX(ctx, flags);
1580
1581                /*
1582                 * check non-blocking read
1583                 */
1584                ret = -EAGAIN;
1585                if(filp->f_flags & O_NONBLOCK) break;
1586
1587                /*
1588                 * check pending signals
1589                 */
1590                if(signal_pending(current)) {
1591                        ret = -EINTR;
1592                        break;
1593                }
1594                /*
1595                 * no message, so wait
1596                 */
1597                schedule();
1598
1599                PROTECT_CTX(ctx, flags);
1600        }
1601        DPRINT(("[%d] back to running ret=%ld\n", current->pid, ret));
1602        set_current_state(TASK_RUNNING);
1603        remove_wait_queue(&ctx->ctx_msgq_wait, &wait);
1604
1605        if (ret < 0) goto abort;
1606
1607        ret = -EINVAL;
1608        msg = pfm_get_next_msg(ctx);
1609        if (msg == NULL) {
1610                printk(KERN_ERR "perfmon: pfm_read no msg for ctx=%p [%d]\n", ctx, current->pid);
1611                goto abort_locked;
1612        }
1613
1614        DPRINT(("fd=%d type=%d\n", msg->pfm_gen_msg.msg_ctx_fd, msg->pfm_gen_msg.msg_type));
1615
1616        ret = -EFAULT;
1617        if(copy_to_user(buf, msg, sizeof(pfm_msg_t)) == 0) ret = sizeof(pfm_msg_t);
1618
1619abort_locked:
1620        UNPROTECT_CTX(ctx, flags);
1621abort:
1622        return ret;
1623}
1624
1625static ssize_t
1626pfm_write(struct file *file, const char __user *ubuf,
1627                          size_t size, loff_t *ppos)
1628{
1629        DPRINT(("pfm_write called\n"));
1630        return -EINVAL;
1631}
1632
1633static unsigned int
1634pfm_poll(struct file *filp, poll_table * wait)
1635{
1636        pfm_context_t *ctx;
1637        unsigned long flags;
1638        unsigned int mask = 0;
1639
1640        if (PFM_IS_FILE(filp) == 0) {
1641                printk(KERN_ERR "perfmon: pfm_poll: bad magic [%d]\n", current->pid);
1642                return 0;
1643        }
1644
1645        ctx = (pfm_context_t *)filp->private_data;
1646        if (ctx == NULL) {
1647                printk(KERN_ERR "perfmon: pfm_poll: NULL ctx [%d]\n", current->pid);
1648                return 0;
1649        }
1650
1651
1652        DPRINT(("pfm_poll ctx_fd=%d before poll_wait\n", ctx->ctx_fd));
1653
1654        poll_wait(filp, &ctx->ctx_msgq_wait, wait);
1655
1656        PROTECT_CTX(ctx, flags);
1657
1658        if (PFM_CTXQ_EMPTY(ctx) == 0)
1659                mask =  POLLIN | POLLRDNORM;
1660
1661        UNPROTECT_CTX(ctx, flags);
1662
1663        DPRINT(("pfm_poll ctx_fd=%d mask=0x%x\n", ctx->ctx_fd, mask));
1664
1665        return mask;
1666}
1667
1668static int
1669pfm_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
1670{
1671        DPRINT(("pfm_ioctl called\n"));
1672        return -EINVAL;
1673}
1674
1675/*
1676 * interrupt cannot be masked when coming here
1677 */
1678static inline int
1679pfm_do_fasync(int fd, struct file *filp, pfm_context_t *ctx, int on)
1680{
1681        int ret;
1682
1683        ret = fasync_helper (fd, filp, on, &ctx->ctx_async_queue);
1684
1685        DPRINT(("pfm_fasync called by [%d] on ctx_fd=%d on=%d async_queue=%p ret=%d\n",
1686                current->pid,
1687                fd,
1688                on,
1689                ctx->ctx_async_queue, ret));
1690
1691        return ret;
1692}
1693
1694static int
1695pfm_fasync(int fd, struct file *filp, int on)
1696{
1697        pfm_context_t *ctx;
1698        int ret;
1699
1700        if (PFM_IS_FILE(filp) == 0) {
1701                printk(KERN_ERR "perfmon: pfm_fasync bad magic [%d]\n", current->pid);
1702                return -EBADF;
1703        }
1704
1705        ctx = (pfm_context_t *)filp->private_data;
1706        if (ctx == NULL) {
1707                printk(KERN_ERR "perfmon: pfm_fasync NULL ctx [%d]\n", current->pid);
1708                return -EBADF;
1709        }
1710        /*
1711         * we cannot mask interrupts during this call because this may
1712         * may go to sleep if memory is not readily avalaible.
1713         *
1714         * We are protected from the conetxt disappearing by the get_fd()/put_fd()
1715         * done in caller. Serialization of this function is ensured by caller.
1716         */
1717        ret = pfm_do_fasync(fd, filp, ctx, on);
1718
1719
1720        DPRINT(("pfm_fasync called on ctx_fd=%d on=%d async_queue=%p ret=%d\n",
1721                fd,
1722                on,
1723                ctx->ctx_async_queue, ret));
1724
1725        return ret;
1726}
1727
1728#ifdef CONFIG_SMP
1729/*
1730 * this function is exclusively called from pfm_close().
1731 * The context is not protected at that time, nor are interrupts
1732 * on the remote CPU. That's necessary to avoid deadlocks.
1733 */
1734static void
1735pfm_syswide_force_stop(void *info)
1736{
1737        pfm_context_t   *ctx = (pfm_context_t *)info;
1738        struct pt_regs *regs = task_pt_regs(current);
1739        struct task_struct *owner;
1740        unsigned long flags;
1741        int ret;
1742
1743        if (ctx->ctx_cpu != smp_processor_id()) {
1744                printk(KERN_ERR "perfmon: pfm_syswide_force_stop for CPU%d  but on CPU%d\n",
1745                        ctx->ctx_cpu,
1746                        smp_processor_id());
1747                return;
1748        }
1749        owner = GET_PMU_OWNER();
1750        if (owner != ctx->ctx_task) {
1751                printk(KERN_ERR "perfmon: pfm_syswide_force_stop CPU%d unexpected owner [%d] instead of [%d]\n",
1752                        smp_processor_id(),
1753                        owner->pid, ctx->ctx_task->pid);
1754                return;
1755        }
1756        if (GET_PMU_CTX() != ctx) {
1757                printk(KERN_ERR "perfmon: pfm_syswide_force_stop CPU%d unexpected ctx %p instead of %p\n",
1758                        smp_processor_id(),
1759                        GET_PMU_CTX(), ctx);
1760                return;
1761        }
1762
1763        DPRINT(("on CPU%d forcing system wide stop for [%d]\n", smp_processor_id(), ctx->ctx_task->pid));       
1764        /*
1765         * the context is already protected in pfm_close(), we simply
1766         * need to mask interrupts to avoid a PMU interrupt race on
1767         * this CPU
1768         */
1769        local_irq_save(flags);
1770
1771        ret = pfm_context_unload(ctx, NULL, 0, regs);
1772        if (ret) {
1773                DPRINT(("context_unload returned %d\n", ret));
1774        }
1775
1776        /*
1777         * unmask interrupts, PMU interrupts are now spurious here
1778         */
1779        local_irq_restore(flags);
1780}
1781
1782static void
1783pfm_syswide_cleanup_other_cpu(pfm_context_t *ctx)
1784{
1785        int ret;
1786
1787        DPRINT(("calling CPU%d for cleanup\n", ctx->ctx_cpu));
1788        ret = smp_call_function_single(ctx->ctx_cpu, pfm_syswide_force_stop, ctx, 0, 1);
1789        DPRINT(("called CPU%d for cleanup ret=%d\n", ctx->ctx_cpu, ret));
1790}
1791#endif /* CONFIG_SMP */
1792
1793/*
1794 * called for each close(). Partially free resources.
1795 * When caller is self-monitoring, the context is unloaded.
1796 */
1797static int
1798pfm_flush(struct file *filp, fl_owner_t id)
1799{
1800        pfm_context_t *ctx;
1801        struct task_struct *task;
1802        struct pt_regs *regs;
1803        unsigned long flags;
1804        unsigned long smpl_buf_size = 0UL;
1805        void *smpl_buf_vaddr = NULL;
1806        int state, is_system;
1807
1808        if (PFM_IS_FILE(filp) == 0) {
1809                DPRINT(("bad magic for\n"));
1810                return -EBADF;
1811        }
1812
1813        ctx = (pfm_context_t *)filp->private_data;
1814        if (ctx == NULL) {
1815                printk(KERN_ERR "perfmon: pfm_flush: NULL ctx [%d]\n", current->pid);
1816                return -EBADF;
1817        }
1818
1819        /*
1820         * remove our file from the async queue, if we use this mode.
1821         * This can be done without the context being protected. We come
1822         * here when the context has become unreacheable by other tasks.
1823         *
1824         * We may still have active monitoring at this point and we may
1825         * end up in pfm_overflow_handler(). However, fasync_helper()
1826         * operates with interrupts disabled and it cleans up the
1827         * queue. If the PMU handler is called prior to entering
1828         * fasync_helper() then it will send a signal. If it is
1829         * invoked after, it will find an empty queue and no
1830         * signal will be sent. In both case, we are safe
1831         */
1832        if (filp->f_flags & FASYNC) {
1833                DPRINT(("cleaning up async_queue=%p\n", ctx->ctx_async_queue));
1834                pfm_do_fasync (-1, filp, ctx, 0);
1835        }
1836
1837        PROTECT_CTX(ctx, flags);
1838
1839        state     = ctx->ctx_state;
1840        is_system = ctx->ctx_fl_system;
1841
1842        task = PFM_CTX_TASK(ctx);
1843        regs = task_pt_regs(task);
1844
1845        DPRINT(("ctx_state=%d is_current=%d\n",
1846                state,
1847                task == current ? 1 : 0));
1848
1849        /*
1850         * if state == UNLOADED, then task is NULL
1851         */
1852
1853        /*
1854         * we must stop and unload because we are losing access to the context.
1855         */
1856        if (task == current) {
1857#ifdef CONFIG_SMP
1858                /*
1859                 * the task IS the owner but it migrated to another CPU: that's bad
1860                 * but we must handle this cleanly. Unfortunately, the kernel does
1861                 * not provide a mechanism to block migration (while the context is loaded).
1862                 *
1863                 * We need to release the resource on the ORIGINAL cpu.
1864                 */
1865                if (is_system && ctx->ctx_cpu != smp_processor_id()) {
1866
1867                        DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
1868                        /*
1869                         * keep context protected but unmask interrupt for IPI
1870                         */
1871                        local_irq_restore(flags);
1872
1873                        pfm_syswide_cleanup_other_cpu(ctx);
1874
1875                        /*
1876                         * restore interrupt masking
1877                         */
1878                        local_irq_save(flags);
1879
1880                        /*
1881                         * context is unloaded at this point
1882                         */
1883                } else
1884#endif /* CONFIG_SMP */
1885                {
1886
1887                        DPRINT(("forcing unload\n"));
1888                        /*
1889                        * stop and unload, returning with state UNLOADED
1890                        * and session unreserved.
1891                        */
1892                        pfm_context_unload(ctx, NULL, 0, regs);
1893
1894                        DPRINT(("ctx_state=%d\n", ctx->ctx_state));
1895                }
1896        }
1897
1898        /*
1899         * remove virtual mapping, if any, for the calling task.
1900         * cannot reset ctx field until last user is calling close().
1901         *
1902         * ctx_smpl_vaddr must never be cleared because it is needed
1903         * by every task with access to the context
1904         *
1905         * When called from do_exit(), the mm context is gone already, therefore
1906         * mm is NULL, i.e., the VMA is already gone  and we do not have to
1907         * do anything here
1908         */
1909        if (ctx->ctx_smpl_vaddr && current->mm) {
1910                smpl_buf_vaddr = ctx->ctx_smpl_vaddr;
1911                smpl_buf_size  = ctx->ctx_smpl_size;
1912        }
1913
1914        UNPROTECT_CTX(ctx, flags);
1915
1916        /*
1917         * if there was a mapping, then we systematically remove it
1918         * at this point. Cannot be done inside critical section
1919         * because some VM function reenables interrupts.
1920         *
1921         */
1922        if (smpl_buf_vaddr) pfm_remove_smpl_mapping(current, smpl_buf_vaddr, smpl_buf_size);
1923
1924        return 0;
1925}
1926/*
1927 * called either on explicit close() or from exit_files().
1928 * Only the LAST user of the file gets to this point, i.e., it is
1929 * called only ONCE.
1930 *
1931 * IMPORTANT: we get called ONLY when the refcnt on the file gets to zero
1932 * (fput()),i.e, last task to access the file. Nobody else can access the
1933 * file at this point.
1934 *
1935 * When called from exit_files(), the VMA has been freed because exit_mm()
1936 * is executed before exit_files().
1937 *
1938 * When called from exit_files(), the current task is not yet ZOMBIE but we
1939 * flush the PMU state to the context.
1940 */
1941static int
1942pfm_close(struct inode *inode, struct file *filp)
1943{
1944        pfm_context_t *ctx;
1945        struct task_struct *task;
1946        struct pt_regs *regs;
1947        DECLARE_WAITQUEUE(wait, current);
1948        unsigned long flags;
1949        unsigned long smpl_buf_size = 0UL;
1950        void *smpl_buf_addr = NULL;
1951        int free_possible = 1;
1952        int state, is_system;
1953
1954        DPRINT(("pfm_close called private=%p\n", filp->private_data));
1955
1956        if (PFM_IS_FILE(filp) == 0) {
1957                DPRINT(("bad magic\n"));
1958                return -EBADF;
1959        }
1960       
1961        ctx = (pfm_context_t *)filp->private_data;
1962        if (ctx == NULL) {
1963                printk(KERN_ERR "perfmon: pfm_close: NULL ctx [%d]\n", current->pid);
1964                return -EBADF;
1965        }
1966
1967        PROTECT_CTX(ctx, flags);
1968
1969        state     = ctx->ctx_state;
1970        is_system = ctx->ctx_fl_system;
1971
1972        task = PFM_CTX_TASK(ctx);
1973        regs = task_pt_regs(task);
1974
1975        DPRINT(("ctx_state=%d is_current=%d\n", 
1976                state,
1977                task == current ? 1 : 0));
1978
1979        /*
1980         * if task == current, then pfm_flush() unloaded the context
1981         */
1982        if (state == PFM_CTX_UNLOADED) goto doit;
1983
1984        /*
1985         * context is loaded/masked and task != current, we need to
1986         * either force an unload or go zombie
1987         */
1988
1989        /*
1990         * The task is currently blocked or will block after an overflow.
1991         * we must force it to wakeup to get out of the
1992         * MASKED state and transition to the unloaded state by itself.
1993         *
1994         * This situation is only possible for per-task mode
1995         */
1996        if (state == PFM_CTX_MASKED && CTX_OVFL_NOBLOCK(ctx) == 0) {
1997
1998                /*
1999                 * set a "partial" zombie state to be checked
2000                 * upon return from down() in pfm_handle_work().
2001                 *
2002                 * We cannot use the ZOMBIE state, because it is checked
2003                 * by pfm_load_regs() which is called upon wakeup from down().
2004                 * In such case, it would free the context and then we would
2005                 * return to pfm_handle_work() which would access the
2006                 * stale context. Instead, we set a flag invisible to pfm_load_regs()
2007                 * but visible to pfm_handle_work().
2008                 *
2009                 * For some window of time, we have a zombie context with
2010                 * ctx_state = MASKED  and not ZOMBIE
2011                 */
2012                ctx->ctx_fl_going_zombie = 1;
2013
2014                /*
2015                 * force task to wake up from MASKED state
2016                 */
2017                complete(&ctx->ctx_restart_done);
2018
2019                DPRINT(("waking up ctx_state=%d\n", state));
2020
2021                /*
2022                 * put ourself to sleep waiting for the other
2023                 * task to report completion
2024                 *
2025                 * the context is protected by mutex, therefore there
2026                 * is no risk of being notified of completion before
2027                 * begin actually on the waitq.
2028                 */
2029                set_current_state(TASK_INTERRUPTIBLE);
2030                add_wait_queue(&ctx->ctx_zombieq, &wait);
2031
2032                UNPROTECT_CTX(ctx, flags);
2033
2034                /*
2035                 * XXX: check for signals :
2036                 *      - ok for explicit close
2037                 *      - not ok when coming from exit_files()
2038                 */
2039                schedule();
2040
2041
2042                PROTECT_CTX(ctx, flags);
2043
2044
2045                remove_wait_queue(&ctx->ctx_zombieq, &wait);
2046                set_current_state(TASK_RUNNING);
2047
2048                /*
2049                 * context is unloaded at this point
2050                 */
2051                DPRINT(("after zombie wakeup ctx_state=%d for\n", state));
2052        }
2053        else if (task != current) {
2054#ifdef CONFIG_SMP
2055                /*
2056                 * switch context to zombie state
2057                 */
2058                ctx->ctx_state = PFM_CTX_ZOMBIE;
2059
2060                DPRINT(("zombie ctx for [%d]\n", task->pid));
2061                /*
2062                 * cannot free the context on the spot. deferred until
2063                 * the task notices the ZOMBIE state
2064                 */
2065                free_possible = 0;
2066#else
2067                pfm_context_unload(ctx, NULL, 0, regs);
2068#endif
2069        }
2070
2071doit:
2072        /* reload state, may have changed during  opening of critical section */
2073        state = ctx->ctx_state;
2074
2075        /*
2076         * the context is still attached to a task (possibly current)
2077         * we cannot destroy it right now
2078         */
2079
2080        /*
2081         * we must free the sampling buffer right here because
2082         * we cannot rely on it being cleaned up later by the
2083         * monitored task. It is not possible to free vmalloc'ed
2084         * memory in pfm_load_regs(). Instead, we remove the buffer
2085         * now. should there be subsequent PMU overflow originally
2086         * meant for sampling, the will be converted to spurious
2087         * and that's fine because the monitoring tools is gone anyway.
2088         */
2089        if (ctx->ctx_smpl_hdr) {
2090                smpl_buf_addr = ctx->ctx_smpl_hdr;
2091                smpl_buf_size = ctx->ctx_smpl_size;
2092                /* no more sampling */
2093                ctx->ctx_smpl_hdr = NULL;
2094                ctx->ctx_fl_is_sampling = 0;
2095        }
2096
2097        DPRINT(("ctx_state=%d free_possible=%d addr=%p size=%lu\n",
2098                state,
2099                free_possible,
2100                smpl_buf_addr,
2101                smpl_buf_size));
2102
2103        if (smpl_buf_addr) pfm_exit_smpl_buffer(ctx->ctx_buf_fmt);
2104
2105        /*
2106         * UNLOADED that the session has already been unreserved.
2107         */
2108        if (state == PFM_CTX_ZOMBIE) {
2109                pfm_unreserve_session(ctx, ctx->ctx_fl_system , ctx->ctx_cpu);
2110        }
2111
2112        /*
2113         * disconnect file descriptor from context must be done
2114         * before we unlock.
2115         */
2116        filp->private_data = NULL;
2117
2118        /*
2119         * if we free on the spot, the context is now completely unreacheable
2120         * from the callers side. The monitored task side is also cut, so we
2121         * can freely cut.
2122         *
2123         * If we have a deferred free, only the caller side is disconnected.
2124         */
2125        UNPROTECT_CTX(ctx, flags);
2126
2127        /*
2128         * All memory free operations (especially for vmalloc'ed memory)
2129         * MUST be done with interrupts ENABLED.
2130         */
2131        if (smpl_buf_addr)  pfm_rvfree(smpl_buf_addr, smpl_buf_size);
2132
2133        /*
2134         * return the memory used by the context
2135         */
2136        if (free_possible) pfm_context_free(ctx);
2137
2138        if (is_running_on_xen()) {
2139                if (is_xenoprof_primary()) {
2140                        int ret = HYPERVISOR_perfmon_op(PFM_DESTROY_CONTEXT,
2141                                                        NULL, 0);
2142                        if (ret)
2143                                printk("%s:%d PFM_DESTROY_CONTEXT hypercall "
2144                                       "failed\n", __func__, __LINE__);
2145                }
2146        }
2147        return 0;
2148}
2149
2150static int
2151pfm_no_open(struct inode *irrelevant, struct file *dontcare)
2152{
2153        DPRINT(("pfm_no_open called\n"));
2154        return -ENXIO;
2155}
2156
2157
2158
2159static struct file_operations pfm_file_ops = {
2160        .llseek   = no_llseek,
2161        .read     = pfm_read,
2162        .write    = pfm_write,
2163        .poll     = pfm_poll,
2164        .ioctl    = pfm_ioctl,
2165        .open     = pfm_no_open,        /* special open code to disallow open via /proc */
2166        .fasync   = pfm_fasync,
2167        .release  = pfm_close,
2168        .flush    = pfm_flush
2169};
2170
2171static int
2172pfmfs_delete_dentry(struct dentry *dentry)
2173{
2174        return 1;
2175}
2176
2177static struct dentry_operations pfmfs_dentry_operations = {
2178        .d_delete = pfmfs_delete_dentry,
2179};
2180
2181
2182static int
2183pfm_alloc_fd(struct file **cfile)
2184{
2185        int fd, ret = 0;
2186        struct file *file = NULL;
2187        struct inode * inode;
2188        char name[32];
2189        struct qstr this;
2190
2191        fd = get_unused_fd();
2192        if (fd < 0) return -ENFILE;
2193
2194        ret = -ENFILE;
2195
2196        file = get_empty_filp();
2197        if (!file) goto out;
2198
2199        /*
2200         * allocate a new inode
2201         */
2202        inode = new_inode(pfmfs_mnt->mnt_sb);
2203        if (!inode) goto out;
2204
2205        DPRINT(("new inode ino=%ld @%p\n", inode->i_ino, inode));
2206
2207        inode->i_mode = S_IFCHR|S_IRUGO;
2208        inode->i_uid  = current->fsuid;
2209        inode->i_gid  = current->fsgid;
2210
2211        sprintf(name, "[%lu]", inode->i_ino);
2212        this.name = name;
2213        this.len  = strlen(name);
2214        this.hash = inode->i_ino;
2215
2216        ret = -ENOMEM;
2217
2218        /*
2219         * allocate a new dcache entry
2220         */
2221        file->f_dentry = d_alloc(pfmfs_mnt->mnt_sb->s_root, &this);
2222        if (!file->f_dentry) goto out;
2223
2224        file->f_dentry->d_op = &pfmfs_dentry_operations;
2225
2226        d_add(file->f_dentry, inode);
2227        file->f_vfsmnt = mntget(pfmfs_mnt);
2228        file->f_mapping = inode->i_mapping;
2229
2230        file->f_op    = &pfm_file_ops;
2231        file->f_mode  = FMODE_READ;
2232        file->f_flags = O_RDONLY;
2233        file->f_pos   = 0;
2234
2235        /*
2236         * may have to delay until context is attached?
2237         */
2238        fd_install(fd, file);
2239
2240        /*
2241         * the file structure we will use
2242         */
2243        *cfile = file;
2244
2245        return fd;
2246out:
2247        if (file) put_filp(file);
2248        put_unused_fd(fd);
2249        return ret;
2250}
2251
2252static void
2253pfm_free_fd(int fd, struct file *file)
2254{
2255        struct files_struct *files = current->files;
2256        struct fdtable *fdt;
2257
2258        /*
2259         * there ie no fd_uninstall(), so we do it here
2260         */
2261        spin_lock(&files->file_lock);
2262        fdt = files_fdtable(files);
2263        rcu_assign_pointer(fdt->fd[fd], NULL);
2264        spin_unlock(&files->file_lock);
2265
2266        if (file)
2267                put_filp(file);
2268        put_unused_fd(fd);
2269}
2270
2271static int
2272pfm_remap_buffer(struct vm_area_struct *vma, unsigned long buf, unsigned long addr, unsigned long size)
2273{
2274        DPRINT(("CPU%d buf=0x%lx addr=0x%lx size=%ld\n", smp_processor_id(), buf, addr, size));
2275
2276        while (size > 0) {
2277                unsigned long pfn = ia64_tpa(buf) >> PAGE_SHIFT;
2278
2279
2280                if (remap_pfn_range(vma, addr, pfn, PAGE_SIZE, PAGE_READONLY))
2281                        return -ENOMEM;
2282
2283                addr  += PAGE_SIZE;
2284                buf   += PAGE_SIZE;
2285                size  -= PAGE_SIZE;
2286        }
2287        return 0;
2288}
2289
2290/*
2291 * allocate a sampling buffer and remaps it into the user address space of the task
2292 */
2293static int
2294pfm_smpl_buffer_alloc(struct task_struct *task, pfm_context_t *ctx, unsigned long rsize, void **user_vaddr)
2295{
2296        struct mm_struct *mm = task->mm;
2297        struct vm_area_struct *vma = NULL;
2298        unsigned long size;
2299        void *smpl_buf;
2300
2301
2302        /*
2303         * the fixed header + requested size and align to page boundary
2304         */
2305        size = PAGE_ALIGN(rsize);
2306
2307        DPRINT(("sampling buffer rsize=%lu size=%lu bytes\n", rsize, size));
2308
2309        /*
2310         * check requested size to avoid Denial-of-service attacks
2311         * XXX: may have to refine this test
2312         * Check against address space limit.
2313         *
2314         * if ((mm->total_vm << PAGE_SHIFT) + len> task->rlim[RLIMIT_AS].rlim_cur)
2315         *      return -ENOMEM;
2316         */
2317        if (size > task->signal->rlim[RLIMIT_MEMLOCK].rlim_cur)
2318                return -ENOMEM;
2319
2320        /*
2321         * We do the easy to undo allocations first.
2322         *
2323         * pfm_rvmalloc(), clears the buffer, so there is no leak
2324         */
2325        smpl_buf = pfm_rvmalloc(size);
2326        if (smpl_buf == NULL) {
2327                DPRINT(("Can't allocate sampling buffer\n"));
2328                return -ENOMEM;
2329        }
2330
2331        DPRINT(("smpl_buf @%p\n", smpl_buf));
2332
2333        /* allocate vma */
2334        vma = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
2335        if (!vma) {
2336                DPRINT(("Cannot allocate vma\n"));
2337                goto error_kmem;
2338        }
2339        memset(vma, 0, sizeof(*vma));
2340
2341        /*
2342         * partially initialize the vma for the sampling buffer
2343         */
2344        vma->vm_mm           = mm;
2345        vma->vm_flags        = VM_READ| VM_MAYREAD |VM_RESERVED;
2346        vma->vm_page_prot    = PAGE_READONLY; /* XXX may need to change */
2347
2348        /*
2349         * Now we have everything we need and we can initialize
2350         * and connect all the data structures
2351         */
2352
2353        ctx->ctx_smpl_hdr   = smpl_buf;
2354        ctx->ctx_smpl_size  = size; /* aligned size */
2355
2356        /*
2357         * Let's do the difficult operations next.
2358         *
2359         * now we atomically find some area in the address space and
2360         * remap the buffer in it.
2361         */
2362        down_write(&task->mm->mmap_sem);
2363
2364        /* find some free area in address space, must have mmap sem held */
2365        vma->vm_start = pfm_get_unmapped_area(NULL, 0, size, 0, MAP_PRIVATE|MAP_ANONYMOUS, 0);
2366        if (vma->vm_start == 0UL) {
2367                DPRINT(("Cannot find unmapped area for size %ld\n", size));
2368                up_write(&task->mm->mmap_sem);
2369                goto error;
2370        }
2371        vma->vm_end = vma->vm_start + size;
2372        vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
2373
2374        DPRINT(("aligned size=%ld, hdr=%p mapped @0x%lx\n", size, ctx->ctx_smpl_hdr, vma->vm_start));
2375
2376        /* can only be applied to current task, need to have the mm semaphore held when called */
2377        if (pfm_remap_buffer(vma, (unsigned long)smpl_buf, vma->vm_start, size)) {
2378                DPRINT(("Can't remap buffer\n"));
2379                up_write(&task->mm->mmap_sem);
2380                goto error;
2381        }
2382
2383        /*
2384         * now insert the vma in the vm list for the process, must be
2385         * done with mmap lock held
2386         */
2387        insert_vm_struct(mm, vma);
2388
2389        mm->total_vm  += size >> PAGE_SHIFT;
2390        vm_stat_account(vma->vm_mm, vma->vm_flags, vma->vm_file,
2391                                                        vma_pages(vma));
2392        up_write(&task->mm->mmap_sem);
2393
2394        /*
2395         * keep track of user level virtual address
2396         */
2397        ctx->ctx_smpl_vaddr = (void *)vma->vm_start;
2398        *(unsigned long *)user_vaddr = vma->vm_start;
2399
2400        return 0;
2401
2402error:
2403        kmem_cache_free(vm_area_cachep, vma);
2404error_kmem:
2405        pfm_rvfree(smpl_buf, size);
2406
2407        return -ENOMEM;
2408}
2409
2410/*
2411 * XXX: do something better here
2412 */
2413static int
2414pfm_bad_permissions(struct task_struct *task)
2415{
2416        /* inspired by ptrace_attach() */
2417        DPRINT(("cur: uid=%d gid=%d task: euid=%d suid=%d uid=%d egid=%d sgid=%d\n",
2418                current->uid,
2419                current->gid,
2420                task->euid,
2421                task->suid,
2422                task->uid,
2423                task->egid,
2424                task->sgid));
2425
2426        return ((current->uid != task->euid)
2427            || (current->uid != task->suid)
2428            || (current->uid != task->uid)
2429            || (current->gid != task->egid)
2430            || (current->gid != task->sgid)
2431            || (current->gid != task->gid)) && !capable(CAP_SYS_PTRACE);
2432}
2433
2434static int
2435pfarg_is_sane(struct task_struct *task, pfarg_context_t *pfx)
2436{
2437        int ctx_flags;
2438
2439        /* valid signal */
2440
2441        ctx_flags = pfx->ctx_flags;
2442
2443        if (ctx_flags & PFM_FL_SYSTEM_WIDE) {
2444
2445                /*
2446                 * cannot block in this mode
2447                 */
2448                if (ctx_flags & PFM_FL_NOTIFY_BLOCK) {
2449                        DPRINT(("cannot use blocking mode when in system wide monitoring\n"));
2450                        return -EINVAL;
2451                }
2452        } else {
2453        }
2454        /* probably more to add here */
2455
2456        return 0;
2457}
2458
2459static int
2460pfm_setup_buffer_fmt(struct task_struct *task, pfm_context_t *ctx, unsigned int ctx_flags,
2461                     unsigned int cpu, pfarg_context_t *arg)
2462{
2463        pfm_buffer_fmt_t *fmt = NULL;
2464        unsigned long size = 0UL;
2465        void *uaddr = NULL;
2466        void *fmt_arg = NULL;
2467        int ret = 0;
2468#define PFM_CTXARG_BUF_ARG(a)   (pfm_buffer_fmt_t *)(a+1)
2469
2470        /* invoke and lock buffer format, if found */
2471        fmt = pfm_find_buffer_fmt(arg->ctx_smpl_buf_id);
2472        if (fmt == NULL) {
2473                DPRINT(("[%d] cannot find buffer format\n", task->pid));
2474                return -EINVAL;
2475        }
2476
2477        /*
2478         * buffer argument MUST be contiguous to pfarg_context_t
2479         */
2480        if (fmt->fmt_arg_size) fmt_arg = PFM_CTXARG_BUF_ARG(arg);
2481
2482        ret = pfm_buf_fmt_validate(fmt, task, ctx_flags, cpu, fmt_arg);
2483
2484        DPRINT(("[%d] after validate(0x%x,%d,%p)=%d\n", task->pid, ctx_flags, cpu, fmt_arg, ret));
2485
2486        if (ret) goto error;
2487
2488        /* link buffer format and context */
2489        ctx->ctx_buf_fmt = fmt;
2490
2491        /*
2492         * check if buffer format wants to use perfmon buffer allocation/mapping service
2493         */
2494        ret = pfm_buf_fmt_getsize(fmt, task, ctx_flags, cpu, fmt_arg, &size);
2495        if (ret) goto error;
2496
2497        if (size) {
2498                /*
2499                 * buffer is always remapped into the caller's address space
2500                 */
2501                ret = pfm_smpl_buffer_alloc(current, ctx, size, &uaddr);
2502                if (ret) goto error;
2503
2504                /* keep track of user address of buffer */
2505                arg->ctx_smpl_vaddr = uaddr;
2506        }
2507        ret = pfm_buf_fmt_init(fmt, task, ctx->ctx_smpl_hdr, ctx_flags, cpu, fmt_arg);
2508
2509error:
2510        return ret;
2511}
2512
2513static void
2514pfm_reset_pmu_state(pfm_context_t *ctx)
2515{
2516        int i;
2517
2518        /*
2519         * install reset values for PMC.
2520         */
2521        for (i=1; PMC_IS_LAST(i) == 0; i++) {
2522                if (PMC_IS_IMPL(i) == 0) continue;
2523                ctx->ctx_pmcs[i] = PMC_DFL_VAL(i);
2524                DPRINT(("pmc[%d]=0x%lx\n", i, ctx->ctx_pmcs[i]));
2525        }
2526        /*
2527         * PMD registers are set to 0UL when the context in memset()
2528         */
2529
2530        /*
2531         * On context switched restore, we must restore ALL pmc and ALL pmd even
2532         * when they are not actively used by the task. In UP, the incoming process
2533         * may otherwise pick up left over PMC, PMD state from the previous process.
2534         * As opposed to PMD, stale PMC can cause harm to the incoming
2535         * process because they may change what is being measured.
2536         * Therefore, we must systematically reinstall the entire
2537         * PMC state. In SMP, the same thing is possible on the
2538         * same CPU but also on between 2 CPUs.
2539         *
2540         * The problem with PMD is information leaking especially
2541         * to user level when psr.sp=0
2542         *
2543         * There is unfortunately no easy way to avoid this problem
2544         * on either UP or SMP. This definitively slows down the
2545         * pfm_load_regs() function.
2546         */
2547
2548         /*
2549          * bitmask of all PMCs accessible to this context
2550          *
2551          * PMC0 is treated differently.
2552          */
2553        ctx->ctx_all_pmcs[0] = pmu_conf->impl_pmcs[0] & ~0x1;
2554
2555        /*
2556         * bitmask of all PMDs that are accesible to this context
2557         */
2558        ctx->ctx_all_pmds[0] = pmu_conf->impl_pmds[0];
2559
2560        DPRINT(("<%d> all_pmcs=0x%lx all_pmds=0x%lx\n", ctx->ctx_fd, ctx->ctx_all_pmcs[0],ctx->ctx_all_pmds[0]));
2561
2562        /*
2563         * useful in case of re-enable after disable
2564         */
2565        ctx->ctx_used_ibrs[0] = 0UL;
2566        ctx->ctx_used_dbrs[0] = 0UL;
2567}
2568
2569static int
2570pfm_ctx_getsize(void *arg, size_t *sz)
2571{
2572        pfarg_context_t *req = (pfarg_context_t *)arg;
2573        pfm_buffer_fmt_t *fmt;
2574
2575        *sz = 0;
2576
2577        if (!pfm_uuid_cmp(req->ctx_smpl_buf_id, pfm_null_uuid)) return 0;
2578
2579        fmt = pfm_find_buffer_fmt(req->ctx_smpl_buf_id);
2580        if (fmt == NULL) {
2581                DPRINT(("cannot find buffer format\n"));
2582                return -EINVAL;
2583        }
2584        /* get just enough to copy in user parameters */
2585        *sz = fmt->fmt_arg_size;
2586        DPRINT(("arg_size=%lu\n", *sz));
2587
2588        return 0;
2589}
2590
2591
2592
2593/*
2594 * cannot attach if :
2595 *      - kernel task
2596 *      - task not owned by caller
2597 *      - task incompatible with context mode
2598 */
2599static int
2600pfm_task_incompatible(pfm_context_t *ctx, struct task_struct *task)
2601{
2602        /*
2603         * no kernel task or task not owner by caller
2604         */
2605        if (task->mm == NULL) {
2606                DPRINT(("task [%d] has not memory context (kernel thread)\n", task->pid));
2607                return -EPERM;
2608        }
2609        if (pfm_bad_permissions(task)) {
2610                DPRINT(("no permission to attach to  [%d]\n", task->pid));
2611                return -EPERM;
2612        }
2613        /*
2614         * cannot block in self-monitoring mode
2615         */
2616        if (CTX_OVFL_NOBLOCK(ctx) == 0 && task == current) {
2617                DPRINT(("cannot load a blocking context on self for [%d]\n", task->pid));
2618                return -EINVAL;
2619        }
2620
2621        if (task->exit_state == EXIT_ZOMBIE) {
2622                DPRINT(("cannot attach to  zombie task [%d]\n", task->pid));
2623                return -EBUSY;
2624        }
2625
2626        /*
2627         * always ok for self
2628         */
2629        if (task == current) return 0;
2630
2631        if ((task->state != TASK_STOPPED) && (task->state != TASK_TRACED)) {
2632                DPRINT(("cannot attach to non-stopped task [%d] state=%ld\n", task->pid, task->state));
2633                return -EBUSY;
2634        }
2635        /*
2636         * make sure the task is off any CPU
2637         */
2638        wait_task_inactive(task);
2639
2640        /* more to come... */
2641
2642        return 0;
2643}
2644
2645static int
2646pfm_get_task(pfm_context_t *ctx, pid_t pid, struct task_struct **task)
2647{
2648        struct task_struct *p = current;
2649        int ret;
2650
2651        /* XXX: need to add more checks here */
2652        if (pid < 2) return -EPERM;
2653
2654        if (pid != current->pid) {
2655
2656                read_lock(&tasklist_lock);
2657
2658                p = find_task_by_pid(pid);
2659
2660                /* make sure task cannot go away while we operate on it */
2661                if (p) get_task_struct(p);
2662
2663                read_unlock(&tasklist_lock);
2664
2665                if (p == NULL) return -ESRCH;
2666        }
2667
2668        ret = pfm_task_incompatible(ctx, p);
2669        if (ret == 0) {
2670                *task = p;
2671        } else if (p != current) {
2672                pfm_put_task(p);
2673        }
2674        return ret;
2675}
2676
2677
2678
2679static int
2680pfm_context_create(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
2681{
2682        pfarg_context_t *req = (pfarg_context_t *)arg;
2683        struct file *filp;
2684        int ctx_flags;
2685        int ret;
2686
2687        /* let's check the arguments first */
2688        ret = pfarg_is_sane(current, req);
2689        if (ret < 0) return ret;
2690
2691        ctx_flags = req->ctx_flags;
2692
2693        ret = -ENOMEM;
2694
2695        ctx = pfm_context_alloc();
2696        if (!ctx) goto error;
2697
2698        ret = pfm_alloc_fd(&filp);
2699        if (ret < 0) goto error_file;
2700
2701        req->ctx_fd = ctx->ctx_fd = ret;
2702
2703        /*
2704         * attach context to file
2705         */
2706        filp->private_data = ctx;
2707
2708        /*
2709         * does the user want to sample?
2710         */
2711        if (pfm_uuid_cmp(req->ctx_smpl_buf_id, pfm_null_uuid)) {
2712                ret = pfm_setup_buffer_fmt(current, ctx, ctx_flags, 0, req);
2713                if (ret) goto buffer_error;
2714        }
2715
2716        /*
2717         * init context protection lock
2718         */
2719        spin_lock_init(&ctx->ctx_lock);
2720
2721        /*
2722         * context is unloaded
2723         */
2724        ctx->ctx_state = PFM_CTX_UNLOADED;
2725
2726        /*
2727         * initialization of context's flags
2728         */
2729        ctx->ctx_fl_block       = (ctx_flags & PFM_FL_NOTIFY_BLOCK) ? 1 : 0;
2730        ctx->ctx_fl_system      = (ctx_flags & PFM_FL_SYSTEM_WIDE) ? 1: 0;
2731        ctx->ctx_fl_is_sampling = ctx->ctx_buf_fmt ? 1 : 0; /* assume record() is defined */
2732        ctx->ctx_fl_no_msg      = (ctx_flags & PFM_FL_OVFL_NO_MSG) ? 1: 0;
2733        /*
2734         * will move to set properties
2735         * ctx->ctx_fl_excl_idle   = (ctx_flags & PFM_FL_EXCL_IDLE) ? 1: 0;
2736         */
2737
2738        /*
2739         * init restart semaphore to locked
2740         */
2741        init_completion(&ctx->ctx_restart_done);
2742
2743        /*
2744         * activation is used in SMP only
2745         */
2746        ctx->ctx_last_activation = PFM_INVALID_ACTIVATION;
2747        SET_LAST_CPU(ctx, -1);
2748
2749        /*
2750         * initialize notification message queue
2751         */
2752        ctx->ctx_msgq_head = ctx->ctx_msgq_tail = 0;
2753        init_waitqueue_head(&ctx->ctx_msgq_wait);
2754        init_waitqueue_head(&ctx->ctx_zombieq);
2755
2756        DPRINT(("ctx=%p flags=0x%x system=%d notify_block=%d excl_idle=%d no_msg=%d ctx_fd=%d \n",
2757                ctx,
2758                ctx_flags,
2759                ctx->ctx_fl_system,
2760                ctx->ctx_fl_block,
2761                ctx->ctx_fl_excl_idle,
2762                ctx->ctx_fl_no_msg,
2763                ctx->ctx_fd));
2764
2765        /*
2766         * initialize soft PMU state
2767         */
2768        pfm_reset_pmu_state(ctx);
2769
2770        if (is_running_on_xen()) {
2771                /*
2772                 * kludge to get xenoprof.is_primary.
2773                 * XENOPROF_init/ia64 is nop. so it is safe to call it here.
2774                 */
2775                struct xenoprof_init init;
2776                ret = HYPERVISOR_xenoprof_op(XENOPROF_init, &init);
2777                if (ret)
2778                        goto buffer_error;
2779                init_xenoprof_primary(init.is_primary);
2780
2781                if (is_xenoprof_primary()) {
2782                        ret = HYPERVISOR_perfmon_op(PFM_CREATE_CONTEXT, arg, 0);
2783                        if (ret)
2784                                goto buffer_error;
2785                }
2786        }
2787        return 0;
2788
2789buffer_error:
2790        pfm_free_fd(ctx->ctx_fd, filp);
2791
2792        if (ctx->ctx_buf_fmt) {
2793                pfm_buf_fmt_exit(ctx->ctx_buf_fmt, current, NULL, regs);
2794        }
2795error_file:
2796        pfm_context_free(ctx);
2797
2798error:
2799        return ret;
2800}
2801
2802static inline unsigned long
2803pfm_new_counter_value (pfm_counter_t *reg, int is_long_reset)
2804{
2805        unsigned long val = is_long_reset ? reg->long_reset : reg->short_reset;
2806        unsigned long new_seed, old_seed = reg->seed, mask = reg->mask;
2807        extern unsigned long carta_random32 (unsigned long seed);
2808
2809        if (reg->flags & PFM_REGFL_RANDOM) {
2810                new_seed = carta_random32(old_seed);
2811                val -= (old_seed & mask);       /* counter values are negative numbers! */
2812                if ((mask >> 32) != 0)
2813                        /* construct a full 64-bit random value: */
2814                        new_seed |= carta_random32(old_seed >> 32) << 32;
2815                reg->seed = new_seed;
2816        }
2817        reg->lval = val;
2818        return val;
2819}
2820
2821static void
2822pfm_reset_regs_masked(pfm_context_t *ctx, unsigned long *ovfl_regs, int is_long_reset)
2823{
2824        unsigned long mask = ovfl_regs[0];
2825        unsigned long reset_others = 0UL;
2826        unsigned long val;
2827        int i;
2828
2829        /*
2830         * now restore reset value on sampling overflowed counters
2831         */
2832        mask >>= PMU_FIRST_COUNTER;
2833        for(i = PMU_FIRST_COUNTER; mask; i++, mask >>= 1) {
2834
2835                if ((mask & 0x1UL) == 0UL) continue;
2836
2837                ctx->ctx_pmds[i].val = val = pfm_new_counter_value(ctx->ctx_pmds+ i, is_long_reset);
2838                reset_others        |= ctx->ctx_pmds[i].reset_pmds[0];
2839
2840                DPRINT_ovfl((" %s reset ctx_pmds[%d]=%lx\n", is_long_reset ? "long" : "short", i, val));
2841        }
2842
2843        /*
2844         * Now take care of resetting the other registers
2845         */
2846        for(i = 0; reset_others; i++, reset_others >>= 1) {
2847
2848                if ((reset_others & 0x1) == 0) continue;
2849
2850                ctx->ctx_pmds[i].val = val = pfm_new_counter_value(ctx->ctx_pmds + i, is_long_reset);
2851
2852                DPRINT_ovfl(("%s reset_others pmd[%d]=%lx\n",
2853                          is_long_reset ? "long" : "short", i, val));
2854        }
2855}
2856
2857static void
2858pfm_reset_regs(pfm_context_t *ctx, unsigned long *ovfl_regs, int is_long_reset)
2859{
2860        unsigned long mask = ovfl_regs[0];
2861        unsigned long reset_others = 0UL;
2862        unsigned long val;
2863        int i;
2864
2865        DPRINT_ovfl(("ovfl_regs=0x%lx is_long_reset=%d\n", ovfl_regs[0], is_long_reset));
2866
2867        if (ctx->ctx_state == PFM_CTX_MASKED) {
2868                pfm_reset_regs_masked(ctx, ovfl_regs, is_long_reset);
2869                return;
2870        }
2871
2872        /*
2873         * now restore reset value on sampling overflowed counters
2874         */
2875        mask >>= PMU_FIRST_COUNTER;
2876        for(i = PMU_FIRST_COUNTER; mask; i++, mask >>= 1) {
2877
2878                if ((mask & 0x1UL) == 0UL) continue;
2879
2880                val           = pfm_new_counter_value(ctx->ctx_pmds+ i, is_long_reset);
2881                reset_others |= ctx->ctx_pmds[i].reset_pmds[0];
2882
2883                DPRINT_ovfl((" %s reset ctx_pmds[%d]=%lx\n", is_long_reset ? "long" : "short", i, val));
2884
2885                pfm_write_soft_counter(ctx, i, val);
2886        }
2887
2888        /*
2889         * Now take care of resetting the other registers
2890         */
2891        for(i = 0; reset_others; i++, reset_others >>= 1) {
2892
2893                if ((reset_others & 0x1) == 0) continue;
2894
2895                val = pfm_new_counter_value(ctx->ctx_pmds + i, is_long_reset);
2896
2897                if (PMD_IS_COUNTING(i)) {
2898                        pfm_write_soft_counter(ctx, i, val);
2899                } else {
2900                        ia64_set_pmd(i, val);
2901                }
2902                DPRINT_ovfl(("%s reset_others pmd[%d]=%lx\n",
2903                          is_long_reset ? "long" : "short", i, val));
2904        }
2905        ia64_srlz_d();
2906}
2907
2908static int
2909pfm_write_pmcs(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
2910{
2911        struct thread_struct *thread = NULL;
2912        struct task_struct *task;
2913        pfarg_reg_t *req = (pfarg_reg_t *)arg;
2914        unsigned long value, pmc_pm;
2915        unsigned long smpl_pmds, reset_pmds, impl_pmds;
2916        unsigned int cnum, reg_flags, flags, pmc_type;
2917        int i, can_access_pmu = 0, is_loaded, is_system, expert_mode;
2918        int is_monitor, is_counting, state;
2919        int ret = -EINVAL;
2920        pfm_reg_check_t wr_func;
2921#define PFM_CHECK_PMC_PM(x, y, z) ((x)->ctx_fl_system ^ PMC_PM(y, z))
2922
2923        if (is_running_on_xen()) {
2924                if (is_xenoprof_primary())
2925                        return HYPERVISOR_perfmon_op(PFM_WRITE_PMCS,
2926                                                     arg, count);
2927                return 0;
2928        }
2929        state     = ctx->ctx_state;
2930        is_loaded = state == PFM_CTX_LOADED ? 1 : 0;
2931        is_system = ctx->ctx_fl_system;
2932        task      = ctx->ctx_task;
2933        impl_pmds = pmu_conf->impl_pmds[0];
2934
2935        if (state == PFM_CTX_ZOMBIE) return -EINVAL;
2936
2937        if (is_loaded) {
2938                thread = &task->thread;
2939                /*
2940                 * In system wide and when the context is loaded, access can only happen
2941                 * when the caller is running on the CPU being monitored by the session.
2942                 * It does not have to be the owner (ctx_task) of the context per se.
2943                 */
2944                if (is_system && ctx->ctx_cpu != smp_processor_id()) {
2945                        DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
2946                        return -EBUSY;
2947                }
2948                can_access_pmu = GET_PMU_OWNER() == task || is_system ? 1 : 0;
2949        }
2950        expert_mode = pfm_sysctl.expert_mode; 
2951
2952        for (i = 0; i < count; i++, req++) {
2953
2954                cnum       = req->reg_num;
2955                reg_flags  = req->reg_flags;
2956                value      = req->reg_value;
2957                smpl_pmds  = req->reg_smpl_pmds[0];
2958                reset_pmds = req->reg_reset_pmds[0];
2959                flags      = 0;
2960
2961
2962                if (cnum >= PMU_MAX_PMCS) {
2963                        DPRINT(("pmc%u is invalid\n", cnum));
2964                        goto error;
2965                }
2966
2967                pmc_type   = pmu_conf->pmc_desc[cnum].type;
2968                pmc_pm     = (value >> pmu_conf->pmc_desc[cnum].pm_pos) & 0x1;
2969                is_counting = (pmc_type & PFM_REG_COUNTING) == PFM_REG_COUNTING ? 1 : 0;
2970                is_monitor  = (pmc_type & PFM_REG_MONITOR) == PFM_REG_MONITOR ? 1 : 0;
2971
2972                /*
2973                 * we reject all non implemented PMC as well
2974                 * as attempts to modify PMC[0-3] which are used
2975                 * as status registers by the PMU
2976                 */
2977                if ((pmc_type & PFM_REG_IMPL) == 0 || (pmc_type & PFM_REG_CONTROL) == PFM_REG_CONTROL) {
2978                        DPRINT(("pmc%u is unimplemented or no-access pmc_type=%x\n", cnum, pmc_type));
2979                        goto error;
2980                }
2981                wr_func = pmu_conf->pmc_desc[cnum].write_check;
2982                /*
2983                 * If the PMC is a monitor, then if the value is not the default:
2984                 *      - system-wide session: PMCx.pm=1 (privileged monitor)
2985                 *      - per-task           : PMCx.pm=0 (user monitor)
2986                 */
2987                if (is_monitor && value != PMC_DFL_VAL(cnum) && is_system ^ pmc_pm) {
2988                        DPRINT(("pmc%u pmc_pm=%lu is_system=%d\n",
2989                                cnum,
2990                                pmc_pm,
2991                                is_system));
2992                        goto error;
2993                }
2994
2995                if (is_counting) {
2996                        /*
2997                         * enforce generation of overflow interrupt. Necessary on all
2998                         * CPUs.
2999                         */
3000                        value |= 1 << PMU_PMC_OI;
3001
3002                        if (reg_flags & PFM_REGFL_OVFL_NOTIFY) {
3003                                flags |= PFM_REGFL_OVFL_NOTIFY;
3004                        }
3005
3006                        if (reg_flags & PFM_REGFL_RANDOM) flags |= PFM_REGFL_RANDOM;
3007
3008                        /* verify validity of smpl_pmds */
3009                        if ((smpl_pmds & impl_pmds) != smpl_pmds) {
3010                                DPRINT(("invalid smpl_pmds 0x%lx for pmc%u\n", smpl_pmds, cnum));
3011                                goto error;
3012                        }
3013
3014                        /* verify validity of reset_pmds */
3015                        if ((reset_pmds & impl_pmds) != reset_pmds) {
3016                                DPRINT(("invalid reset_pmds 0x%lx for pmc%u\n", reset_pmds, cnum));
3017                                goto error;
3018                        }
3019                } else {
3020                        if (reg_flags & (PFM_REGFL_OVFL_NOTIFY|PFM_REGFL_RANDOM)) {
3021                                DPRINT(("cannot set ovfl_notify or random on pmc%u\n", cnum));
3022                                goto error;
3023                        }
3024                        /* eventid on non-counting monitors are ignored */
3025                }
3026
3027                /*
3028                 * execute write checker, if any
3029                 */
3030                if (likely(expert_mode == 0 && wr_func)) {
3031                        ret = (*wr_func)(task, ctx, cnum, &value, regs);
3032                        if (ret) goto error;
3033                        ret = -EINVAL;
3034                }
3035
3036                /*
3037                 * no error on this register
3038                 */
3039                PFM_REG_RETFLAG_SET(req->reg_flags, 0);
3040
3041                /*
3042                 * Now we commit the changes to the software state
3043                 */
3044
3045                /*
3046                 * update overflow information
3047                 */
3048                if (is_counting) {
3049                        /*
3050                         * full flag update each time a register is programmed
3051                         */
3052                        ctx->ctx_pmds[cnum].flags = flags;
3053
3054                        ctx->ctx_pmds[cnum].reset_pmds[0] = reset_pmds;
3055                        ctx->ctx_pmds[cnum].smpl_pmds[0]  = smpl_pmds;
3056                        ctx->ctx_pmds[cnum].eventid       = req->reg_smpl_eventid;
3057
3058                        /*
3059                         * Mark all PMDS to be accessed as used.
3060                         *
3061                         * We do not keep track of PMC because we have to
3062                         * systematically restore ALL of them.
3063                         *
3064                         * We do not update the used_monitors mask, because
3065                         * if we have not programmed them, then will be in
3066                         * a quiescent state, therefore we will not need to
3067                         * mask/restore then when context is MASKED.
3068                         */
3069                        CTX_USED_PMD(ctx, reset_pmds);
3070                        CTX_USED_PMD(ctx, smpl_pmds);
3071                        /*
3072                         * make sure we do not try to reset on
3073                         * restart because we have established new values
3074                         */
3075                        if (state == PFM_CTX_MASKED) ctx->ctx_ovfl_regs[0] &= ~1UL << cnum;
3076                }
3077                /*
3078                 * Needed in case the user does not initialize the equivalent
3079                 * PMD. Clearing is done indirectly via pfm_reset_pmu_state() so there is no
3080                 * possible leak here.
3081                 */
3082                CTX_USED_PMD(ctx, pmu_conf->pmc_desc[cnum].dep_pmd[0]);
3083
3084                /*
3085                 * keep track of the monitor PMC that we are using.
3086                 * we save the value of the pmc in ctx_pmcs[] and if
3087                 * the monitoring is not stopped for the context we also
3088                 * place it in the saved state area so that it will be
3089                 * picked up later by the context switch code.
3090                 *
3091                 * The value in ctx_pmcs[] can only be changed in pfm_write_pmcs().
3092                 *
3093                 * The value in thread->pmcs[] may be modified on overflow, i.e.,  when
3094                 * monitoring needs to be stopped.
3095                 */
3096                if (is_monitor) CTX_USED_MONITOR(ctx, 1UL << cnum);
3097
3098                /*
3099                 * update context state
3100                 */
3101                ctx->ctx_pmcs[cnum] = value;
3102
3103                if (is_loaded) {
3104                        /*
3105                         * write thread state
3106                         */
3107                        if (is_system == 0) thread->pmcs[cnum] = value;
3108
3109                        /*
3110                         * write hardware register if we can
3111                         */
3112                        if (can_access_pmu) {
3113                                ia64_set_pmc(cnum, value);
3114                        }
3115#ifdef CONFIG_SMP
3116                        else {
3117                                /*
3118                                 * per-task SMP only here
3119                                 *
3120                                 * we are guaranteed that the task is not running on the other CPU,
3121                                 * we indicate that this PMD will need to be reloaded if the task
3122                                 * is rescheduled on the CPU it ran last on.
3123                                 */
3124                                ctx->ctx_reload_pmcs[0] |= 1UL << cnum;
3125                        }
3126#endif
3127                }
3128
3129                DPRINT(("pmc[%u]=0x%lx ld=%d apmu=%d flags=0x%x all_pmcs=0x%lx used_pmds=0x%lx eventid=%ld smpl_pmds=0x%lx reset_pmds=0x%lx reloads_pmcs=0x%lx used_monitors=0x%lx ovfl_regs=0x%lx\n",
3130                          cnum,
3131                          value,
3132                          is_loaded,
3133                          can_access_pmu,
3134                          flags,
3135                          ctx->ctx_all_pmcs[0],
3136                          ctx->ctx_used_pmds[0],
3137                          ctx->ctx_pmds[cnum].eventid,
3138                          smpl_pmds,
3139                          reset_pmds,
3140                          ctx->ctx_reload_pmcs[0],
3141                          ctx->ctx_used_monitors[0],
3142                          ctx->ctx_ovfl_regs[0]));
3143        }
3144
3145        /*
3146         * make sure the changes are visible
3147         */
3148        if (can_access_pmu) ia64_srlz_d();
3149
3150        return 0;
3151error:
3152        PFM_REG_RETFLAG_SET(req->reg_flags, PFM_REG_RETFL_EINVAL);
3153        return ret;
3154}
3155
3156static int
3157pfm_write_pmds(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
3158{
3159        struct thread_struct *thread = NULL;
3160        struct task_struct *task;
3161        pfarg_reg_t *req = (pfarg_reg_t *)arg;
3162        unsigned long value, hw_value, ovfl_mask;
3163        unsigned int cnum;
3164        int i, can_access_pmu = 0, state;
3165        int is_counting, is_loaded, is_system, expert_mode;
3166        int ret = -EINVAL;
3167        pfm_reg_check_t wr_func;
3168
3169        if (is_running_on_xen()) {
3170                if (is_xenoprof_primary())
3171                        return HYPERVISOR_perfmon_op(PFM_WRITE_PMDS,
3172                                                     arg, count);
3173                return 0;
3174        }
3175
3176        state     = ctx->ctx_state;
3177        is_loaded = state == PFM_CTX_LOADED ? 1 : 0;
3178        is_system = ctx->ctx_fl_system;
3179        ovfl_mask = pmu_conf->ovfl_val;
3180        task      = ctx->ctx_task;
3181
3182        if (unlikely(state == PFM_CTX_ZOMBIE)) return -EINVAL;
3183
3184        /*
3185         * on both UP and SMP, we can only write to the PMC when the task is
3186         * the owner of the local PMU.
3187         */
3188        if (likely(is_loaded)) {
3189                thread = &task->thread;
3190                /*
3191                 * In system wide and when the context is loaded, access can only happen
3192                 * when the caller is running on the CPU being monitored by the session.
3193                 * It does not have to be the owner (ctx_task) of the context per se.
3194                 */
3195                if (unlikely(is_system && ctx->ctx_cpu != smp_processor_id())) {
3196                        DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
3197                        return -EBUSY;
3198                }
3199                can_access_pmu = GET_PMU_OWNER() == task || is_system ? 1 : 0;
3200        }
3201        expert_mode = pfm_sysctl.expert_mode; 
3202
3203        for (i = 0; i < count; i++, req++) {
3204
3205                cnum  = req->reg_num;
3206                value = req->reg_value;
3207
3208                if (!PMD_IS_IMPL(cnum)) {
3209                        DPRINT(("pmd[%u] is unimplemented or invalid\n", cnum));
3210                        goto abort_mission;
3211                }
3212                is_counting = PMD_IS_COUNTING(cnum);
3213                wr_func     = pmu_conf->pmd_desc[cnum].write_check;
3214
3215                /*
3216                 * execute write checker, if any
3217                 */
3218                if (unlikely(expert_mode == 0 && wr_func)) {
3219                        unsigned long v = value;
3220
3221                        ret = (*wr_func)(task, ctx, cnum, &v, regs);
3222                        if (ret) goto abort_mission;
3223
3224                        value = v;
3225                        ret   = -EINVAL;
3226                }
3227
3228                /*
3229                 * no error on this register
3230                 */
3231                PFM_REG_RETFLAG_SET(req->reg_flags, 0);
3232
3233                /*
3234                 * now commit changes to software state
3235                 */
3236                hw_value = value;
3237
3238                /*
3239                 * update virtualized (64bits) counter
3240                 */
3241                if (is_counting) {
3242                        /*
3243                         * write context state
3244                         */
3245                        ctx->ctx_pmds[cnum].lval = value;
3246
3247                        /*
3248                         * when context is load we use the split value
3249                         */
3250                        if (is_loaded) {
3251                                hw_value = value &  ovfl_mask;
3252                                value    = value & ~ovfl_mask;
3253                        }
3254                }
3255                /*
3256                 * update reset values (not just for counters)
3257                 */
3258                ctx->ctx_pmds[cnum].long_reset  = req->reg_long_reset;
3259                ctx->ctx_pmds[cnum].short_reset = req->reg_short_reset;
3260
3261                /*
3262                 * update randomization parameters (not just for counters)
3263                 */
3264                ctx->ctx_pmds[cnum].seed = req->reg_random_seed;
3265                ctx->ctx_pmds[cnum].mask = req->reg_random_mask;
3266
3267                /*
3268                 * update context value
3269                 */
3270                ctx->ctx_pmds[cnum].val  = value;
3271
3272                /*
3273                 * Keep track of what we use
3274                 *
3275                 * We do not keep track of PMC because we have to
3276                 * systematically restore ALL of them.
3277                 */
3278                CTX_USED_PMD(ctx, PMD_PMD_DEP(cnum));
3279
3280                /*
3281                 * mark this PMD register used as well
3282                 */
3283                CTX_USED_PMD(ctx, RDEP(cnum));
3284
3285                /*
3286                 * make sure we do not try to reset on
3287                 * restart because we have established new values
3288                 */
3289                if (is_counting && state == PFM_CTX_MASKED) {
3290                        ctx->ctx_ovfl_regs[0] &= ~1UL << cnum;
3291                }
3292
3293                if (is_loaded) {
3294                        /*
3295                         * write thread state
3296                         */
3297                        if (is_system == 0) thread->pmds[cnum] = hw_value;
3298
3299                        /*
3300                         * write hardware register if we can
3301                         */
3302                        if (can_access_pmu) {
3303                                ia64_set_pmd(cnum, hw_value);
3304                        } else {
3305#ifdef CONFIG_SMP
3306                                /*
3307                                 * we are guaranteed that the task is not running on the other CPU,
3308                                 * we indicate that this PMD will need to be reloaded if the task
3309                                 * is rescheduled on the CPU it ran last on.
3310                                 */
3311                                ctx->ctx_reload_pmds[0] |= 1UL << cnum;
3312#endif
3313                        }
3314                }
3315
3316                DPRINT(("pmd[%u]=0x%lx ld=%d apmu=%d, hw_value=0x%lx ctx_pmd=0x%lx  short_reset=0x%lx "
3317                          "long_reset=0x%lx notify=%c seed=0x%lx mask=0x%lx used_pmds=0x%lx reset_pmds=0x%lx reload_pmds=0x%lx all_pmds=0x%lx ovfl_regs=0x%lx\n",
3318                        cnum,
3319                        value,
3320                        is_loaded,
3321                        can_access_pmu,
3322                        hw_value,
3323                        ctx->ctx_pmds[cnum].val,
3324                        ctx->ctx_pmds[cnum].short_reset,
3325                        ctx->ctx_pmds[cnum].long_reset,
3326                        PMC_OVFL_NOTIFY(ctx, cnum) ? 'Y':'N',
3327                        ctx->ctx_pmds[cnum].seed,
3328                        ctx->ctx_pmds[cnum].mask,
3329                        ctx->ctx_used_pmds[0],
3330                        ctx->ctx_pmds[cnum].reset_pmds[0],
3331                        ctx->ctx_reload_pmds[0],
3332                        ctx->ctx_all_pmds[0],
3333                        ctx->ctx_ovfl_regs[0]));
3334        }
3335
3336        /*
3337         * make changes visible
3338         */
3339        if (can_access_pmu) ia64_srlz_d();
3340
3341        return 0;
3342
3343abort_mission:
3344        /*
3345         * for now, we have only one possibility for error
3346         */
3347        PFM_REG_RETFLAG_SET(req->reg_flags, PFM_REG_RETFL_EINVAL);
3348        return ret;
3349}
3350
3351/*
3352 * By the way of PROTECT_CONTEXT(), interrupts are masked while we are in this function.
3353 * Therefore we know, we do not have to worry about the PMU overflow interrupt. If an
3354 * interrupt is delivered during the call, it will be kept pending until we leave, making
3355 * it appears as if it had been generated at the UNPROTECT_CONTEXT(). At least we are
3356 * guaranteed to return consistent data to the user, it may simply be old. It is not
3357 * trivial to treat the overflow while inside the call because you may end up in
3358 * some module sampling buffer code causing deadlocks.
3359 */
3360static int
3361pfm_read_pmds(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
3362{
3363        struct thread_struct *thread = NULL;
3364        struct task_struct *task;
3365        unsigned long val = 0UL, lval, ovfl_mask, sval;
3366        pfarg_reg_t *req = (pfarg_reg_t *)arg;
3367        unsigned int cnum, reg_flags = 0;
3368        int i, can_access_pmu = 0, state;
3369        int is_loaded, is_system, is_counting, expert_mode;
3370        int ret = -EINVAL;
3371        pfm_reg_check_t rd_func;
3372        XEN_NOT_SUPPORTED_YET;
3373
3374        /*
3375         * access is possible when loaded only for
3376         * self-monitoring tasks or in UP mode
3377         */
3378
3379        state     = ctx->ctx_state;
3380        is_loaded = state == PFM_CTX_LOADED ? 1 : 0;
3381        is_system = ctx->ctx_fl_system;
3382        ovfl_mask = pmu_conf->ovfl_val;
3383        task      = ctx->ctx_task;
3384
3385        if (state == PFM_CTX_ZOMBIE) return -EINVAL;
3386
3387        if (likely(is_loaded)) {
3388                thread = &task->thread;
3389                /*
3390                 * In system wide and when the context is loaded, access can only happen
3391                 * when the caller is running on the CPU being monitored by the session.
3392                 * It does not have to be the owner (ctx_task) of the context per se.
3393                 */
3394                if (unlikely(is_system && ctx->ctx_cpu != smp_processor_id())) {
3395                        DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
3396                        return -EBUSY;
3397                }
3398                /*
3399                 * this can be true when not self-monitoring only in UP
3400                 */
3401                can_access_pmu = GET_PMU_OWNER() == task || is_system ? 1 : 0;
3402
3403                if (can_access_pmu) ia64_srlz_d();
3404        }
3405        expert_mode = pfm_sysctl.expert_mode; 
3406
3407        DPRINT(("ld=%d apmu=%d ctx_state=%d\n",
3408                is_loaded,
3409                can_access_pmu,
3410                state));
3411
3412        /*
3413         * on both UP and SMP, we can only read the PMD from the hardware register when
3414         * the task is the owner of the local PMU.
3415         */
3416
3417        for (i = 0; i < count; i++, req++) {
3418
3419                cnum        = req->reg_num;
3420                reg_flags   = req->reg_flags;
3421
3422                if (unlikely(!PMD_IS_IMPL(cnum))) goto error;
3423                /*
3424                 * we can only read the register that we use. That includes
3425                 * the one we explicitely initialize AND the one we want included
3426                 * in the sampling buffer (smpl_regs).
3427                 *
3428                 * Having this restriction allows optimization in the ctxsw routine
3429                 * without compromising security (leaks)
3430                 */
3431                if (unlikely(!CTX_IS_USED_PMD(ctx, cnum))) goto error;
3432
3433                sval        = ctx->ctx_pmds[cnum].val;
3434                lval        = ctx->ctx_pmds[cnum].lval;
3435                is_counting = PMD_IS_COUNTING(cnum);
3436
3437                /*
3438                 * If the task is not the current one, then we check if the
3439                 * PMU state is still in the local live register due to lazy ctxsw.
3440                 * If true, then we read directly from the registers.
3441                 */
3442                if (can_access_pmu){
3443                        val = ia64_get_pmd(cnum);
3444                } else {
3445                        /*
3446                         * context has been saved
3447                         * if context is zombie, then task does not exist anymore.
3448                         * In this case, we use the full value saved in the context (pfm_flush_regs()).
3449                         */
3450                        val = is_loaded ? thread->pmds[cnum] : 0UL;
3451                }
3452                rd_func = pmu_conf->pmd_desc[cnum].read_check;
3453
3454                if (is_counting) {
3455                        /*
3456                         * XXX: need to check for overflow when loaded
3457                         */
3458                        val &= ovfl_mask;
3459                        val += sval;
3460                }
3461
3462                /*
3463                 * execute read checker, if any
3464                 */
3465                if (unlikely(expert_mode == 0 && rd_func)) {
3466                        unsigned long v = val;
3467                        ret = (*rd_func)(ctx->ctx_task, ctx, cnum, &v, regs);
3468                        if (ret) goto error;
3469                        val = v;
3470                        ret = -EINVAL;
3471                }
3472
3473                PFM_REG_RETFLAG_SET(reg_flags, 0);
3474
3475                DPRINT(("pmd[%u]=0x%lx\n", cnum, val));
3476
3477                /*
3478                 * update register return value, abort all if problem during copy.
3479                 * we only modify the reg_flags field. no check mode is fine because
3480                 * access has been verified upfront in sys_perfmonctl().
3481                 */
3482                req->reg_value            = val;
3483                req->reg_flags            = reg_flags;
3484                req->reg_last_reset_val   = lval;
3485        }
3486
3487        return 0;
3488
3489error:
3490        PFM_REG_RETFLAG_SET(req->reg_flags, PFM_REG_RETFL_EINVAL);
3491        return ret;
3492}
3493
3494int
3495pfm_mod_write_pmcs(struct task_struct *task, void *req, unsigned int nreq, struct pt_regs *regs)
3496{
3497        pfm_context_t *ctx;
3498
3499        if (req == NULL) return -EINVAL;
3500
3501        ctx = GET_PMU_CTX();
3502
3503        if (ctx == NULL) return -EINVAL;
3504
3505        /*
3506         * for now limit to current task, which is enough when calling
3507         * from overflow handler
3508         */
3509        if (task != current && ctx->ctx_fl_system == 0) return -EBUSY;
3510
3511        return pfm_write_pmcs(ctx, req, nreq, regs);
3512}
3513EXPORT_SYMBOL(pfm_mod_write_pmcs);
3514
3515int
3516pfm_mod_read_pmds(struct task_struct *task, void *req, unsigned int nreq, struct pt_regs *regs)
3517{
3518        pfm_context_t *ctx;
3519
3520        if (req == NULL) return -EINVAL;
3521
3522        ctx = GET_PMU_CTX();
3523
3524        if (ctx == NULL) return -EINVAL;
3525
3526        /*
3527         * for now limit to current task, which is enough when calling
3528         * from overflow handler
3529         */
3530        if (task != current && ctx->ctx_fl_system == 0) return -EBUSY;
3531
3532        return pfm_read_pmds(ctx, req, nreq, regs);
3533}
3534EXPORT_SYMBOL(pfm_mod_read_pmds);
3535
3536/*
3537 * Only call this function when a process it trying to
3538 * write the debug registers (reading is always allowed)
3539 */
3540int
3541pfm_use_debug_registers(struct task_struct *task)
3542{
3543        pfm_context_t *ctx = task->thread.pfm_context;
3544        unsigned long flags;
3545        int ret = 0;
3546
3547        if (pmu_conf->use_rr_dbregs == 0) return 0;
3548
3549        DPRINT(("called for [%d]\n", task->pid));
3550
3551        /*
3552         * do it only once
3553         */
3554        if (task->thread.flags & IA64_THREAD_DBG_VALID) return 0;
3555
3556        /*
3557         * Even on SMP, we do not need to use an atomic here because
3558         * the only way in is via ptrace() and this is possible only when the
3559         * process is stopped. Even in the case where the ctxsw out is not totally
3560         * completed by the time we come here, there is no way the 'stopped' process
3561         * could be in the middle of fiddling with the pfm_write_ibr_dbr() routine.
3562         * So this is always safe.
3563         */
3564        if (ctx && ctx->ctx_fl_using_dbreg == 1) return -1;
3565
3566        LOCK_PFS(flags);
3567
3568        /*
3569         * We cannot allow setting breakpoints when system wide monitoring
3570         * sessions are using the debug registers.
3571         */
3572        if (pfm_sessions.pfs_sys_use_dbregs> 0)
3573                ret = -1;
3574        else
3575                pfm_sessions.pfs_ptrace_use_dbregs++;
3576
3577        DPRINT(("ptrace_use_dbregs=%u  sys_use_dbregs=%u by [%d] ret = %d\n",
3578                  pfm_sessions.pfs_ptrace_use_dbregs,
3579                  pfm_sessions.pfs_sys_use_dbregs,
3580                  task->pid, ret));
3581
3582        UNLOCK_PFS(flags);
3583
3584        return ret;
3585}
3586
3587/*
3588 * This function is called for every task that exits with the
3589 * IA64_THREAD_DBG_VALID set. This indicates a task which was
3590 * able to use the debug registers for debugging purposes via
3591 * ptrace(). Therefore we know it was not using them for
3592 * perfmormance monitoring, so we only decrement the number
3593 * of "ptraced" debug register users to keep the count up to date
3594 */
3595int
3596pfm_release_debug_registers(struct task_struct *task)
3597{
3598        unsigned long flags;
3599        int ret;
3600
3601        if (pmu_conf->use_rr_dbregs == 0) return 0;
3602
3603        LOCK_PFS(flags);
3604        if (pfm_sessions.pfs_ptrace_use_dbregs == 0) {
3605                printk(KERN_ERR "perfmon: invalid release for [%d] ptrace_use_dbregs=0\n", task->pid);
3606                ret = -1;
3607        }  else {
3608                pfm_sessions.pfs_ptrace_use_dbregs--;
3609                ret = 0;
3610        }
3611        UNLOCK_PFS(flags);
3612
3613        return ret;
3614}
3615
3616static int
3617pfm_restart(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
3618{
3619        struct task_struct *task;
3620        pfm_buffer_fmt_t *fmt;
3621        pfm_ovfl_ctrl_t rst_ctrl;
3622        int state, is_system;
3623        int ret = 0;
3624        XEN_NOT_SUPPORTED_YET;
3625
3626        state     = ctx->ctx_state;
3627        fmt       = ctx->ctx_buf_fmt;
3628        is_system = ctx->ctx_fl_system;
3629        task      = PFM_CTX_TASK(ctx);
3630
3631        switch(state) {
3632                case PFM_CTX_MASKED:
3633                        break;
3634                case PFM_CTX_LOADED:
3635                        if (CTX_HAS_SMPL(ctx) && fmt->fmt_restart_active) break;
3636                        /* fall through */
3637                case PFM_CTX_UNLOADED:
3638                case PFM_CTX_ZOMBIE:
3639                        DPRINT(("invalid state=%d\n", state));
3640                        return -EBUSY;
3641                default:
3642                        DPRINT(("state=%d, cannot operate (no active_restart handler)\n", state));
3643                        return -EINVAL;
3644        }
3645
3646        /*
3647         * In system wide and when the context is loaded, access can only happen
3648         * when the caller is running on the CPU being monitored by the session.
3649         * It does not have to be the owner (ctx_task) of the context per se.
3650         */
3651        if (is_system && ctx->ctx_cpu != smp_processor_id()) {
3652                DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
3653                return -EBUSY;
3654        }
3655
3656        /* sanity check */
3657        if (unlikely(task == NULL)) {
3658                printk(KERN_ERR "perfmon: [%d] pfm_restart no task\n", current->pid);
3659                return -EINVAL;
3660        }
3661
3662        if (task == current || is_system) {
3663
3664                fmt = ctx->ctx_buf_fmt;
3665
3666                DPRINT(("restarting self %d ovfl=0x%lx\n",
3667                        task->pid,
3668                        ctx->ctx_ovfl_regs[0]));
3669
3670                if (CTX_HAS_SMPL(ctx)) {
3671
3672                        prefetch(ctx->ctx_smpl_hdr);
3673
3674                        rst_ctrl.bits.mask_monitoring = 0;
3675                        rst_ctrl.bits.reset_ovfl_pmds = 0;
3676
3677                        if (state == PFM_CTX_LOADED)
3678                                ret = pfm_buf_fmt_restart_active(fmt, task, &rst_ctrl, ctx->ctx_smpl_hdr, regs);
3679                        else
3680                                ret = pfm_buf_fmt_restart(fmt, task, &rst_ctrl, ctx->ctx_smpl_hdr, regs);
3681                } else {
3682                        rst_ctrl.bits.mask_monitoring = 0;
3683                        rst_ctrl.bits.reset_ovfl_pmds = 1;
3684                }
3685
3686                if (ret == 0) {
3687                        if (rst_ctrl.bits.reset_ovfl_pmds)
3688                                pfm_reset_regs(ctx, ctx->ctx_ovfl_regs, PFM_PMD_LONG_RESET);
3689
3690                        if (rst_ctrl.bits.mask_monitoring == 0) {
3691                                DPRINT(("resuming monitoring for [%d]\n", task->pid));
3692
3693                                if (state == PFM_CTX_MASKED) pfm_restore_monitoring(task);
3694                        } else {
3695                                DPRINT(("keeping monitoring stopped for [%d]\n", task->pid));
3696
3697                                // cannot use pfm_stop_monitoring(task, regs);
3698                        }
3699                }
3700                /*
3701                 * clear overflowed PMD mask to remove any stale information
3702                 */
3703                ctx->ctx_ovfl_regs[0] = 0UL;
3704
3705                /*
3706                 * back to LOADED state
3707                 */
3708                ctx->ctx_state = PFM_CTX_LOADED;
3709
3710                /*
3711                 * XXX: not really useful for self monitoring
3712                 */
3713                ctx->ctx_fl_can_restart = 0;
3714
3715                return 0;
3716        }
3717
3718        /*
3719         * restart another task
3720         */
3721
3722        /*
3723         * When PFM_CTX_MASKED, we cannot issue a restart before the previous
3724         * one is seen by the task.
3725         */
3726        if (state == PFM_CTX_MASKED) {
3727                if (ctx->ctx_fl_can_restart == 0) return -EINVAL;
3728                /*
3729                 * will prevent subsequent restart before this one is
3730                 * seen by other task
3731                 */
3732                ctx->ctx_fl_can_restart = 0;
3733        }
3734
3735        /*
3736         * if blocking, then post the semaphore is PFM_CTX_MASKED, i.e.
3737         * the task is blocked or on its way to block. That's the normal
3738         * restart path. If the monitoring is not masked, then the task
3739         * can be actively monitoring and we cannot directly intervene.
3740         * Therefore we use the trap mechanism to catch the task and
3741         * force it to reset the buffer/reset PMDs.
3742         *
3743         * if non-blocking, then we ensure that the task will go into
3744         * pfm_handle_work() before returning to user mode.
3745         *
3746         * We cannot explicitely reset another task, it MUST always
3747         * be done by the task itself. This works for system wide because
3748         * the tool that is controlling the session is logically doing
3749         * "self-monitoring".
3750         */
3751        if (CTX_OVFL_NOBLOCK(ctx) == 0 && state == PFM_CTX_MASKED) {
3752                DPRINT(("unblocking [%d] \n", task->pid));
3753                complete(&ctx->ctx_restart_done);
3754        } else {
3755                DPRINT(("[%d] armed exit trap\n", task->pid));
3756
3757                ctx->ctx_fl_trap_reason = PFM_TRAP_REASON_RESET;
3758
3759                PFM_SET_WORK_PENDING(task, 1);
3760
3761                pfm_set_task_notify(task);
3762
3763                /*
3764                 * XXX: send reschedule if task runs on another CPU
3765                 */
3766        }
3767        return 0;
3768}
3769
3770static int
3771pfm_debug(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
3772{
3773        unsigned int m = *(unsigned int *)arg;
3774        XEN_NOT_SUPPORTED_YET;
3775
3776        pfm_sysctl.debug = m == 0 ? 0 : 1;
3777
3778        printk(KERN_INFO "perfmon debugging %s (timing reset)\n", pfm_sysctl.debug ? "on" : "off");
3779
3780        if (m == 0) {
3781                memset(pfm_stats, 0, sizeof(pfm_stats));
3782                for(m=0; m < NR_CPUS; m++) pfm_stats[m].pfm_ovfl_intr_cycles_min = ~0UL;
3783        }
3784        return 0;
3785}
3786
3787/*
3788 * arg can be NULL and count can be zero for this function
3789 */
3790static int
3791pfm_write_ibr_dbr(int mode, pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
3792{
3793        struct thread_struct *thread = NULL;
3794        struct task_struct *task;
3795        pfarg_dbreg_t *req = (pfarg_dbreg_t *)arg;
3796        unsigned long flags;
3797        dbreg_t dbreg;
3798        unsigned int rnum;
3799        int first_time;
3800        int ret = 0, state;
3801        int i, can_access_pmu = 0;
3802        int is_system, is_loaded;
3803
3804        if (pmu_conf->use_rr_dbregs == 0) return -EINVAL;
3805
3806        state     = ctx->ctx_state;
3807        is_loaded = state == PFM_CTX_LOADED ? 1 : 0;
3808        is_system = ctx->ctx_fl_system;
3809        task      = ctx->ctx_task;
3810
3811        if (state == PFM_CTX_ZOMBIE) return -EINVAL;
3812
3813        /*
3814         * on both UP and SMP, we can only write to the PMC when the task is
3815         * the owner of the local PMU.
3816         */
3817        if (is_loaded) {
3818                thread = &task->thread;
3819                /*
3820                 * In system wide and when the context is loaded, access can only happen
3821                 * when the caller is running on the CPU being monitored by the session.
3822                 * It does not have to be the owner (ctx_task) of the context per se.
3823                 */
3824                if (unlikely(is_system && ctx->ctx_cpu != smp_processor_id())) {
3825                        DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
3826                        return -EBUSY;
3827                }
3828                can_access_pmu = GET_PMU_OWNER() == task || is_system ? 1 : 0;
3829        }
3830
3831        /*
3832         * we do not need to check for ipsr.db because we do clear ibr.x, dbr.r, and dbr.w
3833         * ensuring that no real breakpoint can be installed via this call.
3834         *
3835         * IMPORTANT: regs can be NULL in this function
3836         */
3837
3838        first_time = ctx->ctx_fl_using_dbreg == 0;
3839
3840        /*
3841         * don't bother if we are loaded and task is being debugged
3842         */
3843        if (is_loaded && (thread->flags & IA64_THREAD_DBG_VALID) != 0) {
3844                DPRINT(("debug registers already in use for [%d]\n", task->pid));
3845                return -EBUSY;
3846        }
3847
3848        /*
3849         * check for debug registers in system wide mode
3850         *
3851         * If though a check is done in pfm_context_load(),
3852         * we must repeat it here, in case the registers are
3853         * written after the context is loaded
3854         */
3855        if (is_loaded) {
3856                LOCK_PFS(flags);
3857
3858                if (first_time && is_system) {
3859                        if (pfm_sessions.pfs_ptrace_use_dbregs)
3860                                ret = -EBUSY;
3861                        else
3862                                pfm_sessions.pfs_sys_use_dbregs++;
3863                }
3864                UNLOCK_PFS(flags);
3865        }
3866
3867        if (ret != 0) return ret;
3868
3869        /*
3870         * mark ourself as user of the debug registers for
3871         * perfmon purposes.
3872         */
3873        ctx->ctx_fl_using_dbreg = 1;
3874
3875        /*
3876         * clear hardware registers to make sure we don't
3877         * pick up stale state.
3878         *
3879         * for a system wide session, we do not use
3880         * thread.dbr, thread.ibr because this process
3881         * never leaves the current CPU and the state
3882         * is shared by all processes running on it
3883         */
3884        if (first_time && can_access_pmu) {
3885                DPRINT(("[%d] clearing ibrs, dbrs\n", task->pid));
3886                for (i=0; i < pmu_conf->num_ibrs; i++) {
3887                        ia64_set_ibr(i, 0UL);
3888                        ia64_dv_serialize_instruction();
3889                }
3890                ia64_srlz_i();
3891                for (i=0; i < pmu_conf->num_dbrs; i++) {
3892                        ia64_set_dbr(i, 0UL);
3893                        ia64_dv_serialize_data();
3894                }
3895                ia64_srlz_d();
3896        }
3897
3898        /*
3899         * Now install the values into the registers
3900         */
3901        for (i = 0; i < count; i++, req++) {
3902
3903                rnum      = req->dbreg_num;
3904                dbreg.val = req->dbreg_value;
3905
3906                ret = -EINVAL;
3907
3908                if ((mode == PFM_CODE_RR && rnum >= PFM_NUM_IBRS) || ((mode == PFM_DATA_RR) && rnum >= PFM_NUM_DBRS)) {
3909                        DPRINT(("invalid register %u val=0x%lx mode=%d i=%d count=%d\n",
3910                                  rnum, dbreg.val, mode, i, count));
3911
3912                        goto abort_mission;
3913                }
3914
3915                /*
3916                 * make sure we do not install enabled breakpoint
3917                 */
3918                if (rnum & 0x1) {
3919                        if (mode == PFM_CODE_RR)
3920                                dbreg.ibr.ibr_x = 0;
3921                        else
3922                                dbreg.dbr.dbr_r = dbreg.dbr.dbr_w = 0;
3923                }
3924
3925                PFM_REG_RETFLAG_SET(req->dbreg_flags, 0);
3926
3927                /*
3928                 * Debug registers, just like PMC, can only be modified
3929                 * by a kernel call. Moreover, perfmon() access to those
3930                 * registers are centralized in this routine. The hardware
3931                 * does not modify the value of these registers, therefore,
3932                 * if we save them as they are written, we can avoid having
3933                 * to save them on context switch out. This is made possible
3934                 * by the fact that when perfmon uses debug registers, ptrace()
3935                 * won't be able to modify them concurrently.
3936                 */
3937                if (mode == PFM_CODE_RR) {
3938                        CTX_USED_IBR(ctx, rnum);
3939
3940                        if (can_access_pmu) {
3941                                ia64_set_ibr(rnum, dbreg.val);
3942                                ia64_dv_serialize_instruction();
3943                        }
3944
3945                        ctx->ctx_ibrs[rnum] = dbreg.val;
3946
3947                        DPRINT(("write ibr%u=0x%lx used_ibrs=0x%x ld=%d apmu=%d\n",
3948                                rnum, dbreg.val, ctx->ctx_used_ibrs[0], is_loaded, can_access_pmu));
3949                } else {
3950                        CTX_USED_DBR(ctx, rnum);
3951
3952                        if (can_access_pmu) {
3953                                ia64_set_dbr(rnum, dbreg.val);
3954                                ia64_dv_serialize_data();
3955                        }
3956                        ctx->ctx_dbrs[rnum] = dbreg.val;
3957
3958                        DPRINT(("write dbr%u=0x%lx used_dbrs=0x%x ld=%d apmu=%d\n",
3959                                rnum, dbreg.val, ctx->ctx_used_dbrs[0], is_loaded, can_access_pmu));
3960                }
3961        }
3962
3963        return 0;
3964
3965abort_mission:
3966        /*
3967         * in case it was our first attempt, we undo the global modifications
3968         */
3969        if (first_time) {
3970                LOCK_PFS(flags);
3971                if (ctx->ctx_fl_system) {
3972                        pfm_sessions.pfs_sys_use_dbregs--;
3973                }
3974                UNLOCK_PFS(flags);
3975                ctx->ctx_fl_using_dbreg = 0;
3976        }
3977        /*
3978         * install error return flag
3979         */
3980        PFM_REG_RETFLAG_SET(req->dbreg_flags, PFM_REG_RETFL_EINVAL);
3981
3982        return ret;
3983}
3984
3985static int
3986pfm_write_ibrs(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
3987{
3988        return pfm_write_ibr_dbr(PFM_CODE_RR, ctx, arg, count, regs);
3989}
3990
3991static int
3992pfm_write_dbrs(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
3993{
3994        return pfm_write_ibr_dbr(PFM_DATA_RR, ctx, arg, count, regs);
3995}
3996
3997int
3998pfm_mod_write_ibrs(struct task_struct *task, void *req, unsigned int nreq, struct pt_regs *regs)
3999{
4000        pfm_context_t *ctx;
4001
4002        if (req == NULL) return -EINVAL;
4003
4004        ctx = GET_PMU_CTX();
4005
4006        if (ctx == NULL) return -EINVAL;
4007
4008        /*
4009         * for now limit to current task, which is enough when calling
4010         * from overflow handler
4011         */
4012        if (task != current && ctx->ctx_fl_system == 0) return -EBUSY;
4013
4014        return pfm_write_ibrs(ctx, req, nreq, regs);
4015}
4016EXPORT_SYMBOL(pfm_mod_write_ibrs);
4017
4018int
4019pfm_mod_write_dbrs(struct task_struct *task, void *req, unsigned int nreq, struct pt_regs *regs)
4020{
4021        pfm_context_t *ctx;
4022
4023        if (req == NULL) return -EINVAL;
4024
4025        ctx = GET_PMU_CTX();
4026
4027        if (ctx == NULL) return -EINVAL;
4028
4029        /*
4030         * for now limit to current task, which is enough when calling
4031         * from overflow handler
4032         */
4033        if (task != current && ctx->ctx_fl_system == 0) return -EBUSY;
4034
4035        return pfm_write_dbrs(ctx, req, nreq, regs);
4036}
4037EXPORT_SYMBOL(pfm_mod_write_dbrs);
4038
4039
4040static int
4041pfm_get_features(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
4042{
4043        pfarg_features_t *req = (pfarg_features_t *)arg;
4044
4045        if (is_running_on_xen())
4046                return HYPERVISOR_perfmon_op(PFM_GET_FEATURES, &arg, 0);
4047        req->ft_version = PFM_VERSION;
4048        return 0;
4049}
4050
4051static int
4052pfm_stop(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
4053{
4054        struct pt_regs *tregs;
4055        struct task_struct *task = PFM_CTX_TASK(ctx);
4056        int state, is_system;
4057
4058        if (is_running_on_xen()) {
4059                if (is_xenoprof_primary())
4060                        return HYPERVISOR_perfmon_op(PFM_STOP, NULL, 0);
4061                return 0;
4062        }
4063
4064        state     = ctx->ctx_state;
4065        is_system = ctx->ctx_fl_system;
4066
4067        /*
4068         * context must be attached to issue the stop command (includes LOADED,MASKED,ZOMBIE)
4069         */
4070        if (state == PFM_CTX_UNLOADED) return -EINVAL;
4071
4072        /*
4073         * In system wide and when the context is loaded, access can only happen
4074         * when the caller is running on the CPU being monitored by the session.
4075         * It does not have to be the owner (ctx_task) of the context per se.
4076         */
4077        if (is_system && ctx->ctx_cpu != smp_processor_id()) {
4078                DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
4079                return -EBUSY;
4080        }
4081        DPRINT(("task [%d] ctx_state=%d is_system=%d\n",
4082                PFM_CTX_TASK(ctx)->pid,
4083                state,
4084                is_system));
4085        /*
4086         * in system mode, we need to update the PMU directly
4087         * and the user level state of the caller, which may not
4088         * necessarily be the creator of the context.
4089         */
4090        if (is_system) {
4091                /*
4092                 * Update local PMU first
4093                 *
4094                 * disable dcr pp
4095                 */
4096                ia64_setreg(_IA64_REG_CR_DCR, ia64_getreg(_IA64_REG_CR_DCR) & ~IA64_DCR_PP);
4097                ia64_srlz_i();
4098
4099                /*
4100                 * update local cpuinfo
4101                 */
4102                PFM_CPUINFO_CLEAR(PFM_CPUINFO_DCR_PP);
4103
4104                /*
4105                 * stop monitoring, does srlz.i
4106                 */
4107                pfm_clear_psr_pp();
4108
4109                /*
4110                 * stop monitoring in the caller
4111                 */
4112                ia64_psr(regs)->pp = 0;
4113
4114                return 0;
4115        }
4116        /*
4117         * per-task mode
4118         */
4119
4120        if (task == current) {
4121                /* stop monitoring  at kernel level */
4122                pfm_clear_psr_up();
4123
4124                /*
4125                 * stop monitoring at the user level
4126                 */
4127                ia64_psr(regs)->up = 0;
4128        } else {
4129                tregs = task_pt_regs(task);
4130
4131                /*
4132                 * stop monitoring at the user level
4133                 */
4134                ia64_psr(tregs)->up = 0;
4135
4136                /*
4137                 * monitoring disabled in kernel at next reschedule
4138                 */
4139                ctx->ctx_saved_psr_up = 0;
4140                DPRINT(("task=[%d]\n", task->pid));
4141        }
4142        return 0;
4143}
4144
4145
4146static int
4147pfm_start(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
4148{
4149        struct pt_regs *tregs;
4150        int state, is_system;
4151
4152        if (is_running_on_xen()) {
4153                if (is_xenoprof_primary())
4154                        return HYPERVISOR_perfmon_op(PFM_START, NULL, 0);
4155                return 0;
4156        }
4157        state     = ctx->ctx_state;
4158        is_system = ctx->ctx_fl_system;
4159
4160        if (state != PFM_CTX_LOADED) return -EINVAL;
4161
4162        /*
4163         * In system wide and when the context is loaded, access can only happen
4164         * when the caller is running on the CPU being monitored by the session.
4165         * It does not have to be the owner (ctx_task) of the context per se.
4166         */
4167        if (is_system && ctx->ctx_cpu != smp_processor_id()) {
4168                DPRINT(("should be running on CPU%d\n", ctx->ctx_cpu));
4169                return -EBUSY;
4170        }
4171
4172        /*
4173         * in system mode, we need to update the PMU directly
4174         * and the user level state of the caller, which may not
4175         * necessarily be the creator of the context.
4176         */
4177        if (is_system) {
4178
4179                /*
4180                 * set user level psr.pp for the caller
4181                 */
4182                ia64_psr(regs)->pp = 1;
4183
4184                /*
4185                 * now update the local PMU and cpuinfo
4186                 */
4187                PFM_CPUINFO_SET(PFM_CPUINFO_DCR_PP);
4188
4189                /*
4190                 * start monitoring at kernel level
4191                 */
4192                pfm_set_psr_pp();
4193
4194                /* enable dcr pp */
4195                ia64_setreg(_IA64_REG_CR_DCR, ia64_getreg(_IA64_REG_CR_DCR) | IA64_DCR_PP);
4196                ia64_srlz_i();
4197
4198                return 0;
4199        }
4200
4201        /*
4202         * per-process mode
4203         */
4204
4205        if (ctx->ctx_task == current) {
4206
4207                /* start monitoring at kernel level */
4208                pfm_set_psr_up();
4209
4210                /*
4211                 * activate monitoring at user level
4212                 */
4213                ia64_psr(regs)->up = 1;
4214
4215        } else {
4216                tregs = task_pt_regs(ctx->ctx_task);
4217
4218                /*
4219                 * start monitoring at the kernel level the next
4220                 * time the task is scheduled
4221                 */
4222                ctx->ctx_saved_psr_up = IA64_PSR_UP;
4223
4224                /*
4225                 * activate monitoring at user level
4226                 */
4227                ia64_psr(tregs)->up = 1;
4228        }
4229        return 0;
4230}
4231
4232static int
4233pfm_get_pmc_reset(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
4234{
4235        pfarg_reg_t *req = (pfarg_reg_t *)arg;
4236        unsigned int cnum;
4237        int i;
4238        int ret = -EINVAL;
4239        XEN_NOT_SUPPORTED_YET;
4240
4241        for (i = 0; i < count; i++, req++) {
4242
4243                cnum = req->reg_num;
4244
4245                if (!PMC_IS_IMPL(cnum)) goto abort_mission;
4246
4247                req->reg_value = PMC_DFL_VAL(cnum);
4248
4249                PFM_REG_RETFLAG_SET(req->reg_flags, 0);
4250
4251                DPRINT(("pmc_reset_val pmc[%u]=0x%lx\n", cnum, req->reg_value));
4252        }
4253        return 0;
4254
4255abort_mission:
4256        PFM_REG_RETFLAG_SET(req->reg_flags, PFM_REG_RETFL_EINVAL);
4257        return ret;
4258}
4259
4260static int
4261pfm_check_task_exist(pfm_context_t *ctx)
4262{
4263        struct task_struct *g, *t;
4264        int ret = -ESRCH;
4265
4266        read_lock(&tasklist_lock);
4267
4268        do_each_thread (g, t) {
4269                if (t->thread.pfm_context == ctx) {
4270                        ret = 0;
4271                        break;
4272                }
4273        } while_each_thread (g, t);
4274
4275        read_unlock(&tasklist_lock);
4276
4277        DPRINT(("pfm_check_task_exist: ret=%d ctx=%p\n", ret, ctx));
4278
4279        return ret;
4280}
4281
4282static int
4283pfm_context_load(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
4284{
4285        struct task_struct *task;
4286        struct thread_struct *thread;
4287        struct pfm_context_t *old;
4288        unsigned long flags;
4289#ifndef CONFIG_SMP
4290        struct task_struct *owner_task = NULL;
4291#endif
4292        pfarg_load_t *req = (pfarg_load_t *)arg;
4293        unsigned long *pmcs_source, *pmds_source;
4294        int the_cpu;
4295        int ret = 0;
4296        int state, is_system, set_dbregs = 0;
4297
4298        if (is_running_on_xen()) {
4299                if (is_xenoprof_primary())
4300                        return HYPERVISOR_perfmon_op(PFM_LOAD_CONTEXT, arg, 0);
4301                return 0;
4302        }
4303        state     = ctx->ctx_state;
4304        is_system = ctx->ctx_fl_system;
4305        /*
4306         * can only load from unloaded or terminated state
4307         */
4308        if (state != PFM_CTX_UNLOADED) {
4309                DPRINT(("cannot load to [%d], invalid ctx_state=%d\n",
4310                        req->load_pid,
4311                        ctx->ctx_state));
4312                return -EBUSY;
4313        }
4314
4315        DPRINT(("load_pid [%d] using_dbreg=%d\n", req->load_pid, ctx->ctx_fl_using_dbreg));
4316
4317        if (CTX_OVFL_NOBLOCK(ctx) == 0 && req->load_pid == current->pid) {
4318                DPRINT(("cannot use blocking mode on self\n"));
4319                return -EINVAL;
4320        }
4321
4322        ret = pfm_get_task(ctx, req->load_pid, &task);
4323        if (ret) {
4324                DPRINT(("load_pid [%d] get_task=%d\n", req->load_pid, ret));
4325                return ret;
4326        }
4327
4328        ret = -EINVAL;
4329
4330        /*
4331         * system wide is self monitoring only
4332         */
4333        if (is_system && task != current) {
4334                DPRINT(("system wide is self monitoring only load_pid=%d\n",
4335                        req->load_pid));
4336                goto error;
4337        }
4338
4339        thread = &task->thread;
4340
4341        ret = 0;
4342        /*
4343         * cannot load a context which is using range restrictions,
4344         * into a task that is being debugged.
4345         */
4346        if (ctx->ctx_fl_using_dbreg) {
4347                if (thread->flags & IA64_THREAD_DBG_VALID) {
4348                        ret = -EBUSY;
4349                        DPRINT(("load_pid [%d] task is debugged, cannot load range restrictions\n", req->load_pid));
4350                        goto error;
4351                }
4352                LOCK_PFS(flags);
4353
4354                if (is_system) {
4355                        if (pfm_sessions.pfs_ptrace_use_dbregs) {
4356                                DPRINT(("cannot load [%d] dbregs in use\n", task->pid));
4357                                ret = -EBUSY;
4358                        } else {
4359                                pfm_sessions.pfs_sys_use_dbregs++;
4360                                DPRINT(("load [%d] increased sys_use_dbreg=%u\n", task->pid, pfm_sessions.pfs_sys_use_dbregs));
4361                                set_dbregs = 1;
4362                        }
4363                }
4364
4365                UNLOCK_PFS(flags);
4366
4367                if (ret) goto error;
4368        }
4369
4370        /*
4371         * SMP system-wide monitoring implies self-monitoring.
4372         *
4373         * The programming model expects the task to
4374         * be pinned on a CPU throughout the session.
4375         * Here we take note of the current CPU at the
4376         * time the context is loaded. No call from
4377         * another CPU will be allowed.
4378         *
4379         * The pinning via shed_setaffinity()
4380         * must be done by the calling task prior
4381         * to this call.
4382         *
4383         * systemwide: keep track of CPU this session is supposed to run on
4384         */
4385        the_cpu = ctx->ctx_cpu = smp_processor_id();
4386
4387        ret = -EBUSY;
4388        /*
4389         * now reserve the session
4390         */
4391        ret = pfm_reserve_session(current, is_system, the_cpu);
4392        if (ret) goto error;
4393
4394        /*
4395         * task is necessarily stopped at this point.
4396         *
4397         * If the previous context was zombie, then it got removed in
4398         * pfm_save_regs(). Therefore we should not see it here.
4399         * If we see a context, then this is an active context
4400         *
4401         * XXX: needs to be atomic
4402         */
4403        DPRINT(("before cmpxchg() old_ctx=%p new_ctx=%p\n",
4404                thread->pfm_context, ctx));
4405
4406        ret = -EBUSY;
4407        old = ia64_cmpxchg(acq, &thread->pfm_context, NULL, ctx, sizeof(pfm_context_t *));
4408        if (old != NULL) {
4409                DPRINT(("load_pid [%d] already has a context\n", req->load_pid));
4410                goto error_unres;
4411        }
4412
4413        pfm_reset_msgq(ctx);
4414
4415        ctx->ctx_state = PFM_CTX_LOADED;
4416
4417        /*
4418         * link context to task
4419         */
4420        ctx->ctx_task = task;
4421
4422        if (is_system) {
4423                /*
4424                 * we load as stopped
4425                 */
4426                PFM_CPUINFO_SET(PFM_CPUINFO_SYST_WIDE);
4427                PFM_CPUINFO_CLEAR(PFM_CPUINFO_DCR_PP);
4428
4429                if (ctx->ctx_fl_excl_idle) PFM_CPUINFO_SET(PFM_CPUINFO_EXCL_IDLE);
4430        } else {
4431                thread->flags |= IA64_THREAD_PM_VALID;
4432        }
4433
4434        /*
4435         * propagate into thread-state
4436         */
4437        pfm_copy_pmds(task, ctx);
4438        pfm_copy_pmcs(task, ctx);
4439
4440        pmcs_source = thread->pmcs;
4441        pmds_source = thread->pmds;
4442
4443        /*
4444         * always the case for system-wide
4445         */
4446        if (task == current) {
4447
4448                if (is_system == 0) {
4449
4450                        /* allow user level control */
4451                        ia64_psr(regs)->sp = 0;
4452                        DPRINT(("clearing psr.sp for [%d]\n", task->pid));
4453
4454                        SET_LAST_CPU(ctx, smp_processor_id());
4455                        INC_ACTIVATION();
4456                        SET_ACTIVATION(ctx);
4457#ifndef CONFIG_SMP
4458                        /*
4459                         * push the other task out, if any
4460                         */
4461                        owner_task = GET_PMU_OWNER();
4462                        if (owner_task) pfm_lazy_save_regs(owner_task);
4463#endif
4464                }
4465                /*
4466                 * load all PMD from ctx to PMU (as opposed to thread state)
4467                 * restore all PMC from ctx to PMU
4468                 */
4469                pfm_restore_pmds(pmds_source, ctx->ctx_all_pmds[0]);
4470                pfm_restore_pmcs(pmcs_source, ctx->ctx_all_pmcs[0]);
4471
4472                ctx->ctx_reload_pmcs[0] = 0UL;
4473                ctx->ctx_reload_pmds[0] = 0UL;
4474
4475                /*
4476                 * guaranteed safe by earlier check against DBG_VALID
4477                 */
4478                if (ctx->ctx_fl_using_dbreg) {
4479                        pfm_restore_ibrs(ctx->ctx_ibrs, pmu_conf->num_ibrs);
4480                        pfm_restore_dbrs(ctx->ctx_dbrs, pmu_conf->num_dbrs);
4481                }
4482                /*
4483                 * set new ownership
4484                 */
4485                SET_PMU_OWNER(task, ctx);
4486
4487                DPRINT(("context loaded on PMU for [%d]\n", task->pid));
4488        } else {
4489                /*
4490                 * when not current, task MUST be stopped, so this is safe
4491                 */
4492                regs = task_pt_regs(task);
4493
4494                /* force a full reload */
4495                ctx->ctx_last_activation = PFM_INVALID_ACTIVATION;
4496                SET_LAST_CPU(ctx, -1);
4497
4498                /* initial saved psr (stopped) */
4499                ctx->ctx_saved_psr_up = 0UL;
4500                ia64_psr(regs)->up = ia64_psr(regs)->pp = 0;
4501        }
4502
4503        ret = 0;
4504
4505error_unres:
4506        if (ret) pfm_unreserve_session(ctx, ctx->ctx_fl_system, the_cpu);
4507error:
4508        /*
4509         * we must undo the dbregs setting (for system-wide)
4510         */
4511        if (ret && set_dbregs) {
4512                LOCK_PFS(flags);
4513                pfm_sessions.pfs_sys_use_dbregs--;
4514                UNLOCK_PFS(flags);
4515        }
4516        /*
4517         * release task, there is now a link with the context
4518         */
4519        if (is_system == 0 && task != current) {
4520                pfm_put_task(task);
4521
4522                if (ret == 0) {
4523                        ret = pfm_check_task_exist(ctx);
4524                        if (ret) {
4525                                ctx->ctx_state = PFM_CTX_UNLOADED;
4526                                ctx->ctx_task  = NULL;
4527                        }
4528                }
4529        }
4530        return ret;
4531}
4532
4533/*
4534 * in this function, we do not need to increase the use count
4535 * for the task via get_task_struct(), because we hold the
4536 * context lock. If the task were to disappear while having
4537 * a context attached, it would go through pfm_exit_thread()
4538 * which also grabs the context lock  and would therefore be blocked
4539 * until we are here.
4540 */
4541static void pfm_flush_pmds(struct task_struct *, pfm_context_t *ctx);
4542
4543static int
4544pfm_context_unload(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs)
4545{
4546        struct task_struct *task = PFM_CTX_TASK(ctx);
4547        struct pt_regs *tregs;
4548        int prev_state, is_system;
4549        int ret;
4550
4551        if (is_running_on_xen()) {
4552                if (is_xenoprof_primary())
4553                        return HYPERVISOR_perfmon_op(PFM_UNLOAD_CONTEXT,
4554                                                     NULL, 0);
4555                return 0;
4556        }
4557        DPRINT(("ctx_state=%d task [%d]\n", ctx->ctx_state, task ? task->pid : -1));
4558
4559        prev_state = ctx->ctx_state;
4560        is_system  = ctx->ctx_fl_system;
4561
4562        /*
4563         * unload only when necessary
4564         */
4565        if (prev_state == PFM_CTX_UNLOADED) {
4566                DPRINT(("ctx_state=%d, nothing to do\n", prev_state));
4567                return 0;
4568        }
4569
4570        /*
4571         * clear psr and dcr bits
4572         */
4573        ret = pfm_stop(ctx, NULL, 0, regs);
4574        if (ret) return ret;
4575
4576        ctx->ctx_state = PFM_CTX_UNLOADED;
4577
4578        /*
4579         * in system mode, we need to update the PMU directly
4580         * and the user level state of the caller, which may not
4581         * necessarily be the creator of the context.
4582         */
4583        if (is_system) {
4584
4585                /*
4586                 * Update cpuinfo
4587                 *
4588                 * local PMU is taken care of in pfm_stop()
4589                 */
4590                PFM_CPUINFO_CLEAR(PFM_CPUINFO_SYST_WIDE);
4591                PFM_CPUINFO_CLEAR(PFM_CPUINFO_EXCL_IDLE);
4592
4593                /*
4594                 * save PMDs in context
4595                 * release ownership
4596                 */
4597                pfm_flush_pmds(current, ctx);
4598
4599                /*
4600                 * at this point we are done with the PMU
4601                 * so we can unreserve the resource.
4602                 */
4603                if (prev_state != PFM_CTX_ZOMBIE) 
4604                        pfm_unreserve_session(ctx, 1 , ctx->ctx_cpu);
4605
4606                /*
4607                 * disconnect context from task
4608                 */
4609                task->thread.pfm_context = NULL;
4610                /*
4611                 * disconnect task from context
4612                 */
4613                ctx->ctx_task = NULL;
4614
4615                /*
4616                 * There is nothing more to cleanup here.
4617                 */
4618                return 0;
4619        }
4620
4621        /*
4622         * per-task mode
4623         */
4624        tregs = task == current ? regs : task_pt_regs(task);
4625
4626        if (task == current) {
4627                /*
4628                 * cancel user level control
4629                 */
4630                ia64_psr(regs)->sp = 1;
4631
4632                DPRINT(("setting psr.sp for [%d]\n", task->pid));
4633        }
4634        /*
4635         * save PMDs to context
4636         * release ownership
4637         */
4638        pfm_flush_pmds(task, ctx);
4639
4640        /*
4641         * at this point we are done with the PMU
4642         * so we can unreserve the resource.
4643         *
4644         * when state was ZOMBIE, we have already unreserved.
4645         */
4646        if (prev_state != PFM_CTX_ZOMBIE) 
4647                pfm_unreserve_session(ctx, 0 , ctx->ctx_cpu);
4648
4649        /*
4650         * reset activation counter and psr
4651         */
4652        ctx->ctx_last_activation = PFM_INVALID_ACTIVATION;
4653        SET_LAST_CPU(ctx, -1);
4654
4655        /*
4656         * PMU state will not be restored
4657         */
4658        task->thread.flags &= ~IA64_THREAD_PM_VALID;
4659
4660        /*
4661         * break links between context and task
4662         */
4663        task->thread.pfm_context  = NULL;
4664        ctx->ctx_task             = NULL;
4665
4666        PFM_SET_WORK_PENDING(task, 0);
4667
4668        ctx->ctx_fl_trap_reason  = PFM_TRAP_REASON_NONE;
4669        ctx->ctx_fl_can_restart  = 0;
4670        ctx->ctx_fl_going_zombie = 0;
4671
4672        DPRINT(("disconnected [%d] from context\n", task->pid));
4673
4674        return 0;
4675}
4676
4677
4678/*
4679 * called only from exit_thread(): task == current
4680 * we come here only if current has a context attached (loaded or masked)
4681 */
4682void
4683pfm_exit_thread(struct task_struct *task)
4684{
4685        pfm_context_t *ctx;
4686        unsigned long flags;
4687        struct pt_regs *regs = task_pt_regs(task);
4688        int ret, state;
4689        int free_ok = 0;
4690
4691        ctx = PFM_GET_CTX(task);
4692
4693        PROTECT_CTX(ctx, flags);
4694
4695        DPRINT(("state=%d task [%d]\n", ctx->ctx_state, task->pid));
4696
4697        state = ctx->ctx_state;
4698        switch(state) {
4699                case PFM_CTX_UNLOADED:
4700                        /*
4701                         * only comes to thios function if pfm_context is not NULL, i.e., cannot
4702                         * be in unloaded state
4703                         */
4704                        printk(KERN_ERR "perfmon: pfm_exit_thread [%d] ctx unloaded\n", task->pid);
4705                        break;
4706                case PFM_CTX_LOADED:
4707                case PFM_CTX_MASKED:
4708                        ret = pfm_context_unload(ctx, NULL, 0, regs);
4709                        if (ret) {
4710                                printk(KERN_ERR "perfmon: pfm_exit_thread [%d] state=%d unload failed %d\n", task->pid, state, ret);
4711                        }
4712                        DPRINT(("ctx unloaded for current state was %d\n", state));
4713
4714                        pfm_end_notify_user(ctx);
4715                        break;
4716                case PFM_CTX_ZOMBIE:
4717                        ret = pfm_context_unload(ctx, NULL, 0, regs);
4718                        if (ret) {
4719                                printk(KERN_ERR "perfmon: pfm_exit_thread [%d] state=%d unload failed %d\n", task->pid, state, ret);
4720                        }
4721                        free_ok = 1;
4722                        break;
4723                default:
4724                        printk(KERN_ERR "perfmon: pfm_exit_thread [%d] unexpected state=%d\n", task->pid, state);
4725                        break;
4726        }
4727        UNPROTECT_CTX(ctx, flags);
4728
4729        { u64 psr = pfm_get_psr();
4730          BUG_ON(psr & (IA64_PSR_UP|IA64_PSR_PP));
4731          BUG_ON(GET_PMU_OWNER());
4732          BUG_ON(ia64_psr(regs)->up);
4733          BUG_ON(ia64_psr(regs)->pp);
4734        }
4735
4736        /*
4737         * All memory free operations (especially for vmalloc'ed memory)
4738         * MUST be done with interrupts ENABLED.
4739         */
4740        if (free_ok) pfm_context_free(ctx);
4741}
4742
4743/*
4744 * functions MUST be listed in the increasing order of their index (see permfon.h)
4745 */
4746#define PFM_CMD(name, flags, arg_count, arg_type, getsz) { name, #name, flags, arg_count, sizeof(arg_type), getsz }
4747#define PFM_CMD_S(name, flags) { name, #name, flags, 0, 0, NULL }
4748#define PFM_CMD_PCLRWS  (PFM_CMD_FD|PFM_CMD_ARG_RW|PFM_CMD_STOP)
4749#define PFM_CMD_PCLRW   (PFM_CMD_FD|PFM_CMD_ARG_RW)
4750#define PFM_CMD_NONE    { NULL, "no-cmd", 0, 0, 0, NULL}
4751
4752static pfm_cmd_desc_t pfm_cmd_tab[]={
4753/* 0  */PFM_CMD_NONE,
4754/* 1  */PFM_CMD(pfm_write_pmcs, PFM_CMD_PCLRWS, PFM_CMD_ARG_MANY, pfarg_reg_t, NULL),
4755/* 2  */PFM_CMD(pfm_write_pmds, PFM_CMD_PCLRWS, PFM_CMD_ARG_MANY, pfarg_reg_t, NULL),
4756/* 3  */PFM_CMD(pfm_read_pmds, PFM_CMD_PCLRWS, PFM_CMD_ARG_MANY, pfarg_reg_t, NULL),
4757/* 4  */PFM_CMD_S(pfm_stop, PFM_CMD_PCLRWS),
4758/* 5  */PFM_CMD_S(pfm_start, PFM_CMD_PCLRWS),
4759/* 6  */PFM_CMD_NONE,
4760/* 7  */PFM_CMD_NONE,
4761/* 8  */PFM_CMD(pfm_context_create, PFM_CMD_ARG_RW, 1, pfarg_context_t, pfm_ctx_getsize),
4762/* 9  */PFM_CMD_NONE,
4763/* 10 */PFM_CMD_S(pfm_restart, PFM_CMD_PCLRW),
4764/* 11 */PFM_CMD_NONE,
4765/* 12 */PFM_CMD(pfm_get_features, PFM_CMD_ARG_RW, 1, pfarg_features_t, NULL),
4766/* 13 */PFM_CMD(pfm_debug, 0, 1, unsigned int, NULL),
4767/* 14 */PFM_CMD_NONE,
4768/* 15 */PFM_CMD(pfm_get_pmc_reset, PFM_CMD_ARG_RW, PFM_CMD_ARG_MANY, pfarg_reg_t, NULL),
4769/* 16 */PFM_CMD(pfm_context_load, PFM_CMD_PCLRWS, 1, pfarg_load_t, NULL),
4770/* 17 */PFM_CMD_S(pfm_context_unload, PFM_CMD_PCLRWS),
4771/* 18 */PFM_CMD_NONE,
4772/* 19 */PFM_CMD_NONE,
4773/* 20 */PFM_CMD_NONE,
4774/* 21 */PFM_CMD_NONE,
4775/* 22 */PFM_CMD_NONE,
4776/* 23 */PFM_CMD_NONE,
4777/* 24 */PFM_CMD_NONE,
4778/* 25 */PFM_CMD_NONE,
4779/* 26 */PFM_CMD_NONE,
4780/* 27 */PFM_CMD_NONE,
4781/* 28 */PFM_CMD_NONE,
4782/* 29 */PFM_CMD_NONE,
4783/* 30 */PFM_CMD_NONE,
4784/* 31 */PFM_CMD_NONE,
4785/* 32 */PFM_CMD(pfm_write_ibrs, PFM_CMD_PCLRWS, PFM_CMD_ARG_MANY, pfarg_dbreg_t, NULL),
4786/* 33 */PFM_CMD(pfm_write_dbrs, PFM_CMD_PCLRWS, PFM_CMD_ARG_MANY, pfarg_dbreg_t, NULL)
4787};
4788#define PFM_CMD_COUNT   (sizeof(pfm_cmd_tab)/sizeof(pfm_cmd_desc_t))
4789
4790static int
4791pfm_check_task_state(pfm_context_t *ctx, int cmd, unsigned long flags)
4792{
4793        struct task_struct *task;
4794        int state, old_state;
4795
4796recheck:
4797        state = ctx->ctx_state;
4798        task  = ctx->ctx_task;
4799
4800        if (task == NULL) {
4801                DPRINT(("context %d no task, state=%d\n", ctx->ctx_fd, state));
4802                return 0;
4803        }
4804
4805        DPRINT(("context %d state=%d [%d] task_state=%ld must_stop=%d\n",
4806                ctx->ctx_fd,
4807                state,
4808                task->pid,
4809                task->state, PFM_CMD_STOPPED(cmd)));
4810
4811        /*
4812         * self-monitoring always ok.
4813         *
4814         * for system-wide the caller can either be the creator of the
4815         * context (to one to which the context is attached to) OR
4816         * a task running on the same CPU as the session.
4817         */
4818        if (task == current || ctx->ctx_fl_system) return 0;
4819
4820        /*
4821         * we are monitoring another thread
4822         */
4823        switch(state) {
4824                case PFM_CTX_UNLOADED:
4825                        /*
4826                         * if context is UNLOADED we are safe to go
4827                         */
4828                        return 0;
4829                case PFM_CTX_ZOMBIE:
4830                        /*
4831                         * no command can operate on a zombie context
4832                         */
4833                        DPRINT(("cmd %d state zombie cannot operate on context\n", cmd));
4834                        return -EINVAL;
4835                case PFM_CTX_MASKED:
4836                        /*
4837                         * PMU state has been saved to software even though
4838                         * the thread may still be running.
4839                         */
4840                        if (cmd != PFM_UNLOAD_CONTEXT) return 0;
4841        }
4842
4843        /*
4844         * context is LOADED or MASKED. Some commands may need to have
4845         * the task stopped.
4846         *
4847         * We could lift this restriction for UP but it would mean that
4848         * the user has no guarantee the task would not run between
4849         * two successive calls to perfmonctl(). That's probably OK.
4850         * If this user wants to ensure the task does not run, then
4851         * the task must be stopped.
4852         */
4853        if (PFM_CMD_STOPPED(cmd)) {
4854                if ((task->state != TASK_STOPPED) && (task->state != TASK_TRACED)) {
4855                        DPRINT(("[%d] task not in stopped state\n", task->pid));
4856                        return -EBUSY;
4857                }
4858                /*
4859                 * task is now stopped, wait for ctxsw out
4860                 *
4861                 * This is an interesting point in the code.
4862                 * We need to unprotect the context because
4863                 * the pfm_save_regs() routines needs to grab
4864                 * the same lock. There are danger in doing
4865                 * this because it leaves a window open for
4866                 * another task to get access to the context
4867                 * and possibly change its state. The one thing
4868                 * that is not possible is for the context to disappear
4869                 * because we are protected by the VFS layer, i.e.,
4870                 * get_fd()/put_fd().
4871                 */
4872                old_state = state;
4873
4874                UNPROTECT_CTX(ctx, flags);
4875
4876                wait_task_inactive(task);
4877
4878                PROTECT_CTX(ctx, flags);
4879
4880                /*
4881                 * we must recheck to verify if state has changed
4882                 */
4883                if (ctx->ctx_state != old_state) {
4884                        DPRINT(("old_state=%d new_state=%d\n", old_state, ctx->ctx_state));
4885                        goto recheck;
4886                }
4887        }
4888        return 0;
4889}
4890
4891/*
4892 * system-call entry point (must return long)
4893 */
4894asmlinkage long
4895sys_perfmonctl (int fd, int cmd, void __user *arg, int count)
4896{
4897        struct file *file = NULL;
4898        pfm_context_t *ctx = NULL;
4899        unsigned long flags = 0UL;
4900        void *args_k = NULL;
4901        long ret; /* will expand int return types */
4902        size_t base_sz, sz, xtra_sz = 0;
4903        int narg, completed_args = 0, call_made = 0, cmd_flags;
4904        int (*func)(pfm_context_t *ctx, void *arg, int count, struct pt_regs *regs);
4905        int (*getsize)(void *arg, size_t *sz);
4906#define PFM_MAX_ARGSIZE 4096
4907
4908        /*
4909         * reject any call if perfmon was disabled at initialization
4910         */
4911        if (unlikely(pmu_conf == NULL)) return -ENOSYS;
4912
4913        if (unlikely(cmd < 0 || cmd >= PFM_CMD_COUNT)) {
4914                DPRINT(("invalid cmd=%d\n", cmd));
4915                return -EINVAL;
4916        }
4917
4918        func      = pfm_cmd_tab[cmd].cmd_func;
4919        narg      = pfm_cmd_tab[cmd].cmd_narg;
4920        base_sz   = pfm_cmd_tab[cmd].cmd_argsize;
4921        getsize   = pfm_cmd_tab[cmd].cmd_getsize;
4922        cmd_flags = pfm_cmd_tab[cmd].cmd_flags;
4923
4924        if (unlikely(func == NULL)) {
4925                DPRINT(("invalid cmd=%d\n", cmd));
4926                return -EINVAL;
4927        }
4928
4929        DPRINT(("cmd=%s idx=%d narg=0x%x argsz=%lu count=%d\n",
4930                PFM_CMD_NAME(cmd),
4931                cmd,
4932                narg,
4933                base_sz,
4934                count));
4935
4936        /*
4937         * check if number of arguments matches what the command expects
4938         */
4939        if (unlikely((narg == PFM_CMD_ARG_MANY && count <= 0) || (narg > 0 && narg != count)))
4940                return -EINVAL;
4941
4942restart_args:
4943        sz = xtra_sz + base_sz*count;
4944        /*
4945         * limit abuse to min page size
4946         */
4947        if (unlikely(sz > PFM_MAX_ARGSIZE)) {
4948                printk(KERN_ERR "perfmon: [%d] argument too big %lu\n", current->pid, sz);
4949                return -E2BIG;
4950        }
4951
4952        /*
4953         * allocate default-sized argument buffer
4954         */
4955        if (likely(count && args_k == NULL)) {
4956                args_k = kmalloc(PFM_MAX_ARGSIZE, GFP_KERNEL);
4957                if (args_k == NULL) return -ENOMEM;
4958        }
4959
4960        ret = -EFAULT;
4961
4962        /*
4963         * copy arguments
4964         *
4965         * assume sz = 0 for command without parameters
4966         */
4967        if (sz && copy_from_user(args_k, arg, sz)) {
4968                DPRINT(("cannot copy_from_user %lu bytes @%p\n", sz, arg));
4969                goto error_args;
4970        }
4971
4972        /*
4973         * check if command supports extra parameters
4974         */
4975        if (completed_args == 0 && getsize) {
4976                /*
4977                 * get extra parameters size (based on main argument)
4978                 */
4979                ret = (*getsize)(args_k, &xtra_sz);
4980                if (ret) goto error_args;
4981
4982                completed_args = 1;
4983
4984                DPRINT(("restart_args sz=%lu xtra_sz=%lu\n", sz, xtra_sz));
4985
4986                /* retry if necessary */
4987                if (likely(xtra_sz)) goto restart_args;
4988        }
4989
4990        if (unlikely((cmd_flags & PFM_CMD_FD) == 0)) goto skip_fd;
4991
4992        ret = -EBADF;
4993
4994        file = fget(fd);
4995        if (unlikely(file == NULL)) {
4996                DPRINT(("invalid fd %d\n", fd));
4997                goto error_args;
4998        }
4999        if (unlikely(PFM_IS_FILE(file) == 0)) {
5000                DPRINT(("fd %d not related to perfmon\n", fd));
5001                goto error_args;
5002        }
5003
5004        ctx = (pfm_context_t *)file->private_data;
5005        if (unlikely(ctx == NULL)) {
5006                DPRINT(("no context for fd %d\n", fd));
5007                goto error_args;
5008        }
5009        prefetch(&ctx->ctx_state);
5010
5011        PROTECT_CTX(ctx, flags);
5012
5013        /*
5014         * check task is stopped
5015         */
5016        ret = pfm_check_task_state(ctx, cmd, flags);
5017        if (unlikely(ret)) goto abort_locked;
5018
5019skip_fd:
5020        ret = (*func)(ctx, args_k, count, task_pt_regs(current));
5021
5022        call_made = 1;
5023
5024abort_locked:
5025        if (likely(ctx)) {
5026                DPRINT(("context unlocked\n"));
5027                UNPROTECT_CTX(ctx, flags);
5028        }
5029
5030        /* copy argument back to user, if needed */
5031        if (call_made && PFM_CMD_RW_ARG(cmd) && copy_to_user(arg, args_k, base_sz*count)) ret = -EFAULT;
5032
5033error_args:
5034        if (file)
5035                fput(file);
5036
5037        kfree(args_k);
5038
5039        DPRINT(("cmd=%s ret=%ld\n", PFM_CMD_NAME(cmd), ret));
5040
5041        return ret;
5042}
5043
5044static void
5045pfm_resume_after_ovfl(pfm_context_t *ctx, unsigned long ovfl_regs, struct pt_regs *regs)
5046{
5047        pfm_buffer_fmt_t *fmt = ctx->ctx_buf_fmt;
5048        pfm_ovfl_ctrl_t rst_ctrl;
5049        int state;
5050        int ret = 0;
5051
5052        state = ctx->ctx_state;
5053        /*
5054         * Unlock sampling buffer and reset index atomically
5055         * XXX: not really needed when blocking
5056         */
5057        if (CTX_HAS_SMPL(ctx)) {
5058
5059                rst_ctrl.bits.mask_monitoring = 0;
5060                rst_ctrl.bits.reset_ovfl_pmds = 0;
5061
5062                if (state == PFM_CTX_LOADED)
5063                        ret = pfm_buf_fmt_restart_active(fmt, current, &rst_ctrl, ctx->ctx_smpl_hdr, regs);
5064                else
5065                        ret = pfm_buf_fmt_restart(fmt, current, &rst_ctrl, ctx->ctx_smpl_hdr, regs);
5066        } else {
5067                rst_ctrl.bits.mask_monitoring = 0;
5068                rst_ctrl.bits.reset_ovfl_pmds = 1;
5069        }
5070
5071        if (ret == 0) {
5072                if (rst_ctrl.bits.reset_ovfl_pmds) {
5073                        pfm_reset_regs(ctx, &ovfl_regs, PFM_PMD_LONG_RESET);
5074                }
5075                if (rst_ctrl.bits.mask_monitoring == 0) {
5076                        DPRINT(("resuming monitoring\n"));
5077                        if (ctx->ctx_state == PFM_CTX_MASKED) pfm_restore_monitoring(current);
5078                } else {
5079                        DPRINT(("stopping monitoring\n"));
5080                        //pfm_stop_monitoring(current, regs);
5081                }
5082                ctx->ctx_state = PFM_CTX_LOADED;
5083        }
5084}
5085
5086/*
5087 * context MUST BE LOCKED when calling
5088 * can only be called for current
5089 */
5090static void
5091pfm_context_force_terminate(pfm_context_t *ctx, struct pt_regs *regs)
5092{
5093        int ret;
5094
5095        DPRINT(("entering for [%d]\n", current->pid));
5096
5097        ret = pfm_context_unload(ctx, NULL, 0, regs);
5098        if (ret) {
5099                printk(KERN_ERR "pfm_context_force_terminate: [%d] unloaded failed with %d\n", current->pid, ret);
5100        }
5101
5102        /*
5103         * and wakeup controlling task, indicating we are now disconnected
5104         */
5105        wake_up_interruptible(&ctx->ctx_zombieq);
5106
5107        /*
5108         * given that context is still locked, the controlling
5109         * task will only get access when we return from
5110         * pfm_handle_work().
5111         */
5112}
5113
5114static int pfm_ovfl_notify_user(pfm_context_t *ctx, unsigned long ovfl_pmds);
5115 /*
5116  * pfm_handle_work() can be called with interrupts enabled
5117  * (TIF_NEED_RESCHED) or disabled. The down_interruptible
5118  * call may sleep, therefore we must re-enable interrupts
5119  * to avoid deadlocks. It is safe to do so because this function
5120  * is called ONLY when returning to user level (PUStk=1), in which case
5121  * there is no risk of kernel stack overflow due to deep
5122  * interrupt nesting.
5123  */
5124void
5125pfm_handle_work(void)
5126{
5127        pfm_context_t *ctx;
5128        struct pt_regs *regs;
5129        unsigned long flags, dummy_flags;
5130        unsigned long ovfl_regs;
5131        unsigned int reason;
5132        int ret;
5133
5134        ctx = PFM_GET_CTX(current);
5135        if (ctx == NULL) {
5136                printk(KERN_ERR "perfmon: [%d] has no PFM context\n", current->pid);
5137                return;
5138        }
5139
5140        PROTECT_CTX(ctx, flags);
5141
5142        PFM_SET_WORK_PENDING(current, 0);
5143
5144        pfm_clear_task_notify();
5145
5146        regs = task_pt_regs(current);
5147
5148        /*
5149         * extract reason for being here and clear
5150         */
5151        reason = ctx->ctx_fl_trap_reason;
5152        ctx->ctx_fl_trap_reason = PFM_TRAP_REASON_NONE;
5153        ovfl_regs = ctx->ctx_ovfl_regs[0];
5154
5155        DPRINT(("reason=%d state=%d\n", reason, ctx->ctx_state));
5156
5157        /*
5158         * must be done before we check for simple-reset mode
5159         */
5160        if (ctx->ctx_fl_going_zombie || ctx->ctx_state == PFM_CTX_ZOMBIE) goto do_zombie;
5161
5162
5163        //if (CTX_OVFL_NOBLOCK(ctx)) goto skip_blocking;
5164        if (reason == PFM_TRAP_REASON_RESET) goto skip_blocking;
5165
5166        /*
5167         * restore interrupt mask to what it was on entry.
5168         * Could be enabled/diasbled.
5169         */
5170        UNPROTECT_CTX(ctx, flags);
5171
5172        /*
5173         * force interrupt enable because of down_interruptible()
5174         */
5175        local_irq_enable();
5176
5177        DPRINT(("before block sleeping\n"));
5178
5179        /*
5180         * may go through without blocking on SMP systems
5181         * if restart has been received already by the time we call down()
5182         */
5183        ret = wait_for_completion_interruptible(&ctx->ctx_restart_done);
5184
5185        DPRINT(("after block sleeping ret=%d\n", ret));
5186
5187        /*
5188         * lock context and mask interrupts again
5189         * We save flags into a dummy because we may have
5190         * altered interrupts mask compared to entry in this
5191         * function.
5192         */
5193        PROTECT_CTX(ctx, dummy_flags);
5194
5195        /*
5196         * we need to read the ovfl_regs only after wake-up
5197         * because we may have had pfm_write_pmds() in between
5198         * and that can changed PMD values and therefore
5199         * ovfl_regs is reset for these new PMD values.
5200         */
5201        ovfl_regs = ctx->ctx_ovfl_regs[0];
5202
5203        if (ctx->ctx_fl_going_zombie) {
5204do_zombie:
5205                DPRINT(("context is zombie, bailing out\n"));
5206                pfm_context_force_terminate(ctx, regs);
5207                goto nothing_to_do;
5208        }
5209        /*
5210         * in case of interruption of down() we don't restart anything
5211         */
5212        if (ret < 0) goto nothing_to_do;
5213
5214skip_blocking:
5215        pfm_resume_after_ovfl(ctx, ovfl_regs, regs);
5216        ctx->ctx_ovfl_regs[0] = 0UL;
5217
5218nothing_to_do:
5219        /*
5220         * restore flags as they were upon entry
5221         */
5222        UNPROTECT_CTX(ctx, flags);
5223}
5224
5225static int
5226pfm_notify_user(pfm_context_t *ctx, pfm_msg_t *msg)
5227{
5228        if (ctx->ctx_state == PFM_CTX_ZOMBIE) {
5229                DPRINT(("ignoring overflow notification, owner is zombie\n"));
5230                return 0;
5231        }
5232
5233        DPRINT(("waking up somebody\n"));
5234
5235        if (msg) wake_up_interruptible(&ctx->ctx_msgq_wait);
5236
5237        /*
5238         * safe, we are not in intr handler, nor in ctxsw when
5239         * we come here
5240         */
5241        kill_fasync (&ctx->ctx_async_queue, SIGIO, POLL_IN);
5242
5243        return 0;
5244}
5245
5246static int
5247pfm_ovfl_notify_user(pfm_context_t *ctx, unsigned long ovfl_pmds)
5248{
5249        pfm_msg_t *msg = NULL;
5250
5251        if (ctx->ctx_fl_no_msg == 0) {
5252                msg = pfm_get_new_msg(ctx);
5253                if (msg == NULL) {
5254                        printk(KERN_ERR "perfmon: pfm_ovfl_notify_user no more notification msgs\n");
5255                        return -1;
5256                }
5257
5258                msg->pfm_ovfl_msg.msg_type         = PFM_MSG_OVFL;
5259                msg->pfm_ovfl_msg.msg_ctx_fd       = ctx->ctx_fd;
5260                msg->pfm_ovfl_msg.msg_active_set   = 0;
5261                msg->pfm_ovfl_msg.msg_ovfl_pmds[0] = ovfl_pmds;
5262                msg->pfm_ovfl_msg.msg_ovfl_pmds[1] = 0UL;
5263                msg->pfm_ovfl_msg.msg_ovfl_pmds[2] = 0UL;
5264                msg->pfm_ovfl_msg.msg_ovfl_pmds[3] = 0UL;
5265                msg->pfm_ovfl_msg.msg_tstamp       = 0UL;
5266        }
5267
5268        DPRINT(("ovfl msg: msg=%p no_msg=%d fd=%d ovfl_pmds=0x%lx\n",
5269                msg,
5270                ctx->ctx_fl_no_msg,
5271                ctx->ctx_fd,
5272                ovfl_pmds));
5273
5274        return pfm_notify_user(ctx, msg);
5275}
5276
5277static int
5278pfm_end_notify_user(pfm_context_t *ctx)
5279{
5280        pfm_msg_t *msg;
5281
5282        msg = pfm_get_new_msg(ctx);
5283        if (msg == NULL) {
5284                printk(KERN_ERR "perfmon: pfm_end_notify_user no more notification msgs\n");
5285                return -1;
5286        }
5287        /* no leak */
5288        memset(msg, 0, sizeof(*msg));
5289
5290        msg->pfm_end_msg.msg_type    = PFM_MSG_END;
5291        msg->pfm_end_msg.msg_ctx_fd  = ctx->ctx_fd;
5292        msg->pfm_ovfl_msg.msg_tstamp = 0UL;
5293
5294        DPRINT(("end msg: msg=%p no_msg=%d ctx_fd=%d\n",
5295                msg,
5296                ctx->ctx_fl_no_msg,
5297                ctx->ctx_fd));
5298
5299        return pfm_notify_user(ctx, msg);
5300}
5301
5302/*
5303 * main overflow processing routine.
5304 * it can be called from the interrupt path or explicitely during the context switch code
5305 */
5306static void
5307pfm_overflow_handler(struct task_struct *task, pfm_context_t *ctx, u64 pmc0, struct pt_regs *regs)
5308{
5309        pfm_ovfl_arg_t *ovfl_arg;
5310        unsigned long mask;
5311        unsigned long old_val, ovfl_val, new_val;
5312        unsigned long ovfl_notify = 0UL, ovfl_pmds = 0UL, smpl_pmds = 0UL, reset_pmds;
5313        unsigned long tstamp;
5314        pfm_ovfl_ctrl_t ovfl_ctrl;
5315        unsigned int i, has_smpl;
5316        int must_notify = 0;
5317
5318        if (unlikely(ctx->ctx_state == PFM_CTX_ZOMBIE)) goto stop_monitoring;
5319
5320        /*
5321         * sanity test. Should never happen
5322         */
5323        if (unlikely((pmc0 & 0x1) == 0)) goto sanity_check;
5324
5325        tstamp   = ia64_get_itc();
5326        mask     = pmc0 >> PMU_FIRST_COUNTER;
5327        ovfl_val = pmu_conf->ovfl_val;
5328        has_smpl = CTX_HAS_SMPL(ctx);
5329
5330        DPRINT_ovfl(("pmc0=0x%lx pid=%d iip=0x%lx, %s "
5331                     "used_pmds=0x%lx\n",
5332                        pmc0,
5333                        task ? task->pid: -1,
5334                        (regs ? regs->cr_iip : 0),
5335                        CTX_OVFL_NOBLOCK(ctx) ? "nonblocking" : "blocking",
5336                        ctx->ctx_used_pmds[0]));
5337
5338
5339        /*
5340         * first we update the virtual counters
5341         * assume there was a prior ia64_srlz_d() issued
5342         */
5343        for (i = PMU_FIRST_COUNTER; mask ; i++, mask >>= 1) {
5344
5345                /* skip pmd which did not overflow */
5346                if ((mask & 0x1) == 0) continue;
5347
5348                /*
5349                 * Note that the pmd is not necessarily 0 at this point as qualified events
5350                 * may have happened before the PMU was frozen. The residual count is not
5351                 * taken into consideration here but will be with any read of the pmd via
5352                 * pfm_read_pmds().
5353                 */
5354                old_val              = new_val = ctx->ctx_pmds[i].val;
5355                new_val             += 1 + ovfl_val;
5356                ctx->ctx_pmds[i].val = new_val;
5357
5358                /*
5359                 * check for overflow condition
5360                 */
5361                if (likely(old_val > new_val)) {
5362                        ovfl_pmds |= 1UL << i;
5363                        if (PMC_OVFL_NOTIFY(ctx, i)) ovfl_notify |= 1UL << i;
5364                }
5365
5366                DPRINT_ovfl(("ctx_pmd[%d].val=0x%lx old_val=0x%lx pmd=0x%lx ovfl_pmds=0x%lx ovfl_notify=0x%lx\n",
5367                        i,
5368                        new_val,
5369                        old_val,
5370                        ia64_get_pmd(i) & ovfl_val,
5371                        ovfl_pmds,
5372                        ovfl_notify));
5373        }
5374
5375        /*
5376         * there was no 64-bit overflow, nothing else to do
5377         */
5378        if (ovfl_pmds == 0UL) return;
5379
5380        /*
5381         * reset all control bits
5382         */
5383        ovfl_ctrl.val = 0;
5384        reset_pmds    = 0UL;
5385
5386        /*
5387         * if a sampling format module exists, then we "cache" the overflow by
5388         * calling the module's handler() routine.
5389         */
5390        if (has_smpl) {
5391                unsigned long start_cycles, end_cycles;
5392                unsigned long pmd_mask;
5393                int j, k, ret = 0;
5394                int this_cpu = smp_processor_id();
5395
5396                pmd_mask = ovfl_pmds >> PMU_FIRST_COUNTER;
5397                ovfl_arg = &ctx->ctx_ovfl_arg;
5398
5399                prefetch(ctx->ctx_smpl_hdr);
5400
5401                for(i=PMU_FIRST_COUNTER; pmd_mask && ret == 0; i++, pmd_mask >>=1) {
5402
5403                        mask = 1UL << i;
5404
5405                        if ((pmd_mask & 0x1) == 0) continue;
5406
5407                        ovfl_arg->ovfl_pmd      = (unsigned char )i;
5408                        ovfl_arg->ovfl_notify   = ovfl_notify & mask ? 1 : 0;
5409                        ovfl_arg->active_set    = 0;
5410                        ovfl_arg->ovfl_ctrl.val = 0; /* module must fill in all fields */
5411                        ovfl_arg->smpl_pmds[0]  = smpl_pmds = ctx->ctx_pmds[i].smpl_pmds[0];
5412
5413                        ovfl_arg->pmd_value      = ctx->ctx_pmds[i].val;
5414                        ovfl_arg->pmd_last_reset = ctx->ctx_pmds[i].lval;
5415                        ovfl_arg->pmd_eventid    = ctx->ctx_pmds[i].eventid;
5416
5417                        /*
5418                         * copy values of pmds of interest. Sampling format may copy them
5419                         * into sampling buffer.
5420                         */
5421                        if (smpl_pmds) {
5422                                for(j=0, k=0; smpl_pmds; j++, smpl_pmds >>=1) {
5423                                        if ((smpl_pmds & 0x1) == 0) continue;
5424                                        ovfl_arg->smpl_pmds_values[k++] = PMD_IS_COUNTING(j) ?  pfm_read_soft_counter(ctx, j) : ia64_get_pmd(j);
5425                                        DPRINT_ovfl(("smpl_pmd[%d]=pmd%u=0x%lx\n", k-1, j, ovfl_arg->smpl_pmds_values[k-1]));
5426                                }
5427                        }
5428
5429                        pfm_stats[this_cpu].pfm_smpl_handler_calls++;
5430
5431                        start_cycles = ia64_get_itc();
5432
5433                        /*
5434                         * call custom buffer format record (handler) routine
5435                         */
5436                        ret = (*ctx->ctx_buf_fmt->fmt_handler)(task, ctx->ctx_smpl_hdr, ovfl_arg, regs, tstamp);
5437
5438                        end_cycles = ia64_get_itc();
5439
5440                        /*
5441                         * For those controls, we take the union because they have
5442                         * an all or nothing behavior.
5443                         */
5444                        ovfl_ctrl.bits.notify_user     |= ovfl_arg->ovfl_ctrl.bits.notify_user;
5445                        ovfl_ctrl.bits.block_task      |= ovfl_arg->ovfl_ctrl.bits.block_task;
5446                        ovfl_ctrl.bits.mask_monitoring |= ovfl_arg->ovfl_ctrl.bits.mask_monitoring;
5447                        /*
5448                         * build the bitmask of pmds to reset now
5449                         */
5450                        if (ovfl_arg->ovfl_ctrl.bits.reset_ovfl_pmds) reset_pmds |= mask;
5451
5452                        pfm_stats[this_cpu].pfm_smpl_handler_cycles += end_cycles - start_cycles;
5453                }
5454                /*
5455                 * when the module cannot handle the rest of the overflows, we abort right here
5456                 */
5457                if (ret && pmd_mask) {
5458                        DPRINT(("handler aborts leftover ovfl_pmds=0x%lx\n",
5459                                pmd_mask<<PMU_FIRST_COUNTER));
5460                }
5461                /*
5462                 * remove the pmds we reset now from the set of pmds to reset in pfm_restart()
5463                 */
5464                ovfl_pmds &= ~reset_pmds;
5465        } else {
5466                /*
5467                 * when no sampling module is used, then the default
5468                 * is to notify on overflow if requested by user
5469                 */
5470                ovfl_ctrl.bits.notify_user     = ovfl_notify ? 1 : 0;
5471                ovfl_ctrl.bits.block_task      = ovfl_notify ? 1 : 0;
5472                ovfl_ctrl.bits.mask_monitoring = ovfl_notify ? 1 : 0; /* XXX: change for saturation */
5473                ovfl_ctrl.bits.reset_ovfl_pmds = ovfl_notify ? 0 : 1;
5474                /*
5475                 * if needed, we reset all overflowed pmds
5476                 */
5477                if (ovfl_notify == 0) reset_pmds = ovfl_pmds;
5478        }
5479
5480        DPRINT_ovfl(("ovfl_pmds=0x%lx reset_pmds=0x%lx\n", ovfl_pmds, reset_pmds));
5481
5482        /*
5483         * reset the requested PMD registers using the short reset values
5484         */
5485        if (reset_pmds) {
5486                unsigned long bm = reset_pmds;
5487                pfm_reset_regs(ctx, &bm, PFM_PMD_SHORT_RESET);
5488        }
5489
5490        if (ovfl_notify && ovfl_ctrl.bits.notify_user) {
5491                /*
5492                 * keep track of what to reset when unblocking
5493                 */
5494                ctx->ctx_ovfl_regs[0] = ovfl_pmds;
5495
5496                /*
5497                 * check for blocking context
5498                 */
5499                if (CTX_OVFL_NOBLOCK(ctx) == 0 && ovfl_ctrl.bits.block_task) {
5500
5501                        ctx->ctx_fl_trap_reason = PFM_TRAP_REASON_BLOCK;
5502
5503                        /*
5504                         * set the perfmon specific checking pending work for the task
5505                         */
5506                        PFM_SET_WORK_PENDING(task, 1);
5507
5508                        /*
5509                         * when coming from ctxsw, current still points to the
5510                         * previous task, therefore we must work with task and not current.
5511                         */
5512                        pfm_set_task_notify(task);
5513                }
5514                /*
5515                 * defer until state is changed (shorten spin window). the context is locked
5516                 * anyway, so the signal receiver would come spin for nothing.
5517                 */
5518                must_notify = 1;
5519        }
5520
5521        DPRINT_ovfl(("owner [%d] pending=%ld reason=%u ovfl_pmds=0x%lx ovfl_notify=0x%lx masked=%d\n",
5522                        GET_PMU_OWNER() ? GET_PMU_OWNER()->pid : -1,
5523                        PFM_GET_WORK_PENDING(task),
5524                        ctx->ctx_fl_trap_reason,
5525                        ovfl_pmds,
5526                        ovfl_notify,
5527                        ovfl_ctrl.bits.mask_monitoring ? 1 : 0));
5528        /*
5529         * in case monitoring must be stopped, we toggle the psr bits
5530         */
5531        if (ovfl_ctrl.bits.mask_monitoring) {
5532                pfm_mask_monitoring(task);
5533                ctx->ctx_state = PFM_CTX_MASKED;
5534                ctx->ctx_fl_can_restart = 1;
5535        }
5536
5537        /*
5538         * send notification now
5539         */
5540        if (must_notify) pfm_ovfl_notify_user(ctx, ovfl_notify);
5541
5542        return;
5543
5544sanity_check:
5545        printk(KERN_ERR "perfmon: CPU%d overflow handler [%d] pmc0=0x%lx\n",
5546                        smp_processor_id(),
5547                        task ? task->pid : -1,
5548                        pmc0);
5549        return;
5550
5551stop_monitoring:
5552        /*
5553         * in SMP, zombie context is never restored but reclaimed in pfm_load_regs().
5554         * Moreover, zombies are also reclaimed in pfm_save_regs(). Therefore we can
5555         * come here as zombie only if the task is the current task. In which case, we
5556         * can access the PMU  hardware directly.
5557         *
5558         * Note that zombies do have PM_VALID set. So here we do the minimal.
5559         *
5560         * In case the context was zombified it could not be reclaimed at the time
5561         * the monitoring program exited. At this point, the PMU reservation has been
5562         * returned, the sampiing buffer has been freed. We must convert this call
5563         * into a spurious interrupt. However, we must also avoid infinite overflows
5564         * by stopping monitoring for this task. We can only come here for a per-task
5565         * context. All we need to do is to stop monitoring using the psr bits which
5566         * are always task private. By re-enabling secure montioring, we ensure that
5567         * the monitored task will not be able to re-activate monitoring.
5568         * The task will eventually be context switched out, at which point the context
5569         * will be reclaimed (that includes releasing ownership of the PMU).
5570         *
5571         * So there might be a window of time where the number of per-task session is zero
5572         * yet one PMU might have a owner and get at most one overflow interrupt for a zombie
5573         * context. This is safe because if a per-task session comes in, it will push this one
5574         * out and by the virtue on pfm_save_regs(), this one will disappear. If a system wide
5575         * session is force on that CPU, given that we use task pinning, pfm_save_regs() will
5576         * also push our zombie context out.
5577         *
5578         * Overall pretty hairy stuff....
5579         */
5580        DPRINT(("ctx is zombie for [%d], converted to spurious\n", task ? task->pid: -1));
5581        pfm_clear_psr_up();
5582        ia64_psr(regs)->up = 0;
5583        ia64_psr(regs)->sp = 1;
5584        return;
5585}
5586
5587static int
5588pfm_do_interrupt_handler(int irq, void *arg, struct pt_regs *regs)
5589{
5590        struct task_struct *task;
5591        pfm_context_t *ctx;
5592        unsigned long flags;
5593        u64 pmc0;
5594        int this_cpu = smp_processor_id();
5595        int retval = 0;
5596
5597        pfm_stats[this_cpu].pfm_ovfl_intr_count++;
5598
5599        /*
5600         * srlz.d done before arriving here
5601         */
5602        pmc0 = ia64_get_pmc(0);
5603
5604        task = GET_PMU_OWNER();
5605        ctx  = GET_PMU_CTX();
5606
5607        /*
5608         * if we have some pending bits set
5609         * assumes : if any PMC0.bit[63-1] is set, then PMC0.fr = 1
5610         */
5611        if (PMC0_HAS_OVFL(pmc0) && task) {
5612                /*
5613                 * we assume that pmc0.fr is always set here
5614                 */
5615
5616                /* sanity check */
5617                if (!ctx) goto report_spurious1;
5618
5619                if (ctx->ctx_fl_system == 0 && (task->thread.flags & IA64_THREAD_PM_VALID) == 0) 
5620                        goto report_spurious2;
5621
5622                PROTECT_CTX_NOPRINT(ctx, flags);
5623
5624                pfm_overflow_handler(task, ctx, pmc0, regs);
5625
5626                UNPROTECT_CTX_NOPRINT(ctx, flags);
5627
5628        } else {
5629                pfm_stats[this_cpu].pfm_spurious_ovfl_intr_count++;
5630                retval = -1;
5631        }
5632        /*
5633         * keep it unfrozen at all times
5634         */
5635        pfm_unfreeze_pmu();
5636
5637        return retval;
5638
5639report_spurious1:
5640        printk(KERN_INFO "perfmon: spurious overflow interrupt on CPU%d: process %d has no PFM context\n",
5641                this_cpu, task->pid);
5642        pfm_unfreeze_pmu();
5643        return -1;
5644report_spurious2:
5645        printk(KERN_INFO "perfmon: spurious overflow interrupt on CPU%d: process %d, invalid flag\n", 
5646                this_cpu, 
5647                task->pid);
5648        pfm_unfreeze_pmu();
5649        return -1;
5650}
5651
5652static irqreturn_t
5653pfm_interrupt_handler(int irq, void *arg, struct pt_regs *regs)
5654{
5655        unsigned long start_cycles, total_cycles;
5656        unsigned long min, max;
5657        int this_cpu;
5658        int ret;
5659
5660        this_cpu = get_cpu();
5661        if (likely(!pfm_alt_intr_handler)) {
5662                min = pfm_stats[this_cpu].pfm_ovfl_intr_cycles_min;
5663                max = pfm_stats[this_cpu].pfm_ovfl_intr_cycles_max;
5664
5665                start_cycles = ia64_get_itc();
5666
5667                ret = pfm_do_interrupt_handler(irq, arg, regs);
5668
5669                total_cycles = ia64_get_itc();
5670
5671                /*
5672                 * don't measure spurious interrupts
5673                 */
5674                if (likely(ret == 0)) {
5675                        total_cycles -= start_cycles;
5676
5677                        if (total_cycles < min) pfm_stats[this_cpu].pfm_ovfl_intr_cycles_min = total_cycles;
5678                        if (total_cycles > max) pfm_stats[this_cpu].pfm_ovfl_intr_cycles_max = total_cycles;
5679
5680                        pfm_stats[this_cpu].pfm_ovfl_intr_cycles += total_cycles;
5681                }
5682        }
5683        else {
5684                (*pfm_alt_intr_handler->handler)(irq, arg, regs);
5685        }
5686
5687        put_cpu_no_resched();
5688        return IRQ_HANDLED;
5689}
5690
5691/*
5692 * /proc/perfmon interface, for debug only
5693 */
5694
5695#define PFM_PROC_SHOW_HEADER    ((void *)NR_CPUS+1)
5696
5697static void *
5698pfm_proc_start(struct seq_file *m, loff_t *pos)
5699{
5700        if (*pos == 0) {
5701                return PFM_PROC_SHOW_HEADER;
5702        }
5703
5704        while (*pos <= NR_CPUS) {
5705                if (cpu_online(*pos - 1)) {
5706                        return (void *)*pos;
5707                }
5708                ++*pos;
5709        }
5710        return NULL;
5711}
5712
5713static void *
5714pfm_proc_next(struct seq_file *m, void *v, loff_t *pos)
5715{
5716        ++*pos;
5717        return pfm_proc_start(m, pos);
5718}
5719
5720static void
5721pfm_proc_stop(struct seq_file *m, void *v)
5722{
5723}
5724
5725static void
5726pfm_proc_show_header(struct seq_file *m)
5727{
5728        struct list_head * pos;
5729        pfm_buffer_fmt_t * entry;
5730        unsigned long flags;
5731
5732        seq_printf(m,
5733                "perfmon version           : %u.%u\n"
5734                "model                     : %s\n"
5735                "fastctxsw                 : %s\n"
5736                "expert mode               : %s\n"
5737                "ovfl_mask                 : 0x%lx\n"
5738                "PMU flags                 : 0x%x\n",
5739                PFM_VERSION_MAJ, PFM_VERSION_MIN,
5740                pmu_conf->pmu_name,
5741                pfm_sysctl.fastctxsw > 0 ? "Yes": "No",
5742                pfm_sysctl.expert_mode > 0 ? "Yes": "No",
5743                pmu_conf->ovfl_val,
5744                pmu_conf->flags);
5745
5746        LOCK_PFS(flags);
5747
5748        seq_printf(m,
5749                "proc_sessions             : %u\n"
5750                "sys_sessions              : %u\n"
5751                "sys_use_dbregs            : %u\n"
5752                "ptrace_use_dbregs         : %u\n",
5753                pfm_sessions.pfs_task_sessions,
5754                pfm_sessions.pfs_sys_sessions,
5755                pfm_sessions.pfs_sys_use_dbregs,
5756                pfm_sessions.pfs_ptrace_use_dbregs);
5757
5758        UNLOCK_PFS(flags);
5759
5760        spin_lock(&pfm_buffer_fmt_lock);
5761
5762        list_for_each(pos, &pfm_buffer_fmt_list) {
5763                entry = list_entry(pos, pfm_buffer_fmt_t, fmt_list);
5764                seq_printf(m, "format                    : %02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x %s\n",
5765                        entry->fmt_uuid[0],
5766                        entry->fmt_uuid[1],
5767                        entry->fmt_uuid[2],
5768                        entry->fmt_uuid[3],
5769                        entry->fmt_uuid[4],
5770                        entry->fmt_uuid[5],
5771                        entry->fmt_uuid[6],
5772                        entry->fmt_uuid[7],
5773                        entry->fmt_uuid[8],
5774                        entry->fmt_uuid[9],
5775                        entry->fmt_uuid[10],
5776                        entry->fmt_uuid[11],
5777                        entry->fmt_uuid[12],
5778                        entry->fmt_uuid[13],
5779                        entry->fmt_uuid[14],
5780                        entry->fmt_uuid[15],
5781                        entry->fmt_name);
5782        }
5783        spin_unlock(&pfm_buffer_fmt_lock);
5784
5785}
5786
5787static int
5788pfm_proc_show(struct seq_file *m, void *v)
5789{
5790        unsigned long psr;
5791        unsigned int i;
5792        int cpu;
5793
5794        if (v == PFM_PROC_SHOW_HEADER) {
5795                pfm_proc_show_header(m);
5796                return 0;
5797        }
5798
5799        /* show info for CPU (v - 1) */
5800
5801        cpu = (long)v - 1;
5802        seq_printf(m,
5803                "CPU%-2d overflow intrs      : %lu\n"
5804                "CPU%-2d overflow cycles     : %lu\n"
5805                "CPU%-2d overflow min        : %lu\n"
5806                "CPU%-2d overflow max        : %lu\n"
5807                "CPU%-2d smpl handler calls  : %lu\n"
5808                "CPU%-2d smpl handler cycles : %lu\n"
5809                "CPU%-2d spurious intrs      : %lu\n"
5810                "CPU%-2d replay   intrs      : %lu\n"
5811                "CPU%-2d syst_wide           : %d\n"
5812                "CPU%-2d dcr_pp              : %d\n"
5813                "CPU%-2d exclude idle        : %d\n"
5814                "CPU%-2d owner               : %d\n"
5815                "CPU%-2d context             : %p\n"
5816                "CPU%-2d activations         : %lu\n",
5817                cpu, pfm_stats[cpu].pfm_ovfl_intr_count,
5818                cpu, pfm_stats[cpu].pfm_ovfl_intr_cycles,
5819                cpu, pfm_stats[cpu].pfm_ovfl_intr_cycles_min,
5820                cpu, pfm_stats[cpu].pfm_ovfl_intr_cycles_max,
5821                cpu, pfm_stats[cpu].pfm_smpl_handler_calls,
5822                cpu, pfm_stats[cpu].pfm_smpl_handler_cycles,
5823                cpu, pfm_stats[cpu].pfm_spurious_ovfl_intr_count,
5824                cpu, pfm_stats[cpu].pfm_replay_ovfl_intr_count,
5825                cpu, pfm_get_cpu_data(pfm_syst_info, cpu) & PFM_CPUINFO_SYST_WIDE ? 1 : 0,
5826                cpu, pfm_get_cpu_data(pfm_syst_info, cpu) & PFM_CPUINFO_DCR_PP ? 1 : 0,
5827                cpu, pfm_get_cpu_data(pfm_syst_info, cpu) & PFM_CPUINFO_EXCL_IDLE ? 1 : 0,
5828                cpu, pfm_get_cpu_data(pmu_owner, cpu) ? pfm_get_cpu_data(pmu_owner, cpu)->pid: -1,
5829                cpu, pfm_get_cpu_data(pmu_ctx, cpu),
5830                cpu, pfm_get_cpu_data(pmu_activation_number, cpu));
5831
5832        if (num_online_cpus() == 1 && pfm_sysctl.debug > 0) {
5833
5834                psr = pfm_get_psr();
5835
5836                ia64_srlz_d();
5837
5838                seq_printf(m, 
5839                        "CPU%-2d psr                 : 0x%lx\n"
5840                        "CPU%-2d pmc0                : 0x%lx\n", 
5841                        cpu, psr,
5842                        cpu, ia64_get_pmc(0));
5843
5844                for (i=0; PMC_IS_LAST(i) == 0;  i++) {
5845                        if (PMC_IS_COUNTING(i) == 0) continue;
5846                        seq_printf(m, 
5847                                "CPU%-2d pmc%u                : 0x%lx\n"
5848                                "CPU%-2d pmd%u                : 0x%lx\n", 
5849                                cpu, i, ia64_get_pmc(i),
5850                                cpu, i, ia64_get_pmd(i));
5851                }
5852        }
5853        return 0;
5854}
5855
5856struct seq_operations pfm_seq_ops = {
5857        .start =        pfm_proc_start,
5858        .next =         pfm_proc_next,
5859        .stop =         pfm_proc_stop,
5860        .show =         pfm_proc_show
5861};
5862
5863static int
5864pfm_proc_open(struct inode *inode, struct file *file)
5865{
5866        return seq_open(file, &pfm_seq_ops);
5867}
5868
5869
5870/*
5871 * we come here as soon as local_cpu_data->pfm_syst_wide is set. this happens
5872 * during pfm_enable() hence before pfm_start(). We cannot assume monitoring
5873 * is active or inactive based on mode. We must rely on the value in
5874 * local_cpu_data->pfm_syst_info
5875 */
5876void
5877pfm_syst_wide_update_task(struct task_struct *task, unsigned long info, int is_ctxswin)
5878{
5879        struct pt_regs *regs;
5880        unsigned long dcr;
5881        unsigned long dcr_pp;
5882
5883        dcr_pp = info & PFM_CPUINFO_DCR_PP ? 1 : 0;
5884
5885        /*
5886         * pid 0 is guaranteed to be the idle task. There is one such task with pid 0
5887         * on every CPU, so we can rely on the pid to identify the idle task.
5888         */
5889        if ((info & PFM_CPUINFO_EXCL_IDLE) == 0 || task->pid) {
5890                regs = task_pt_regs(task);
5891                ia64_psr(regs)->pp = is_ctxswin ? dcr_pp : 0;
5892                return;
5893        }
5894        /*
5895         * if monitoring has started
5896         */
5897        if (dcr_pp) {
5898                dcr = ia64_getreg(_IA64_REG_CR_DCR);
5899                /*
5900                 * context switching in?
5901                 */
5902                if (is_ctxswin) {
5903                        /* mask monitoring for the idle task */
5904                        ia64_setreg(_IA64_REG_CR_DCR, dcr & ~IA64_DCR_PP);
5905                        pfm_clear_psr_pp();
5906                        ia64_srlz_i();
5907                        return;
5908                }
5909                /*
5910                 * context switching out
5911                 * restore monitoring for next task
5912                 *
5913                 * Due to inlining this odd if-then-else construction generates
5914                 * better code.
5915                 */
5916                ia64_setreg(_IA64_REG_CR_DCR, dcr |IA64_DCR_PP);
5917                pfm_set_psr_pp();
5918                ia64_srlz_i();
5919        }
5920}
5921
5922#ifdef CONFIG_SMP
5923
5924static void
5925pfm_force_cleanup(pfm_context_t *ctx, struct pt_regs *regs)
5926{
5927        struct task_struct *task = ctx->ctx_task;
5928
5929        ia64_psr(regs)->up = 0;
5930        ia64_psr(regs)->sp = 1;
5931
5932        if (GET_PMU_OWNER() == task) {
5933                DPRINT(("cleared ownership for [%d]\n", ctx->ctx_task->pid));
5934                SET_PMU_OWNER(NULL, NULL);
5935        }
5936
5937        /*
5938         * disconnect the task from the context and vice-versa
5939         */
5940        PFM_SET_WORK_PENDING(task, 0);
5941
5942        task->thread.pfm_context  = NULL;
5943        task->thread.flags       &= ~IA64_THREAD_PM_VALID;
5944
5945        DPRINT(("force cleanup for [%d]\n",  task->pid));
5946}
5947
5948
5949/*
5950 * in 2.6, interrupts are masked when we come here and the runqueue lock is held
5951 */
5952void
5953pfm_save_regs(struct task_struct *task)
5954{
5955        pfm_context_t *ctx;
5956        struct thread_struct *t;
5957        unsigned long flags;
5958        u64 psr;
5959
5960
5961        ctx = PFM_GET_CTX(task);
5962        if (ctx == NULL) return;
5963        t = &task->thread;
5964
5965        /*
5966         * we always come here with interrupts ALREADY disabled by
5967         * the scheduler. So we simply need to protect against concurrent
5968         * access, not CPU concurrency.
5969         */
5970        flags = pfm_protect_ctx_ctxsw(ctx);
5971
5972        if (ctx->ctx_state == PFM_CTX_ZOMBIE) {
5973                struct pt_regs *regs = task_pt_regs(task);
5974
5975                pfm_clear_psr_up();
5976
5977                pfm_force_cleanup(ctx, regs);
5978
5979                BUG_ON(ctx->ctx_smpl_hdr);
5980
5981                pfm_unprotect_ctx_ctxsw(ctx, flags);
5982
5983                pfm_context_free(ctx);
5984                return;
5985        }
5986
5987        /*
5988         * save current PSR: needed because we modify it
5989         */
5990        ia64_srlz_d();
5991        psr = pfm_get_psr();
5992
5993        BUG_ON(psr & (IA64_PSR_I));
5994
5995        /*
5996         * stop monitoring:
5997         * This is the last instruction which may generate an overflow
5998         *
5999         * We do not need to set psr.sp because, it is irrelevant in kernel.
6000         * It will be restored from ipsr when going back to user level
6001         */
6002        pfm_clear_psr_up();
6003
6004        /*
6005         * keep a copy of psr.up (for reload)
6006         */
6007        ctx->ctx_saved_psr_up = psr & IA64_PSR_UP;
6008
6009        /*
6010         * release ownership of this PMU.
6011         * PM interrupts are masked, so nothing
6012         * can happen.
6013         */
6014        SET_PMU_OWNER(NULL, NULL);
6015
6016        /*
6017         * we systematically save the PMD as we have no
6018         * guarantee we will be schedule at that same
6019         * CPU again.
6020         */
6021        pfm_save_pmds(t->pmds, ctx->ctx_used_pmds[0]);
6022
6023        /*
6024         * save pmc0 ia64_srlz_d() done in pfm_save_pmds()
6025         * we will need it on the restore path to check
6026         * for pending overflow.
6027         */
6028        t->pmcs[0] = ia64_get_pmc(0);
6029
6030        /*
6031         * unfreeze PMU if had pending overflows
6032         */
6033        if (t->pmcs[0] & ~0x1UL) pfm_unfreeze_pmu();
6034
6035        /*
6036         * finally, allow context access.
6037         * interrupts will still be masked after this call.
6038         */
6039        pfm_unprotect_ctx_ctxsw(ctx, flags);
6040}
6041
6042#else /* !CONFIG_SMP */
6043void
6044pfm_save_regs(struct task_struct *task)
6045{
6046        pfm_context_t *ctx;
6047        u64 psr;
6048
6049        ctx = PFM_GET_CTX(task);
6050        if (ctx == NULL) return;
6051
6052        /*
6053         * save current PSR: needed because we modify it
6054         */
6055        psr = pfm_get_psr();
6056
6057        BUG_ON(psr & (IA64_PSR_I));
6058
6059        /*
6060         * stop monitoring:
6061         * This is the last instruction which may generate an overflow
6062         *
6063         * We do not need to set psr.sp because, it is irrelevant in kernel.
6064         * It will be restored from ipsr when going back to user level
6065         */
6066        pfm_clear_psr_up();
6067
6068        /*
6069         * keep a copy of psr.up (for reload)
6070         */
6071        ctx->ctx_saved_psr_up = psr & IA64_PSR_UP;
6072}
6073
6074static void
6075pfm_lazy_save_regs (struct task_struct *task)
6076{
6077        pfm_context_t *ctx;
6078        struct thread_struct *t;
6079        unsigned long flags;
6080
6081        { u64 psr  = pfm_get_psr();
6082          BUG_ON(psr & IA64_PSR_UP);
6083        }
6084
6085        ctx = PFM_GET_CTX(task);
6086        t   = &task->thread;
6087
6088        /*
6089         * we need to mask PMU overflow here to
6090         * make sure that we maintain pmc0 until
6091         * we save it. overflow interrupts are
6092         * treated as spurious if there is no
6093         * owner.
6094         *
6095         * XXX: I don't think this is necessary
6096         */
6097        PROTECT_CTX(ctx,flags);
6098
6099        /*
6100         * release ownership of this PMU.
6101         * must be done before we save the registers.
6102         *
6103         * after this call any PMU interrupt is treated
6104         * as spurious.
6105         */
6106        SET_PMU_OWNER(NULL, NULL);
6107
6108        /*
6109         * save all the pmds we use
6110         */
6111        pfm_save_pmds(t->pmds, ctx->ctx_used_pmds[0]);
6112
6113        /*
6114         * save pmc0 ia64_srlz_d() done in pfm_save_pmds()
6115         * it is needed to check for pended overflow
6116         * on the restore path
6117         */
6118        t->pmcs[0] = ia64_get_pmc(0);
6119
6120        /*
6121         * unfreeze PMU if had pending overflows
6122         */
6123        if (t->pmcs[0] & ~0x1UL) pfm_unfreeze_pmu();
6124
6125        /*
6126         * now get can unmask PMU interrupts, they will
6127         * be treated as purely spurious and we will not
6128         * lose any information
6129         */
6130        UNPROTECT_CTX(ctx,flags);
6131}
6132#endif /* CONFIG_SMP */
6133
6134#ifdef CONFIG_SMP
6135/*
6136 * in 2.6, interrupts are masked when we come here and the runqueue lock is held
6137 */
6138void
6139pfm_load_regs (struct task_struct *task)
6140{
6141        pfm_context_t *ctx;
6142        struct thread_struct *t;
6143        unsigned long pmc_mask = 0UL, pmd_mask = 0UL;
6144        unsigned long flags;
6145        u64 psr, psr_up;
6146        int need_irq_resend;
6147
6148        ctx = PFM_GET_CTX(task);
6149        if (unlikely(ctx == NULL)) return;
6150
6151        BUG_ON(GET_PMU_OWNER());
6152
6153        t     = &task->thread;
6154        /*
6155         * possible on unload
6156         */
6157        if (unlikely((t->flags & IA64_THREAD_PM_VALID) == 0)) return;
6158
6159        /*
6160         * we always come here with interrupts ALREADY disabled by
6161         * the scheduler. So we simply need to protect against concurrent
6162         * access, not CPU concurrency.
6163         */
6164        flags = pfm_protect_ctx_ctxsw(ctx);
6165        psr   = pfm_get_psr();
6166
6167        need_irq_resend = pmu_conf->flags & PFM_PMU_IRQ_RESEND;
6168
6169        BUG_ON(psr & (IA64_PSR_UP|IA64_PSR_PP));
6170        BUG_ON(psr & IA64_PSR_I);
6171
6172        if (unlikely(ctx->ctx_state == PFM_CTX_ZOMBIE)) {
6173                struct pt_regs *regs = task_pt_regs(task);
6174
6175                BUG_ON(ctx->ctx_smpl_hdr);
6176
6177                pfm_force_cleanup(ctx, regs);
6178
6179                pfm_unprotect_ctx_ctxsw(ctx, flags);
6180
6181                /*
6182                 * this one (kmalloc'ed) is fine with interrupts disabled
6183                 */
6184                pfm_context_free(ctx);
6185
6186                return;
6187        }
6188
6189        /*
6190         * we restore ALL the debug registers to avoid picking up
6191         * stale state.
6192         */
6193        if (ctx->ctx_fl_using_dbreg) {
6194                pfm_restore_ibrs(ctx->ctx_ibrs, pmu_conf->num_ibrs);
6195                pfm_restore_dbrs(ctx->ctx_dbrs, pmu_conf->num_dbrs);
6196        }
6197        /*
6198         * retrieve saved psr.up
6199         */
6200        psr_up = ctx->ctx_saved_psr_up;
6201
6202        /*
6203         * if we were the last user of the PMU on that CPU,
6204         * then nothing to do except restore psr
6205         */
6206        if (GET_LAST_CPU(ctx) == smp_processor_id() && ctx->ctx_last_activation == GET_ACTIVATION()) {
6207
6208                /*
6209                 * retrieve partial reload masks (due to user modifications)
6210                 */
6211                pmc_mask = ctx->ctx_reload_pmcs[0];
6212                pmd_mask = ctx->ctx_reload_pmds[0];
6213
6214        } else {
6215                /*
6216                 * To avoid leaking information to the user level when psr.sp=0,
6217                 * we must reload ALL implemented pmds (even the ones we don't use).
6218                 * In the kernel we only allow PFM_READ_PMDS on registers which
6219                 * we initialized or requested (sampling) so there is no risk there.
6220                 */
6221                pmd_mask = pfm_sysctl.fastctxsw ?  ctx->ctx_used_pmds[0] : ctx->ctx_all_pmds[0];
6222
6223                /*
6224                 * ALL accessible PMCs are systematically reloaded, unused registers
6225                 * get their default (from pfm_reset_pmu_state()) values to avoid picking
6226                 * up stale configuration.
6227                 *
6228                 * PMC0 is never in the mask. It is always restored separately.
6229                 */
6230                pmc_mask = ctx->ctx_all_pmcs[0];
6231        }
6232        /*
6233         * when context is MASKED, we will restore PMC with plm=0
6234         * and PMD with stale information, but that's ok, nothing
6235         * will be captured.
6236         *
6237         * XXX: optimize here
6238         */
6239        if (pmd_mask) pfm_restore_pmds(t->pmds, pmd_mask);
6240        if (pmc_mask) pfm_restore_pmcs(t->pmcs, pmc_mask);
6241
6242        /*
6243         * check for pending overflow at the time the state
6244         * was saved.
6245         */
6246        if (unlikely(PMC0_HAS_OVFL(t->pmcs[0]))) {
6247                /*
6248                 * reload pmc0 with the overflow information
6249                 * On McKinley PMU, this will trigger a PMU interrupt
6250                 */
6251                ia64_set_pmc(0, t->pmcs[0]);
6252                ia64_srlz_d();
6253                t->pmcs[0] = 0UL;
6254
6255                /*
6256                 * will replay the PMU interrupt
6257                 */
6258                if (need_irq_resend) ia64_resend_irq(IA64_PERFMON_VECTOR);
6259
6260                pfm_stats[smp_processor_id()].pfm_replay_ovfl_intr_count++;
6261        }
6262
6263        /*
6264         * we just did a reload, so we reset the partial reload fields
6265         */
6266        ctx->ctx_reload_pmcs[0] = 0UL;
6267        ctx->ctx_reload_pmds[0] = 0UL;
6268
6269        SET_LAST_CPU(ctx, smp_processor_id());
6270
6271        /*
6272         * dump activation value for this PMU
6273         */
6274        INC_ACTIVATION();
6275        /*
6276         * record current activation for this context
6277         */
6278        SET_ACTIVATION(ctx);
6279
6280        /*
6281         * establish new ownership.
6282         */
6283        SET_PMU_OWNER(task, ctx);
6284
6285        /*
6286         * restore the psr.up bit. measurement
6287         * is active again.
6288         * no PMU interrupt can happen at this point
6289         * because we still have interrupts disabled.
6290         */
6291        if (likely(psr_up)) pfm_set_psr_up();
6292
6293        /*
6294         * allow concurrent access to context
6295         */
6296        pfm_unprotect_ctx_ctxsw(ctx, flags);
6297}
6298#else /*  !CONFIG_SMP */
6299/*
6300 * reload PMU state for UP kernels
6301 * in 2.5 we come here with interrupts disabled
6302 */
6303void
6304pfm_load_regs (struct task_struct *task)
6305{
6306        struct thread_struct *t;
6307        pfm_context_t *ctx;
6308        struct task_struct *owner;
6309        unsigned long pmd_mask, pmc_mask;
6310        u64 psr, psr_up;
6311        int need_irq_resend;
6312
6313        owner = GET_PMU_OWNER();
6314        ctx   = PFM_GET_CTX(task);
6315        t     = &task->thread;
6316        psr   = pfm_get_psr();
6317
6318        BUG_ON(psr & (IA64_PSR_UP|IA64_PSR_PP));
6319        BUG_ON(psr & IA64_PSR_I);
6320
6321        /*
6322         * we restore ALL the debug registers to avoid picking up
6323         * stale state.
6324         *
6325         * This must be done even when the task is still the owner
6326         * as the registers may have been modified via ptrace()
6327         * (not perfmon) by the previous task.
6328         */
6329        if (ctx->ctx_fl_using_dbreg) {
6330                pfm_restore_ibrs(ctx->ctx_ibrs, pmu_conf->num_ibrs);
6331                pfm_restore_dbrs(ctx->ctx_dbrs, pmu_conf->num_dbrs);
6332        }
6333
6334        /*
6335         * retrieved saved psr.up
6336         */
6337        psr_up = ctx->ctx_saved_psr_up;
6338        need_irq_resend = pmu_conf->flags & PFM_PMU_IRQ_RESEND;
6339
6340        /*
6341         * short path, our state is still there, just
6342         * need to restore psr and we go
6343         *
6344         * we do not touch either PMC nor PMD. the psr is not touched
6345         * by the overflow_handler. So we are safe w.r.t. to interrupt
6346         * concurrency even without interrupt masking.
6347         */
6348        if (likely(owner == task)) {
6349                if (likely(psr_up)) pfm_set_psr_up();
6350                return;
6351        }
6352
6353        /*
6354         * someone else is still using the PMU, first push it out and
6355         * then we'll be able to install our stuff !
6356         *
6357         * Upon return, there will be no owner for the current PMU
6358         */
6359        if (owner) pfm_lazy_save_regs(owner);
6360
6361        /*
6362         * To avoid leaking information to the user level when psr.sp=0,
6363         * we must reload ALL implemented pmds (even the ones we don't use).
6364         * In the kernel we only allow PFM_READ_PMDS on registers which
6365         * we initialized or requested (sampling) so there is no risk there.
6366         */
6367        pmd_mask = pfm_sysctl.fastctxsw ?  ctx->ctx_used_pmds[0] : ctx->ctx_all_pmds[0];
6368
6369        /*
6370         * ALL accessible PMCs are systematically reloaded, unused registers
6371         * get their default (from pfm_reset_pmu_state()) values to avoid picking
6372         * up stale configuration.
6373         *
6374         * PMC0 is never in the mask. It is always restored separately
6375         */
6376        pmc_mask = ctx->ctx_all_pmcs[0];
6377
6378        pfm_restore_pmds(t->pmds, pmd_mask);
6379        pfm_restore_pmcs(t->pmcs, pmc_mask);
6380
6381        /*
6382         * check for pending overflow at the time the state
6383         * was saved.
6384         */
6385        if (unlikely(PMC0_HAS_OVFL(t->pmcs[0]))) {
6386                /*
6387                 * reload pmc0 with the overflow information
6388                 * On McKinley PMU, this will trigger a PMU interrupt
6389                 */
6390                ia64_set_pmc(0, t->pmcs[0]);
6391                ia64_srlz_d();
6392
6393                t->pmcs[0] = 0UL;
6394
6395                /*
6396                 * will replay the PMU interrupt
6397                 */
6398                if (need_irq_resend) ia64_resend_irq(IA64_PERFMON_VECTOR);
6399
6400                pfm_stats[smp_processor_id()].pfm_replay_ovfl_intr_count++;
6401        }
6402
6403        /*
6404         * establish new ownership.
6405         */
6406        SET_PMU_OWNER(task, ctx);
6407
6408        /*
6409         * restore the psr.up bit. measurement
6410         * is active again.
6411         * no PMU interrupt can happen at this point
6412         * because we still have interrupts disabled.
6413         */
6414        if (likely(psr_up)) pfm_set_psr_up();
6415}
6416#endif /* CONFIG_SMP */
6417
6418/*
6419 * this function assumes monitoring is stopped
6420 */
6421static void
6422pfm_flush_pmds(struct task_struct *task, pfm_context_t *ctx)
6423{
6424        u64 pmc0;
6425        unsigned long mask2, val, pmd_val, ovfl_val;
6426        int i, can_access_pmu = 0;
6427        int is_self;
6428
6429        /*
6430         * is the caller the task being monitored (or which initiated the
6431         * session for system wide measurements)
6432         */
6433        is_self = ctx->ctx_task == task ? 1 : 0;
6434
6435        /*
6436         * can access PMU is task is the owner of the PMU state on the current CPU
6437         * or if we are running on the CPU bound to the context in system-wide mode
6438         * (that is not necessarily the task the context is attached to in this mode).
6439         * In system-wide we always have can_access_pmu true because a task running on an
6440         * invalid processor is flagged earlier in the call stack (see pfm_stop).
6441         */
6442        can_access_pmu = (GET_PMU_OWNER() == task) || (ctx->ctx_fl_system && ctx->ctx_cpu == smp_processor_id());
6443        if (can_access_pmu) {
6444                /*
6445                 * Mark the PMU as not owned
6446                 * This will cause the interrupt handler to do nothing in case an overflow
6447                 * interrupt was in-flight
6448                 * This also guarantees that pmc0 will contain the final state
6449                 * It virtually gives us full control on overflow processing from that point
6450                 * on.
6451                 */
6452                SET_PMU_OWNER(NULL, NULL);
6453                DPRINT(("releasing ownership\n"));
6454
6455                /*
6456                 * read current overflow status:
6457                 *
6458                 * we are guaranteed to read the final stable state
6459                 */
6460                ia64_srlz_d();
6461                pmc0 = ia64_get_pmc(0); /* slow */
6462
6463                /*
6464                 * reset freeze bit, overflow status information destroyed
6465                 */
6466                pfm_unfreeze_pmu();
6467        } else {
6468                pmc0 = task->thread.pmcs[0];
6469                /*
6470                 * clear whatever overflow status bits there were
6471                 */
6472                task->thread.pmcs[0] = 0;
6473        }
6474        ovfl_val = pmu_conf->ovfl_val;
6475        /*
6476         * we save all the used pmds
6477         * we take care of overflows for counting PMDs
6478         *
6479         * XXX: sampling situation is not taken into account here
6480         */
6481        mask2 = ctx->ctx_used_pmds[0];
6482
6483        DPRINT(("is_self=%d ovfl_val=0x%lx mask2=0x%lx\n", is_self, ovfl_val, mask2));
6484
6485        for (i = 0; mask2; i++, mask2>>=1) {
6486
6487                /* skip non used pmds */
6488                if ((mask2 & 0x1) == 0) continue;
6489
6490                /*
6491                 * can access PMU always true in system wide mode
6492                 */
6493                val = pmd_val = can_access_pmu ? ia64_get_pmd(i) : task->thread.pmds[i];
6494
6495                if (PMD_IS_COUNTING(i)) {
6496                        DPRINT(("[%d] pmd[%d] ctx_pmd=0x%lx hw_pmd=0x%lx\n",
6497                                task->pid,
6498                                i,
6499                                ctx->ctx_pmds[i].val,
6500                                val & ovfl_val));
6501
6502                        /*
6503                         * we rebuild the full 64 bit value of the counter
6504                         */
6505                        val = ctx->ctx_pmds[i].val + (val & ovfl_val);
6506
6507                        /*
6508                         * now everything is in ctx_pmds[] and we need
6509                         * to clear the saved context from save_regs() such that
6510                         * pfm_read_pmds() gets the correct value
6511                         */
6512                        pmd_val = 0UL;
6513
6514                        /*
6515                         * take care of overflow inline
6516                         */
6517                        if (pmc0 & (1UL << i)) {
6518                                val += 1 + ovfl_val;
6519                                DPRINT(("[%d] pmd[%d] overflowed\n", task->pid, i));
6520                        }
6521                }
6522
6523                DPRINT(("[%d] ctx_pmd[%d]=0x%lx  pmd_val=0x%lx\n", task->pid, i, val, pmd_val));
6524
6525                if (is_self) task->thread.pmds[i] = pmd_val;
6526
6527                ctx->ctx_pmds[i].val = val;
6528        }
6529}
6530
6531static struct irqaction perfmon_irqaction = {
6532        .handler = pfm_interrupt_handler,
6533        .flags   = IRQF_DISABLED,
6534        .name    = "perfmon"
6535};
6536
6537static void
6538pfm_alt_save_pmu_state(void *data)
6539{
6540        struct pt_regs *regs;
6541
6542        regs = task_pt_regs(current);
6543
6544        DPRINT(("called\n"));
6545
6546        /*
6547         * should not be necessary but
6548         * let's take not risk
6549         */
6550        pfm_clear_psr_up();
6551        pfm_clear_psr_pp();
6552        ia64_psr(regs)->pp = 0;
6553
6554        /*
6555         * This call is required
6556         * May cause a spurious interrupt on some processors
6557         */
6558        pfm_freeze_pmu();
6559
6560        ia64_srlz_d();
6561}
6562
6563void
6564pfm_alt_restore_pmu_state(void *data)
6565{
6566        struct pt_regs *regs;
6567
6568        regs = task_pt_regs(current);
6569
6570        DPRINT(("called\n"));
6571
6572        /*
6573         * put PMU back in state expected
6574         * by perfmon
6575         */
6576        pfm_clear_psr_up();
6577        pfm_clear_psr_pp();
6578        ia64_psr(regs)->pp = 0;
6579
6580        /*
6581         * perfmon runs with PMU unfrozen at all times
6582         */
6583        pfm_unfreeze_pmu();
6584
6585        ia64_srlz_d();
6586}
6587
6588int
6589pfm_install_alt_pmu_interrupt(pfm_intr_handler_desc_t *hdl)
6590{
6591        int ret, i;
6592        int reserve_cpu;
6593
6594        /* some sanity checks */
6595        if (hdl == NULL || hdl->handler == NULL) return -EINVAL;
6596
6597        /* do the easy test first */
6598        if (pfm_alt_intr_handler) return -EBUSY;
6599
6600        /* one at a time in the install or remove, just fail the others */
6601        if (!spin_trylock(&pfm_alt_install_check)) {
6602                return -EBUSY;
6603        }
6604
6605        /* reserve our session */
6606        for_each_online_cpu(reserve_cpu) {
6607                ret = pfm_reserve_session(NULL, 1, reserve_cpu);
6608                if (ret) goto cleanup_reserve;
6609        }
6610
6611        /* save the current system wide pmu states */
6612        ret = on_each_cpu(pfm_alt_save_pmu_state, NULL, 0, 1);
6613        if (ret) {
6614                DPRINT(("on_each_cpu() failed: %d\n", ret));
6615                goto cleanup_reserve;
6616        }
6617
6618        /* officially change to the alternate interrupt handler */
6619        pfm_alt_intr_handler = hdl;
6620
6621        spin_unlock(&pfm_alt_install_check);
6622
6623        return 0;
6624
6625cleanup_reserve:
6626        for_each_online_cpu(i) {
6627                /* don't unreserve more than we reserved */
6628                if (i >= reserve_cpu) break;
6629
6630                pfm_unreserve_session(NULL, 1, i);
6631        }
6632
6633        spin_unlock(&pfm_alt_install_check);
6634
6635        return ret;
6636}
6637EXPORT_SYMBOL_GPL(pfm_install_alt_pmu_interrupt);
6638
6639int
6640pfm_remove_alt_pmu_interrupt(pfm_intr_handler_desc_t *hdl)
6641{
6642        int i;
6643        int ret;
6644
6645        if (hdl == NULL) return -EINVAL;
6646
6647        /* cannot remove someone else's handler! */
6648        if (pfm_alt_intr_handler != hdl) return -EINVAL;
6649
6650        /* one at a time in the install or remove, just fail the others */
6651        if (!spin_trylock(&pfm_alt_install_check)) {
6652                return -EBUSY;
6653        }
6654
6655        pfm_alt_intr_handler = NULL;
6656
6657        ret = on_each_cpu(pfm_alt_restore_pmu_state, NULL, 0, 1);
6658        if (ret) {
6659                DPRINT(("on_each_cpu() failed: %d\n", ret));
6660        }
6661
6662        for_each_online_cpu(i) {
6663                pfm_unreserve_session(NULL, 1, i);
6664        }
6665
6666        spin_unlock(&pfm_alt_install_check);
6667
6668        return 0;
6669}
6670EXPORT_SYMBOL_GPL(pfm_remove_alt_pmu_interrupt);
6671
6672/*
6673 * perfmon initialization routine, called from the initcall() table
6674 */
6675static int init_pfm_fs(void);
6676
6677static int __init
6678pfm_probe_pmu(void)
6679{
6680        pmu_config_t **p;
6681        int family;
6682
6683        family = local_cpu_data->family;
6684        p      = pmu_confs;
6685
6686        while(*p) {
6687                if ((*p)->probe) {
6688                        if ((*p)->probe() == 0) goto found;
6689                } else if ((*p)->pmu_family == family || (*p)->pmu_family == 0xff) {
6690                        goto found;
6691                }
6692                p++;
6693        }
6694        return -1;
6695found:
6696        pmu_conf = *p;
6697        return 0;
6698}
6699
6700static struct file_operations pfm_proc_fops = {
6701        .open           = pfm_proc_open,
6702        .read           = seq_read,
6703        .llseek         = seq_lseek,
6704        .release        = seq_release,
6705};
6706
6707int __init
6708pfm_init(void)
6709{
6710        unsigned int n, n_counters, i;
6711
6712        printk("perfmon: version %u.%u IRQ %u\n",
6713                PFM_VERSION_MAJ,
6714                PFM_VERSION_MIN,
6715                IA64_PERFMON_VECTOR);
6716
6717        if (pfm_probe_pmu()) {
6718                printk(KERN_INFO "perfmon: disabled, there is no support for processor family %d\n", 
6719                                local_cpu_data->family);
6720                return -ENODEV;
6721        }
6722
6723        /*
6724         * compute the number of implemented PMD/PMC from the
6725         * description tables
6726         */
6727        n = 0;
6728        for (i=0; PMC_IS_LAST(i) == 0;  i++) {
6729                if (PMC_IS_IMPL(i) == 0) continue;
6730                pmu_conf->impl_pmcs[i>>6] |= 1UL << (i&63);
6731                n++;
6732        }
6733        pmu_conf->num_pmcs = n;
6734
6735        n = 0; n_counters = 0;
6736        for (i=0; PMD_IS_LAST(i) == 0;  i++) {
6737                if (PMD_IS_IMPL(i) == 0) continue;
6738                pmu_conf->impl_pmds[i>>6] |= 1UL << (i&63);
6739                n++;
6740                if (PMD_IS_COUNTING(i)) n_counters++;
6741        }
6742        pmu_conf->num_pmds      = n;
6743        pmu_conf->num_counters  = n_counters;
6744
6745        /*
6746         * sanity checks on the number of debug registers
6747         */
6748        if (pmu_conf->use_rr_dbregs) {
6749                if (pmu_conf->num_ibrs > IA64_NUM_DBG_REGS) {
6750                        printk(KERN_INFO "perfmon: unsupported number of code debug registers (%u)\n", pmu_conf->num_ibrs);
6751                        pmu_conf = NULL;
6752                        return -1;
6753                }
6754                if (pmu_conf->num_dbrs > IA64_NUM_DBG_REGS) {
6755                        printk(KERN_INFO "perfmon: unsupported number of data debug registers (%u)\n", pmu_conf->num_ibrs);
6756                        pmu_conf = NULL;
6757                        return -1;
6758                }
6759        }
6760
6761        printk("perfmon: %s PMU detected, %u PMCs, %u PMDs, %u counters (%lu bits)\n",
6762               pmu_conf->pmu_name,
6763               pmu_conf->num_pmcs,
6764               pmu_conf->num_pmds,
6765               pmu_conf->num_counters,
6766               ffz(pmu_conf->ovfl_val));
6767
6768        /* sanity check */
6769        if (pmu_conf->num_pmds >= IA64_NUM_PMD_REGS || pmu_conf->num_pmcs >= IA64_NUM_PMC_REGS) {
6770                printk(KERN_ERR "perfmon: not enough pmc/pmd, perfmon disabled\n");
6771                pmu_conf = NULL;
6772                return -1;
6773        }
6774
6775        /*
6776         * create /proc/perfmon (mostly for debugging purposes)
6777         */
6778        perfmon_dir = create_proc_entry("perfmon", S_IRUGO, NULL);
6779        if (perfmon_dir == NULL) {
6780                printk(KERN_ERR "perfmon: cannot create /proc entry, perfmon disabled\n");
6781                pmu_conf = NULL;
6782                return -1;
6783        }
6784        /*
6785         * install customized file operations for /proc/perfmon entry
6786         */
6787        perfmon_dir->proc_fops = &pfm_proc_fops;
6788
6789        /*
6790         * create /proc/sys/kernel/perfmon (for debugging purposes)
6791         */
6792        pfm_sysctl_header = register_sysctl_table(pfm_sysctl_root, 0);
6793
6794        /*
6795         * initialize all our spinlocks
6796         */
6797        spin_lock_init(&pfm_sessions.pfs_lock);
6798        spin_lock_init(&pfm_buffer_fmt_lock);
6799
6800        init_pfm_fs();
6801
6802        for(i=0; i < NR_CPUS; i++) pfm_stats[i].pfm_ovfl_intr_cycles_min = ~0UL;
6803
6804        return 0;
6805}
6806
6807__initcall(pfm_init);
6808
6809/*
6810 * this function is called before pfm_init()
6811 */
6812void
6813pfm_init_percpu (void)
6814{
6815        static int first_time=1;
6816        /*
6817         * make sure no measurement is active
6818         * (may inherit programmed PMCs from EFI).
6819         */
6820        pfm_clear_psr_pp();
6821        pfm_clear_psr_up();
6822
6823        /*
6824         * we run with the PMU not frozen at all times
6825         */
6826        pfm_unfreeze_pmu();
6827
6828        if (first_time) {
6829                register_percpu_irq(IA64_PERFMON_VECTOR, &perfmon_irqaction);
6830                first_time=0;
6831        }
6832
6833        ia64_setreg(_IA64_REG_CR_PMV, IA64_PERFMON_VECTOR);
6834        ia64_srlz_d();
6835}
6836
6837/*
6838 * used for debug purposes only
6839 */
6840void
6841dump_pmu_state(const char *from)
6842{
6843        struct task_struct *task;
6844        struct thread_struct *t;
6845        struct pt_regs *regs;
6846        pfm_context_t *ctx;
6847        unsigned long psr, dcr, info, flags;
6848        int i, this_cpu;
6849
6850        local_irq_save(flags);
6851
6852        this_cpu = smp_processor_id();
6853        regs     = task_pt_regs(current);
6854        info     = PFM_CPUINFO_GET();
6855        dcr      = ia64_getreg(_IA64_REG_CR_DCR);
6856
6857        if (info == 0 && ia64_psr(regs)->pp == 0 && (dcr & IA64_DCR_PP) == 0) {
6858                local_irq_restore(flags);
6859                return;
6860        }
6861
6862        printk("CPU%d from %s() current [%d] iip=0x%lx %s\n", 
6863                this_cpu, 
6864                from, 
6865                current->pid, 
6866                regs->cr_iip,
6867                current->comm);
6868
6869        task = GET_PMU_OWNER();
6870        ctx  = GET_PMU_CTX();
6871
6872        printk("->CPU%d owner [%d] ctx=%p\n", this_cpu, task ? task->pid : -1, ctx);
6873
6874        psr = pfm_get_psr();
6875
6876        printk("->CPU%d pmc0=0x%lx psr.pp=%d psr.up=%d dcr.pp=%d syst_info=0x%lx user_psr.up=%d user_psr.pp=%d\n", 
6877                this_cpu,
6878                ia64_get_pmc(0),
6879                psr & IA64_PSR_PP ? 1 : 0,
6880                psr & IA64_PSR_UP ? 1 : 0,
6881                dcr & IA64_DCR_PP ? 1 : 0,
6882                info,
6883                ia64_psr(regs)->up,
6884                ia64_psr(regs)->pp);
6885
6886        ia64_psr(regs)->up = 0;
6887        ia64_psr(regs)->pp = 0;
6888
6889        t = &current->thread;
6890
6891        for (i=1; PMC_IS_LAST(i) == 0; i++) {
6892                if (PMC_IS_IMPL(i) == 0) continue;
6893                printk("->CPU%d pmc[%d]=0x%lx thread_pmc[%d]=0x%lx\n", this_cpu, i, ia64_get_pmc(i), i, t->pmcs[i]);
6894        }
6895
6896        for (i=1; PMD_IS_LAST(i) == 0; i++) {
6897                if (PMD_IS_IMPL(i) == 0) continue;
6898                printk("->CPU%d pmd[%d]=0x%lx thread_pmd[%d]=0x%lx\n", this_cpu, i, ia64_get_pmd(i), i, t->pmds[i]);
6899        }
6900
6901        if (ctx) {
6902                printk("->CPU%d ctx_state=%d vaddr=%p addr=%p fd=%d ctx_task=[%d] saved_psr_up=0x%lx\n",
6903                                this_cpu,
6904                                ctx->ctx_state,
6905                                ctx->ctx_smpl_vaddr,
6906                                ctx->ctx_smpl_hdr,
6907                                ctx->ctx_msgq_head,
6908                                ctx->ctx_msgq_tail,
6909                                ctx->ctx_saved_psr_up);
6910        }
6911        local_irq_restore(flags);
6912}
6913
6914/*
6915 * called from process.c:copy_thread(). task is new child.
6916 */
6917void
6918pfm_inherit(struct task_struct *task, struct pt_regs *regs)
6919{
6920        struct thread_struct *thread;
6921
6922        DPRINT(("perfmon: pfm_inherit clearing state for [%d]\n", task->pid));
6923
6924        thread = &task->thread;
6925
6926        /*
6927         * cut links inherited from parent (current)
6928         */
6929        thread->pfm_context = NULL;
6930
6931        PFM_SET_WORK_PENDING(task, 0);
6932
6933        /*
6934         * the psr bits are already set properly in copy_threads()
6935         */
6936}
6937#else  /* !CONFIG_PERFMON */
6938asmlinkage long
6939sys_perfmonctl (int fd, int cmd, void *arg, int count)
6940{
6941        return -ENOSYS;
6942}
6943#endif /* CONFIG_PERFMON */
Note: See TracBrowser for help on using the repository browser.