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