Add the rt linux 4.1.3-rt3 as base
[kvmfornfv.git] / kernel / drivers / misc / hwlat_detector.c
1 /*
2  * hwlat_detector.c - A simple Hardware Latency detector.
3  *
4  * Use this module to detect large system latencies induced by the behavior of
5  * certain underlying system hardware or firmware, independent of Linux itself.
6  * The code was developed originally to detect the presence of SMIs on Intel
7  * and AMD systems, although there is no dependency upon x86 herein.
8  *
9  * The classical example usage of this module is in detecting the presence of
10  * SMIs or System Management Interrupts on Intel and AMD systems. An SMI is a
11  * somewhat special form of hardware interrupt spawned from earlier CPU debug
12  * modes in which the (BIOS/EFI/etc.) firmware arranges for the South Bridge
13  * LPC (or other device) to generate a special interrupt under certain
14  * circumstances, for example, upon expiration of a special SMI timer device,
15  * due to certain external thermal readings, on certain I/O address accesses,
16  * and other situations. An SMI hits a special CPU pin, triggers a special
17  * SMI mode (complete with special memory map), and the OS is unaware.
18  *
19  * Although certain hardware-inducing latencies are necessary (for example,
20  * a modern system often requires an SMI handler for correct thermal control
21  * and remote management) they can wreak havoc upon any OS-level performance
22  * guarantees toward low-latency, especially when the OS is not even made
23  * aware of the presence of these interrupts. For this reason, we need a
24  * somewhat brute force mechanism to detect these interrupts. In this case,
25  * we do it by hogging all of the CPU(s) for configurable timer intervals,
26  * sampling the built-in CPU timer, looking for discontiguous readings.
27  *
28  * WARNING: This implementation necessarily introduces latencies. Therefore,
29  *          you should NEVER use this module in a production environment
30  *          requiring any kind of low-latency performance guarantee(s).
31  *
32  * Copyright (C) 2008-2009 Jon Masters, Red Hat, Inc. <jcm@redhat.com>
33  *
34  * Includes useful feedback from Clark Williams <clark@redhat.com>
35  *
36  * This file is licensed under the terms of the GNU General Public
37  * License version 2. This program is licensed "as is" without any
38  * warranty of any kind, whether express or implied.
39  */
40
41 #include <linux/module.h>
42 #include <linux/init.h>
43 #include <linux/ring_buffer.h>
44 #include <linux/time.h>
45 #include <linux/hrtimer.h>
46 #include <linux/kthread.h>
47 #include <linux/debugfs.h>
48 #include <linux/seq_file.h>
49 #include <linux/uaccess.h>
50 #include <linux/version.h>
51 #include <linux/delay.h>
52 #include <linux/slab.h>
53 #include <linux/trace_clock.h>
54
55 #define BUF_SIZE_DEFAULT        262144UL                /* 8K*(sizeof(entry)) */
56 #define BUF_FLAGS               (RB_FL_OVERWRITE)       /* no block on full */
57 #define U64STR_SIZE             22                      /* 20 digits max */
58
59 #define VERSION                 "1.0.0"
60 #define BANNER                  "hwlat_detector: "
61 #define DRVNAME                 "hwlat_detector"
62 #define DEFAULT_SAMPLE_WINDOW   1000000                 /* 1s */
63 #define DEFAULT_SAMPLE_WIDTH    500000                  /* 0.5s */
64 #define DEFAULT_LAT_THRESHOLD   10                      /* 10us */
65
66 /* Module metadata */
67
68 MODULE_LICENSE("GPL");
69 MODULE_AUTHOR("Jon Masters <jcm@redhat.com>");
70 MODULE_DESCRIPTION("A simple hardware latency detector");
71 MODULE_VERSION(VERSION);
72
73 /* Module parameters */
74
75 static int debug;
76 static int enabled;
77 static int threshold;
78
79 module_param(debug, int, 0);                    /* enable debug */
80 module_param(enabled, int, 0);                  /* enable detector */
81 module_param(threshold, int, 0);                /* latency threshold */
82
83 /* Buffering and sampling */
84
85 static struct ring_buffer *ring_buffer;         /* sample buffer */
86 static DEFINE_MUTEX(ring_buffer_mutex);         /* lock changes */
87 static unsigned long buf_size = BUF_SIZE_DEFAULT;
88 static struct task_struct *kthread;             /* sampling thread */
89
90 /* DebugFS filesystem entries */
91
92 static struct dentry *debug_dir;                /* debugfs directory */
93 static struct dentry *debug_max;                /* maximum TSC delta */
94 static struct dentry *debug_count;              /* total detect count */
95 static struct dentry *debug_sample_width;       /* sample width us */
96 static struct dentry *debug_sample_window;      /* sample window us */
97 static struct dentry *debug_sample;             /* raw samples us */
98 static struct dentry *debug_threshold;          /* threshold us */
99 static struct dentry *debug_enable;             /* enable/disable */
100
101 /* Individual samples and global state */
102
103 struct sample;                                  /* latency sample */
104 struct data;                                    /* Global state */
105
106 /* Sampling functions */
107 static int __buffer_add_sample(struct sample *sample);
108 static struct sample *buffer_get_sample(struct sample *sample);
109
110 /* Threading and state */
111 static int kthread_fn(void *unused);
112 static int start_kthread(void);
113 static int stop_kthread(void);
114 static void __reset_stats(void);
115 static int init_stats(void);
116
117 /* Debugfs interface */
118 static ssize_t simple_data_read(struct file *filp, char __user *ubuf,
119                                 size_t cnt, loff_t *ppos, const u64 *entry);
120 static ssize_t simple_data_write(struct file *filp, const char __user *ubuf,
121                                  size_t cnt, loff_t *ppos, u64 *entry);
122 static int debug_sample_fopen(struct inode *inode, struct file *filp);
123 static ssize_t debug_sample_fread(struct file *filp, char __user *ubuf,
124                                   size_t cnt, loff_t *ppos);
125 static int debug_sample_release(struct inode *inode, struct file *filp);
126 static int debug_enable_fopen(struct inode *inode, struct file *filp);
127 static ssize_t debug_enable_fread(struct file *filp, char __user *ubuf,
128                                   size_t cnt, loff_t *ppos);
129 static ssize_t debug_enable_fwrite(struct file *file,
130                                    const char __user *user_buffer,
131                                    size_t user_size, loff_t *offset);
132
133 /* Initialization functions */
134 static int init_debugfs(void);
135 static void free_debugfs(void);
136 static int detector_init(void);
137 static void detector_exit(void);
138
139 /* Individual latency samples are stored here when detected and packed into
140  * the ring_buffer circular buffer, where they are overwritten when
141  * more than buf_size/sizeof(sample) samples are received. */
142 struct sample {
143         u64             seqnum;         /* unique sequence */
144         u64             duration;       /* ktime delta */
145         u64             outer_duration; /* ktime delta (outer loop) */
146         struct timespec timestamp;      /* wall time */
147         unsigned long   lost;
148 };
149
150 /* keep the global state somewhere. */
151 static struct data {
152
153         struct mutex lock;              /* protect changes */
154
155         u64     count;                  /* total since reset */
156         u64     max_sample;             /* max hardware latency */
157         u64     threshold;              /* sample threshold level */
158
159         u64     sample_window;          /* total sampling window (on+off) */
160         u64     sample_width;           /* active sampling portion of window */
161
162         atomic_t sample_open;           /* whether the sample file is open */
163
164         wait_queue_head_t wq;           /* waitqeue for new sample values */
165
166 } data;
167
168 /**
169  * __buffer_add_sample - add a new latency sample recording to the ring buffer
170  * @sample: The new latency sample value
171  *
172  * This receives a new latency sample and records it in a global ring buffer.
173  * No additional locking is used in this case.
174  */
175 static int __buffer_add_sample(struct sample *sample)
176 {
177         return ring_buffer_write(ring_buffer,
178                                  sizeof(struct sample), sample);
179 }
180
181 /**
182  * buffer_get_sample - remove a hardware latency sample from the ring buffer
183  * @sample: Pre-allocated storage for the sample
184  *
185  * This retrieves a hardware latency sample from the global circular buffer
186  */
187 static struct sample *buffer_get_sample(struct sample *sample)
188 {
189         struct ring_buffer_event *e = NULL;
190         struct sample *s = NULL;
191         unsigned int cpu = 0;
192
193         if (!sample)
194                 return NULL;
195
196         mutex_lock(&ring_buffer_mutex);
197         for_each_online_cpu(cpu) {
198                 e = ring_buffer_consume(ring_buffer, cpu, NULL, &sample->lost);
199                 if (e)
200                         break;
201         }
202
203         if (e) {
204                 s = ring_buffer_event_data(e);
205                 memcpy(sample, s, sizeof(struct sample));
206         } else
207                 sample = NULL;
208         mutex_unlock(&ring_buffer_mutex);
209
210         return sample;
211 }
212
213 #ifndef CONFIG_TRACING
214 #define time_type       ktime_t
215 #define time_get()      ktime_get()
216 #define time_to_us(x)   ktime_to_us(x)
217 #define time_sub(a, b)  ktime_sub(a, b)
218 #define init_time(a, b) (a).tv64 = b
219 #define time_u64(a)     ((a).tv64)
220 #else
221 #define time_type       u64
222 #define time_get()      trace_clock_local()
223 #define time_to_us(x)   div_u64(x, 1000)
224 #define time_sub(a, b)  ((a) - (b))
225 #define init_time(a, b) (a = b)
226 #define time_u64(a)     a
227 #endif
228 /**
229  * get_sample - sample the CPU TSC and look for likely hardware latencies
230  *
231  * Used to repeatedly capture the CPU TSC (or similar), looking for potential
232  * hardware-induced latency. Called with interrupts disabled and with
233  * data.lock held.
234  */
235 static int get_sample(void)
236 {
237         time_type start, t1, t2, last_t2;
238         s64 diff, total = 0;
239         u64 sample = 0;
240         u64 outer_sample = 0;
241         int ret = -1;
242
243         init_time(last_t2, 0);
244         start = time_get(); /* start timestamp */
245
246         do {
247
248                 t1 = time_get();        /* we'll look for a discontinuity */
249                 t2 = time_get();
250
251                 if (time_u64(last_t2)) {
252                         /* Check the delta from outer loop (t2 to next t1) */
253                         diff = time_to_us(time_sub(t1, last_t2));
254                         /* This shouldn't happen */
255                         if (diff < 0) {
256                                 pr_err(BANNER "time running backwards\n");
257                                 goto out;
258                         }
259                         if (diff > outer_sample)
260                                 outer_sample = diff;
261                 }
262                 last_t2 = t2;
263
264                 total = time_to_us(time_sub(t2, start)); /* sample width */
265
266                 /* This checks the inner loop (t1 to t2) */
267                 diff = time_to_us(time_sub(t2, t1));     /* current diff */
268
269                 /* This shouldn't happen */
270                 if (diff < 0) {
271                         pr_err(BANNER "time running backwards\n");
272                         goto out;
273                 }
274
275                 if (diff > sample)
276                         sample = diff; /* only want highest value */
277
278         } while (total <= data.sample_width);
279
280         ret = 0;
281
282         /* If we exceed the threshold value, we have found a hardware latency */
283         if (sample > data.threshold || outer_sample > data.threshold) {
284                 struct sample s;
285
286                 ret = 1;
287
288                 data.count++;
289                 s.seqnum = data.count;
290                 s.duration = sample;
291                 s.outer_duration = outer_sample;
292                 s.timestamp = CURRENT_TIME;
293                 __buffer_add_sample(&s);
294
295                 /* Keep a running maximum ever recorded hardware latency */
296                 if (sample > data.max_sample)
297                         data.max_sample = sample;
298         }
299
300 out:
301         return ret;
302 }
303
304 /*
305  * kthread_fn - The CPU time sampling/hardware latency detection kernel thread
306  * @unused: A required part of the kthread API.
307  *
308  * Used to periodically sample the CPU TSC via a call to get_sample. We
309  * disable interrupts, which does (intentionally) introduce latency since we
310  * need to ensure nothing else might be running (and thus pre-empting).
311  * Obviously this should never be used in production environments.
312  *
313  * Currently this runs on which ever CPU it was scheduled on, but most
314  * real-worald hardware latency situations occur across several CPUs,
315  * but we might later generalize this if we find there are any actualy
316  * systems with alternate SMI delivery or other hardware latencies.
317  */
318 static int kthread_fn(void *unused)
319 {
320         int ret;
321         u64 interval;
322
323         while (!kthread_should_stop()) {
324
325                 mutex_lock(&data.lock);
326
327                 local_irq_disable();
328                 ret = get_sample();
329                 local_irq_enable();
330
331                 if (ret > 0)
332                         wake_up(&data.wq); /* wake up reader(s) */
333
334                 interval = data.sample_window - data.sample_width;
335                 do_div(interval, USEC_PER_MSEC); /* modifies interval value */
336
337                 mutex_unlock(&data.lock);
338
339                 if (msleep_interruptible(interval))
340                         break;
341         }
342
343         return 0;
344 }
345
346 /**
347  * start_kthread - Kick off the hardware latency sampling/detector kthread
348  *
349  * This starts a kernel thread that will sit and sample the CPU timestamp
350  * counter (TSC or similar) and look for potential hardware latencies.
351  */
352 static int start_kthread(void)
353 {
354         kthread = kthread_run(kthread_fn, NULL,
355                                         DRVNAME);
356         if (IS_ERR(kthread)) {
357                 pr_err(BANNER "could not start sampling thread\n");
358                 enabled = 0;
359                 return -ENOMEM;
360         }
361
362         return 0;
363 }
364
365 /**
366  * stop_kthread - Inform the hardware latency samping/detector kthread to stop
367  *
368  * This kicks the running hardware latency sampling/detector kernel thread and
369  * tells it to stop sampling now. Use this on unload and at system shutdown.
370  */
371 static int stop_kthread(void)
372 {
373         int ret;
374
375         ret = kthread_stop(kthread);
376
377         return ret;
378 }
379
380 /**
381  * __reset_stats - Reset statistics for the hardware latency detector
382  *
383  * We use data to store various statistics and global state. We call this
384  * function in order to reset those when "enable" is toggled on or off, and
385  * also at initialization. Should be called with data.lock held.
386  */
387 static void __reset_stats(void)
388 {
389         data.count = 0;
390         data.max_sample = 0;
391         ring_buffer_reset(ring_buffer); /* flush out old sample entries */
392 }
393
394 /**
395  * init_stats - Setup global state statistics for the hardware latency detector
396  *
397  * We use data to store various statistics and global state. We also use
398  * a global ring buffer (ring_buffer) to keep raw samples of detected hardware
399  * induced system latencies. This function initializes these structures and
400  * allocates the global ring buffer also.
401  */
402 static int init_stats(void)
403 {
404         int ret = -ENOMEM;
405
406         mutex_init(&data.lock);
407         init_waitqueue_head(&data.wq);
408         atomic_set(&data.sample_open, 0);
409
410         ring_buffer = ring_buffer_alloc(buf_size, BUF_FLAGS);
411
412         if (WARN(!ring_buffer, KERN_ERR BANNER
413                                "failed to allocate ring buffer!\n"))
414                 goto out;
415
416         __reset_stats();
417         data.threshold = threshold ?: DEFAULT_LAT_THRESHOLD; /* threshold us */
418         data.sample_window = DEFAULT_SAMPLE_WINDOW; /* window us */
419         data.sample_width = DEFAULT_SAMPLE_WIDTH;   /* width us */
420
421         ret = 0;
422
423 out:
424         return ret;
425
426 }
427
428 /*
429  * simple_data_read - Wrapper read function for global state debugfs entries
430  * @filp: The active open file structure for the debugfs "file"
431  * @ubuf: The userspace provided buffer to read value into
432  * @cnt: The maximum number of bytes to read
433  * @ppos: The current "file" position
434  * @entry: The entry to read from
435  *
436  * This function provides a generic read implementation for the global state
437  * "data" structure debugfs filesystem entries. It would be nice to use
438  * simple_attr_read directly, but we need to make sure that the data.lock
439  * is held during the actual read.
440  */
441 static ssize_t simple_data_read(struct file *filp, char __user *ubuf,
442                                 size_t cnt, loff_t *ppos, const u64 *entry)
443 {
444         char buf[U64STR_SIZE];
445         u64 val = 0;
446         int len = 0;
447
448         memset(buf, 0, sizeof(buf));
449
450         if (!entry)
451                 return -EFAULT;
452
453         mutex_lock(&data.lock);
454         val = *entry;
455         mutex_unlock(&data.lock);
456
457         len = snprintf(buf, sizeof(buf), "%llu\n", (unsigned long long)val);
458
459         return simple_read_from_buffer(ubuf, cnt, ppos, buf, len);
460
461 }
462
463 /*
464  * simple_data_write - Wrapper write function for global state debugfs entries
465  * @filp: The active open file structure for the debugfs "file"
466  * @ubuf: The userspace provided buffer to write value from
467  * @cnt: The maximum number of bytes to write
468  * @ppos: The current "file" position
469  * @entry: The entry to write to
470  *
471  * This function provides a generic write implementation for the global state
472  * "data" structure debugfs filesystem entries. It would be nice to use
473  * simple_attr_write directly, but we need to make sure that the data.lock
474  * is held during the actual write.
475  */
476 static ssize_t simple_data_write(struct file *filp, const char __user *ubuf,
477                                  size_t cnt, loff_t *ppos, u64 *entry)
478 {
479         char buf[U64STR_SIZE];
480         int csize = min(cnt, sizeof(buf));
481         u64 val = 0;
482         int err = 0;
483
484         memset(buf, '\0', sizeof(buf));
485         if (copy_from_user(buf, ubuf, csize))
486                 return -EFAULT;
487
488         buf[U64STR_SIZE-1] = '\0';                      /* just in case */
489         err = kstrtoull(buf, 10, &val);
490         if (err)
491                 return -EINVAL;
492
493         mutex_lock(&data.lock);
494         *entry = val;
495         mutex_unlock(&data.lock);
496
497         return csize;
498 }
499
500 /**
501  * debug_count_fopen - Open function for "count" debugfs entry
502  * @inode: The in-kernel inode representation of the debugfs "file"
503  * @filp: The active open file structure for the debugfs "file"
504  *
505  * This function provides an open implementation for the "count" debugfs
506  * interface to the hardware latency detector.
507  */
508 static int debug_count_fopen(struct inode *inode, struct file *filp)
509 {
510         return 0;
511 }
512
513 /**
514  * debug_count_fread - Read function for "count" debugfs entry
515  * @filp: The active open file structure for the debugfs "file"
516  * @ubuf: The userspace provided buffer to read value into
517  * @cnt: The maximum number of bytes to read
518  * @ppos: The current "file" position
519  *
520  * This function provides a read implementation for the "count" debugfs
521  * interface to the hardware latency detector. Can be used to read the
522  * number of latency readings exceeding the configured threshold since
523  * the detector was last reset (e.g. by writing a zero into "count").
524  */
525 static ssize_t debug_count_fread(struct file *filp, char __user *ubuf,
526                                      size_t cnt, loff_t *ppos)
527 {
528         return simple_data_read(filp, ubuf, cnt, ppos, &data.count);
529 }
530
531 /**
532  * debug_count_fwrite - Write function for "count" debugfs entry
533  * @filp: The active open file structure for the debugfs "file"
534  * @ubuf: The user buffer that contains the value to write
535  * @cnt: The maximum number of bytes to write to "file"
536  * @ppos: The current position in the debugfs "file"
537  *
538  * This function provides a write implementation for the "count" debugfs
539  * interface to the hardware latency detector. Can be used to write a
540  * desired value, especially to zero the total count.
541  */
542 static ssize_t  debug_count_fwrite(struct file *filp,
543                                        const char __user *ubuf,
544                                        size_t cnt,
545                                        loff_t *ppos)
546 {
547         return simple_data_write(filp, ubuf, cnt, ppos, &data.count);
548 }
549
550 /**
551  * debug_enable_fopen - Dummy open function for "enable" debugfs interface
552  * @inode: The in-kernel inode representation of the debugfs "file"
553  * @filp: The active open file structure for the debugfs "file"
554  *
555  * This function provides an open implementation for the "enable" debugfs
556  * interface to the hardware latency detector.
557  */
558 static int debug_enable_fopen(struct inode *inode, struct file *filp)
559 {
560         return 0;
561 }
562
563 /**
564  * debug_enable_fread - Read function for "enable" debugfs interface
565  * @filp: The active open file structure for the debugfs "file"
566  * @ubuf: The userspace provided buffer to read value into
567  * @cnt: The maximum number of bytes to read
568  * @ppos: The current "file" position
569  *
570  * This function provides a read implementation for the "enable" debugfs
571  * interface to the hardware latency detector. Can be used to determine
572  * whether the detector is currently enabled ("0\n" or "1\n" returned).
573  */
574 static ssize_t debug_enable_fread(struct file *filp, char __user *ubuf,
575                                       size_t cnt, loff_t *ppos)
576 {
577         char buf[4];
578
579         if ((cnt < sizeof(buf)) || (*ppos))
580                 return 0;
581
582         buf[0] = enabled ? '1' : '0';
583         buf[1] = '\n';
584         buf[2] = '\0';
585         if (copy_to_user(ubuf, buf, strlen(buf)))
586                 return -EFAULT;
587         return *ppos = strlen(buf);
588 }
589
590 /**
591  * debug_enable_fwrite - Write function for "enable" debugfs interface
592  * @filp: The active open file structure for the debugfs "file"
593  * @ubuf: The user buffer that contains the value to write
594  * @cnt: The maximum number of bytes to write to "file"
595  * @ppos: The current position in the debugfs "file"
596  *
597  * This function provides a write implementation for the "enable" debugfs
598  * interface to the hardware latency detector. Can be used to enable or
599  * disable the detector, which will have the side-effect of possibly
600  * also resetting the global stats and kicking off the measuring
601  * kthread (on an enable) or the converse (upon a disable).
602  */
603 static ssize_t  debug_enable_fwrite(struct file *filp,
604                                         const char __user *ubuf,
605                                         size_t cnt,
606                                         loff_t *ppos)
607 {
608         char buf[4];
609         int csize = min(cnt, sizeof(buf));
610         long val = 0;
611         int err = 0;
612
613         memset(buf, '\0', sizeof(buf));
614         if (copy_from_user(buf, ubuf, csize))
615                 return -EFAULT;
616
617         buf[sizeof(buf)-1] = '\0';                      /* just in case */
618         err = kstrtoul(buf, 10, &val);
619         if (0 != err)
620                 return -EINVAL;
621
622         if (val) {
623                 if (enabled)
624                         goto unlock;
625                 enabled = 1;
626                 __reset_stats();
627                 if (start_kthread())
628                         return -EFAULT;
629         } else {
630                 if (!enabled)
631                         goto unlock;
632                 enabled = 0;
633                 err = stop_kthread();
634                 if (err) {
635                         pr_err(BANNER "cannot stop kthread\n");
636                         return -EFAULT;
637                 }
638                 wake_up(&data.wq);              /* reader(s) should return */
639         }
640 unlock:
641         return csize;
642 }
643
644 /**
645  * debug_max_fopen - Open function for "max" debugfs entry
646  * @inode: The in-kernel inode representation of the debugfs "file"
647  * @filp: The active open file structure for the debugfs "file"
648  *
649  * This function provides an open implementation for the "max" debugfs
650  * interface to the hardware latency detector.
651  */
652 static int debug_max_fopen(struct inode *inode, struct file *filp)
653 {
654         return 0;
655 }
656
657 /**
658  * debug_max_fread - Read function for "max" debugfs entry
659  * @filp: The active open file structure for the debugfs "file"
660  * @ubuf: The userspace provided buffer to read value into
661  * @cnt: The maximum number of bytes to read
662  * @ppos: The current "file" position
663  *
664  * This function provides a read implementation for the "max" debugfs
665  * interface to the hardware latency detector. Can be used to determine
666  * the maximum latency value observed since it was last reset.
667  */
668 static ssize_t debug_max_fread(struct file *filp, char __user *ubuf,
669                                    size_t cnt, loff_t *ppos)
670 {
671         return simple_data_read(filp, ubuf, cnt, ppos, &data.max_sample);
672 }
673
674 /**
675  * debug_max_fwrite - Write function for "max" debugfs entry
676  * @filp: The active open file structure for the debugfs "file"
677  * @ubuf: The user buffer that contains the value to write
678  * @cnt: The maximum number of bytes to write to "file"
679  * @ppos: The current position in the debugfs "file"
680  *
681  * This function provides a write implementation for the "max" debugfs
682  * interface to the hardware latency detector. Can be used to reset the
683  * maximum or set it to some other desired value - if, then, subsequent
684  * measurements exceed this value, the maximum will be updated.
685  */
686 static ssize_t  debug_max_fwrite(struct file *filp,
687                                      const char __user *ubuf,
688                                      size_t cnt,
689                                      loff_t *ppos)
690 {
691         return simple_data_write(filp, ubuf, cnt, ppos, &data.max_sample);
692 }
693
694
695 /**
696  * debug_sample_fopen - An open function for "sample" debugfs interface
697  * @inode: The in-kernel inode representation of this debugfs "file"
698  * @filp: The active open file structure for the debugfs "file"
699  *
700  * This function handles opening the "sample" file within the hardware
701  * latency detector debugfs directory interface. This file is used to read
702  * raw samples from the global ring_buffer and allows the user to see a
703  * running latency history. Can be opened blocking or non-blocking,
704  * affecting whether it behaves as a buffer read pipe, or does not.
705  * Implements simple locking to prevent multiple simultaneous use.
706  */
707 static int debug_sample_fopen(struct inode *inode, struct file *filp)
708 {
709         if (!atomic_add_unless(&data.sample_open, 1, 1))
710                 return -EBUSY;
711         else
712                 return 0;
713 }
714
715 /**
716  * debug_sample_fread - A read function for "sample" debugfs interface
717  * @filp: The active open file structure for the debugfs "file"
718  * @ubuf: The user buffer that will contain the samples read
719  * @cnt: The maximum bytes to read from the debugfs "file"
720  * @ppos: The current position in the debugfs "file"
721  *
722  * This function handles reading from the "sample" file within the hardware
723  * latency detector debugfs directory interface. This file is used to read
724  * raw samples from the global ring_buffer and allows the user to see a
725  * running latency history. By default this will block pending a new
726  * value written into the sample buffer, unless there are already a
727  * number of value(s) waiting in the buffer, or the sample file was
728  * previously opened in a non-blocking mode of operation.
729  */
730 static ssize_t debug_sample_fread(struct file *filp, char __user *ubuf,
731                                         size_t cnt, loff_t *ppos)
732 {
733         int len = 0;
734         char buf[64];
735         struct sample *sample = NULL;
736
737         if (!enabled)
738                 return 0;
739
740         sample = kzalloc(sizeof(struct sample), GFP_KERNEL);
741         if (!sample)
742                 return -ENOMEM;
743
744         while (!buffer_get_sample(sample)) {
745
746                 DEFINE_WAIT(wait);
747
748                 if (filp->f_flags & O_NONBLOCK) {
749                         len = -EAGAIN;
750                         goto out;
751                 }
752
753                 prepare_to_wait(&data.wq, &wait, TASK_INTERRUPTIBLE);
754                 schedule();
755                 finish_wait(&data.wq, &wait);
756
757                 if (signal_pending(current)) {
758                         len = -EINTR;
759                         goto out;
760                 }
761
762                 if (!enabled) {                 /* enable was toggled */
763                         len = 0;
764                         goto out;
765                 }
766         }
767
768         len = snprintf(buf, sizeof(buf), "%010lu.%010lu\t%llu\t%llu\n",
769                        sample->timestamp.tv_sec,
770                        sample->timestamp.tv_nsec,
771                        sample->duration,
772                        sample->outer_duration);
773
774
775         /* handling partial reads is more trouble than it's worth */
776         if (len > cnt)
777                 goto out;
778
779         if (copy_to_user(ubuf, buf, len))
780                 len = -EFAULT;
781
782 out:
783         kfree(sample);
784         return len;
785 }
786
787 /**
788  * debug_sample_release - Release function for "sample" debugfs interface
789  * @inode: The in-kernel inode represenation of the debugfs "file"
790  * @filp: The active open file structure for the debugfs "file"
791  *
792  * This function completes the close of the debugfs interface "sample" file.
793  * Frees the sample_open "lock" so that other users may open the interface.
794  */
795 static int debug_sample_release(struct inode *inode, struct file *filp)
796 {
797         atomic_dec(&data.sample_open);
798
799         return 0;
800 }
801
802 /**
803  * debug_threshold_fopen - Open function for "threshold" debugfs entry
804  * @inode: The in-kernel inode representation of the debugfs "file"
805  * @filp: The active open file structure for the debugfs "file"
806  *
807  * This function provides an open implementation for the "threshold" debugfs
808  * interface to the hardware latency detector.
809  */
810 static int debug_threshold_fopen(struct inode *inode, struct file *filp)
811 {
812         return 0;
813 }
814
815 /**
816  * debug_threshold_fread - Read function for "threshold" debugfs entry
817  * @filp: The active open file structure for the debugfs "file"
818  * @ubuf: The userspace provided buffer to read value into
819  * @cnt: The maximum number of bytes to read
820  * @ppos: The current "file" position
821  *
822  * This function provides a read implementation for the "threshold" debugfs
823  * interface to the hardware latency detector. It can be used to determine
824  * the current threshold level at which a latency will be recorded in the
825  * global ring buffer, typically on the order of 10us.
826  */
827 static ssize_t debug_threshold_fread(struct file *filp, char __user *ubuf,
828                                          size_t cnt, loff_t *ppos)
829 {
830         return simple_data_read(filp, ubuf, cnt, ppos, &data.threshold);
831 }
832
833 /**
834  * debug_threshold_fwrite - Write function for "threshold" debugfs entry
835  * @filp: The active open file structure for the debugfs "file"
836  * @ubuf: The user buffer that contains the value to write
837  * @cnt: The maximum number of bytes to write to "file"
838  * @ppos: The current position in the debugfs "file"
839  *
840  * This function provides a write implementation for the "threshold" debugfs
841  * interface to the hardware latency detector. It can be used to configure
842  * the threshold level at which any subsequently detected latencies will
843  * be recorded into the global ring buffer.
844  */
845 static ssize_t  debug_threshold_fwrite(struct file *filp,
846                                         const char __user *ubuf,
847                                         size_t cnt,
848                                         loff_t *ppos)
849 {
850         int ret;
851
852         ret = simple_data_write(filp, ubuf, cnt, ppos, &data.threshold);
853
854         if (enabled)
855                 wake_up_process(kthread);
856
857         return ret;
858 }
859
860 /**
861  * debug_width_fopen - Open function for "width" debugfs entry
862  * @inode: The in-kernel inode representation of the debugfs "file"
863  * @filp: The active open file structure for the debugfs "file"
864  *
865  * This function provides an open implementation for the "width" debugfs
866  * interface to the hardware latency detector.
867  */
868 static int debug_width_fopen(struct inode *inode, struct file *filp)
869 {
870         return 0;
871 }
872
873 /**
874  * debug_width_fread - Read function for "width" debugfs entry
875  * @filp: The active open file structure for the debugfs "file"
876  * @ubuf: The userspace provided buffer to read value into
877  * @cnt: The maximum number of bytes to read
878  * @ppos: The current "file" position
879  *
880  * This function provides a read implementation for the "width" debugfs
881  * interface to the hardware latency detector. It can be used to determine
882  * for how many us of the total window us we will actively sample for any
883  * hardware-induced latecy periods. Obviously, it is not possible to
884  * sample constantly and have the system respond to a sample reader, or,
885  * worse, without having the system appear to have gone out to lunch.
886  */
887 static ssize_t debug_width_fread(struct file *filp, char __user *ubuf,
888                                      size_t cnt, loff_t *ppos)
889 {
890         return simple_data_read(filp, ubuf, cnt, ppos, &data.sample_width);
891 }
892
893 /**
894  * debug_width_fwrite - Write function for "width" debugfs entry
895  * @filp: The active open file structure for the debugfs "file"
896  * @ubuf: The user buffer that contains the value to write
897  * @cnt: The maximum number of bytes to write to "file"
898  * @ppos: The current position in the debugfs "file"
899  *
900  * This function provides a write implementation for the "width" debugfs
901  * interface to the hardware latency detector. It can be used to configure
902  * for how many us of the total window us we will actively sample for any
903  * hardware-induced latency periods. Obviously, it is not possible to
904  * sample constantly and have the system respond to a sample reader, or,
905  * worse, without having the system appear to have gone out to lunch. It
906  * is enforced that width is less that the total window size.
907  */
908 static ssize_t  debug_width_fwrite(struct file *filp,
909                                        const char __user *ubuf,
910                                        size_t cnt,
911                                        loff_t *ppos)
912 {
913         char buf[U64STR_SIZE];
914         int csize = min(cnt, sizeof(buf));
915         u64 val = 0;
916         int err = 0;
917
918         memset(buf, '\0', sizeof(buf));
919         if (copy_from_user(buf, ubuf, csize))
920                 return -EFAULT;
921
922         buf[U64STR_SIZE-1] = '\0';                      /* just in case */
923         err = kstrtoull(buf, 10, &val);
924         if (0 != err)
925                 return -EINVAL;
926
927         mutex_lock(&data.lock);
928         if (val < data.sample_window)
929                 data.sample_width = val;
930         else {
931                 mutex_unlock(&data.lock);
932                 return -EINVAL;
933         }
934         mutex_unlock(&data.lock);
935
936         if (enabled)
937                 wake_up_process(kthread);
938
939         return csize;
940 }
941
942 /**
943  * debug_window_fopen - Open function for "window" debugfs entry
944  * @inode: The in-kernel inode representation of the debugfs "file"
945  * @filp: The active open file structure for the debugfs "file"
946  *
947  * This function provides an open implementation for the "window" debugfs
948  * interface to the hardware latency detector. The window is the total time
949  * in us that will be considered one sample period. Conceptually, windows
950  * occur back-to-back and contain a sample width period during which
951  * actual sampling occurs.
952  */
953 static int debug_window_fopen(struct inode *inode, struct file *filp)
954 {
955         return 0;
956 }
957
958 /**
959  * debug_window_fread - Read function for "window" debugfs entry
960  * @filp: The active open file structure for the debugfs "file"
961  * @ubuf: The userspace provided buffer to read value into
962  * @cnt: The maximum number of bytes to read
963  * @ppos: The current "file" position
964  *
965  * This function provides a read implementation for the "window" debugfs
966  * interface to the hardware latency detector. The window is the total time
967  * in us that will be considered one sample period. Conceptually, windows
968  * occur back-to-back and contain a sample width period during which
969  * actual sampling occurs. Can be used to read the total window size.
970  */
971 static ssize_t debug_window_fread(struct file *filp, char __user *ubuf,
972                                       size_t cnt, loff_t *ppos)
973 {
974         return simple_data_read(filp, ubuf, cnt, ppos, &data.sample_window);
975 }
976
977 /**
978  * debug_window_fwrite - Write function for "window" debugfs entry
979  * @filp: The active open file structure for the debugfs "file"
980  * @ubuf: The user buffer that contains the value to write
981  * @cnt: The maximum number of bytes to write to "file"
982  * @ppos: The current position in the debugfs "file"
983  *
984  * This function provides a write implementation for the "window" debufds
985  * interface to the hardware latency detetector. The window is the total time
986  * in us that will be considered one sample period. Conceptually, windows
987  * occur back-to-back and contain a sample width period during which
988  * actual sampling occurs. Can be used to write a new total window size. It
989  * is enfoced that any value written must be greater than the sample width
990  * size, or an error results.
991  */
992 static ssize_t  debug_window_fwrite(struct file *filp,
993                                         const char __user *ubuf,
994                                         size_t cnt,
995                                         loff_t *ppos)
996 {
997         char buf[U64STR_SIZE];
998         int csize = min(cnt, sizeof(buf));
999         u64 val = 0;
1000         int err = 0;
1001
1002         memset(buf, '\0', sizeof(buf));
1003         if (copy_from_user(buf, ubuf, csize))
1004                 return -EFAULT;
1005
1006         buf[U64STR_SIZE-1] = '\0';                      /* just in case */
1007         err = kstrtoull(buf, 10, &val);
1008         if (0 != err)
1009                 return -EINVAL;
1010
1011         mutex_lock(&data.lock);
1012         if (data.sample_width < val)
1013                 data.sample_window = val;
1014         else {
1015                 mutex_unlock(&data.lock);
1016                 return -EINVAL;
1017         }
1018         mutex_unlock(&data.lock);
1019
1020         return csize;
1021 }
1022
1023 /*
1024  * Function pointers for the "count" debugfs file operations
1025  */
1026 static const struct file_operations count_fops = {
1027         .open           = debug_count_fopen,
1028         .read           = debug_count_fread,
1029         .write          = debug_count_fwrite,
1030         .owner          = THIS_MODULE,
1031 };
1032
1033 /*
1034  * Function pointers for the "enable" debugfs file operations
1035  */
1036 static const struct file_operations enable_fops = {
1037         .open           = debug_enable_fopen,
1038         .read           = debug_enable_fread,
1039         .write          = debug_enable_fwrite,
1040         .owner          = THIS_MODULE,
1041 };
1042
1043 /*
1044  * Function pointers for the "max" debugfs file operations
1045  */
1046 static const struct file_operations max_fops = {
1047         .open           = debug_max_fopen,
1048         .read           = debug_max_fread,
1049         .write          = debug_max_fwrite,
1050         .owner          = THIS_MODULE,
1051 };
1052
1053 /*
1054  * Function pointers for the "sample" debugfs file operations
1055  */
1056 static const struct file_operations sample_fops = {
1057         .open           = debug_sample_fopen,
1058         .read           = debug_sample_fread,
1059         .release        = debug_sample_release,
1060         .owner          = THIS_MODULE,
1061 };
1062
1063 /*
1064  * Function pointers for the "threshold" debugfs file operations
1065  */
1066 static const struct file_operations threshold_fops = {
1067         .open           = debug_threshold_fopen,
1068         .read           = debug_threshold_fread,
1069         .write          = debug_threshold_fwrite,
1070         .owner          = THIS_MODULE,
1071 };
1072
1073 /*
1074  * Function pointers for the "width" debugfs file operations
1075  */
1076 static const struct file_operations width_fops = {
1077         .open           = debug_width_fopen,
1078         .read           = debug_width_fread,
1079         .write          = debug_width_fwrite,
1080         .owner          = THIS_MODULE,
1081 };
1082
1083 /*
1084  * Function pointers for the "window" debugfs file operations
1085  */
1086 static const struct file_operations window_fops = {
1087         .open           = debug_window_fopen,
1088         .read           = debug_window_fread,
1089         .write          = debug_window_fwrite,
1090         .owner          = THIS_MODULE,
1091 };
1092
1093 /**
1094  * init_debugfs - A function to initialize the debugfs interface files
1095  *
1096  * This function creates entries in debugfs for "hwlat_detector", including
1097  * files to read values from the detector, current samples, and the
1098  * maximum sample that has been captured since the hardware latency
1099  * dectector was started.
1100  */
1101 static int init_debugfs(void)
1102 {
1103         int ret = -ENOMEM;
1104
1105         debug_dir = debugfs_create_dir(DRVNAME, NULL);
1106         if (!debug_dir)
1107                 goto err_debug_dir;
1108
1109         debug_sample = debugfs_create_file("sample", 0444,
1110                                                debug_dir, NULL,
1111                                                &sample_fops);
1112         if (!debug_sample)
1113                 goto err_sample;
1114
1115         debug_count = debugfs_create_file("count", 0444,
1116                                               debug_dir, NULL,
1117                                               &count_fops);
1118         if (!debug_count)
1119                 goto err_count;
1120
1121         debug_max = debugfs_create_file("max", 0444,
1122                                             debug_dir, NULL,
1123                                             &max_fops);
1124         if (!debug_max)
1125                 goto err_max;
1126
1127         debug_sample_window = debugfs_create_file("window", 0644,
1128                                                       debug_dir, NULL,
1129                                                       &window_fops);
1130         if (!debug_sample_window)
1131                 goto err_window;
1132
1133         debug_sample_width = debugfs_create_file("width", 0644,
1134                                                      debug_dir, NULL,
1135                                                      &width_fops);
1136         if (!debug_sample_width)
1137                 goto err_width;
1138
1139         debug_threshold = debugfs_create_file("threshold", 0644,
1140                                                   debug_dir, NULL,
1141                                                   &threshold_fops);
1142         if (!debug_threshold)
1143                 goto err_threshold;
1144
1145         debug_enable = debugfs_create_file("enable", 0644,
1146                                                debug_dir, &enabled,
1147                                                &enable_fops);
1148         if (!debug_enable)
1149                 goto err_enable;
1150
1151         else {
1152                 ret = 0;
1153                 goto out;
1154         }
1155
1156 err_enable:
1157         debugfs_remove(debug_threshold);
1158 err_threshold:
1159         debugfs_remove(debug_sample_width);
1160 err_width:
1161         debugfs_remove(debug_sample_window);
1162 err_window:
1163         debugfs_remove(debug_max);
1164 err_max:
1165         debugfs_remove(debug_count);
1166 err_count:
1167         debugfs_remove(debug_sample);
1168 err_sample:
1169         debugfs_remove(debug_dir);
1170 err_debug_dir:
1171 out:
1172         return ret;
1173 }
1174
1175 /**
1176  * free_debugfs - A function to cleanup the debugfs file interface
1177  */
1178 static void free_debugfs(void)
1179 {
1180         /* could also use a debugfs_remove_recursive */
1181         debugfs_remove(debug_enable);
1182         debugfs_remove(debug_threshold);
1183         debugfs_remove(debug_sample_width);
1184         debugfs_remove(debug_sample_window);
1185         debugfs_remove(debug_max);
1186         debugfs_remove(debug_count);
1187         debugfs_remove(debug_sample);
1188         debugfs_remove(debug_dir);
1189 }
1190
1191 /**
1192  * detector_init - Standard module initialization code
1193  */
1194 static int detector_init(void)
1195 {
1196         int ret = -ENOMEM;
1197
1198         pr_info(BANNER "version %s\n", VERSION);
1199
1200         ret = init_stats();
1201         if (0 != ret)
1202                 goto out;
1203
1204         ret = init_debugfs();
1205         if (0 != ret)
1206                 goto err_stats;
1207
1208         if (enabled)
1209                 ret = start_kthread();
1210
1211         goto out;
1212
1213 err_stats:
1214         ring_buffer_free(ring_buffer);
1215 out:
1216         return ret;
1217
1218 }
1219
1220 /**
1221  * detector_exit - Standard module cleanup code
1222  */
1223 static void detector_exit(void)
1224 {
1225         int err;
1226
1227         if (enabled) {
1228                 enabled = 0;
1229                 err = stop_kthread();
1230                 if (err)
1231                         pr_err(BANNER "cannot stop kthread\n");
1232         }
1233
1234         free_debugfs();
1235         ring_buffer_free(ring_buffer);  /* free up the ring buffer */
1236
1237 }
1238
1239 module_init(detector_init);
1240 module_exit(detector_exit);