GNU Linux-libre 4.4.284-gnu1
[releases.git] / drivers / md / dm-stats.c
1 #include <linux/errno.h>
2 #include <linux/numa.h>
3 #include <linux/slab.h>
4 #include <linux/rculist.h>
5 #include <linux/threads.h>
6 #include <linux/preempt.h>
7 #include <linux/irqflags.h>
8 #include <linux/vmalloc.h>
9 #include <linux/mm.h>
10 #include <linux/module.h>
11 #include <linux/device-mapper.h>
12
13 #include "dm.h"
14 #include "dm-stats.h"
15
16 #define DM_MSG_PREFIX "stats"
17
18 static int dm_stat_need_rcu_barrier;
19
20 /*
21  * Using 64-bit values to avoid overflow (which is a
22  * problem that block/genhd.c's IO accounting has).
23  */
24 struct dm_stat_percpu {
25         unsigned long long sectors[2];
26         unsigned long long ios[2];
27         unsigned long long merges[2];
28         unsigned long long ticks[2];
29         unsigned long long io_ticks[2];
30         unsigned long long io_ticks_total;
31         unsigned long long time_in_queue;
32         unsigned long long *histogram;
33 };
34
35 struct dm_stat_shared {
36         atomic_t in_flight[2];
37         unsigned long long stamp;
38         struct dm_stat_percpu tmp;
39 };
40
41 struct dm_stat {
42         struct list_head list_entry;
43         int id;
44         unsigned stat_flags;
45         size_t n_entries;
46         sector_t start;
47         sector_t end;
48         sector_t step;
49         unsigned n_histogram_entries;
50         unsigned long long *histogram_boundaries;
51         const char *program_id;
52         const char *aux_data;
53         struct rcu_head rcu_head;
54         size_t shared_alloc_size;
55         size_t percpu_alloc_size;
56         size_t histogram_alloc_size;
57         struct dm_stat_percpu *stat_percpu[NR_CPUS];
58         struct dm_stat_shared stat_shared[0];
59 };
60
61 #define STAT_PRECISE_TIMESTAMPS         1
62
63 struct dm_stats_last_position {
64         sector_t last_sector;
65         unsigned last_rw;
66 };
67
68 /*
69  * A typo on the command line could possibly make the kernel run out of memory
70  * and crash. To prevent the crash we account all used memory. We fail if we
71  * exhaust 1/4 of all memory or 1/2 of vmalloc space.
72  */
73 #define DM_STATS_MEMORY_FACTOR          4
74 #define DM_STATS_VMALLOC_FACTOR         2
75
76 static DEFINE_SPINLOCK(shared_memory_lock);
77
78 static unsigned long shared_memory_amount;
79
80 static bool __check_shared_memory(size_t alloc_size)
81 {
82         size_t a;
83
84         a = shared_memory_amount + alloc_size;
85         if (a < shared_memory_amount)
86                 return false;
87         if (a >> PAGE_SHIFT > totalram_pages / DM_STATS_MEMORY_FACTOR)
88                 return false;
89 #ifdef CONFIG_MMU
90         if (a > (VMALLOC_END - VMALLOC_START) / DM_STATS_VMALLOC_FACTOR)
91                 return false;
92 #endif
93         return true;
94 }
95
96 static bool check_shared_memory(size_t alloc_size)
97 {
98         bool ret;
99
100         spin_lock_irq(&shared_memory_lock);
101
102         ret = __check_shared_memory(alloc_size);
103
104         spin_unlock_irq(&shared_memory_lock);
105
106         return ret;
107 }
108
109 static bool claim_shared_memory(size_t alloc_size)
110 {
111         spin_lock_irq(&shared_memory_lock);
112
113         if (!__check_shared_memory(alloc_size)) {
114                 spin_unlock_irq(&shared_memory_lock);
115                 return false;
116         }
117
118         shared_memory_amount += alloc_size;
119
120         spin_unlock_irq(&shared_memory_lock);
121
122         return true;
123 }
124
125 static void free_shared_memory(size_t alloc_size)
126 {
127         unsigned long flags;
128
129         spin_lock_irqsave(&shared_memory_lock, flags);
130
131         if (WARN_ON_ONCE(shared_memory_amount < alloc_size)) {
132                 spin_unlock_irqrestore(&shared_memory_lock, flags);
133                 DMCRIT("Memory usage accounting bug.");
134                 return;
135         }
136
137         shared_memory_amount -= alloc_size;
138
139         spin_unlock_irqrestore(&shared_memory_lock, flags);
140 }
141
142 static void *dm_kvzalloc(size_t alloc_size, int node)
143 {
144         void *p;
145
146         if (!claim_shared_memory(alloc_size))
147                 return NULL;
148
149         if (alloc_size <= KMALLOC_MAX_SIZE) {
150                 p = kzalloc_node(alloc_size, GFP_KERNEL | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN, node);
151                 if (p)
152                         return p;
153         }
154         p = vzalloc_node(alloc_size, node);
155         if (p)
156                 return p;
157
158         free_shared_memory(alloc_size);
159
160         return NULL;
161 }
162
163 static void dm_kvfree(void *ptr, size_t alloc_size)
164 {
165         if (!ptr)
166                 return;
167
168         free_shared_memory(alloc_size);
169
170         kvfree(ptr);
171 }
172
173 static void dm_stat_free(struct rcu_head *head)
174 {
175         int cpu;
176         struct dm_stat *s = container_of(head, struct dm_stat, rcu_head);
177
178         kfree(s->histogram_boundaries);
179         kfree(s->program_id);
180         kfree(s->aux_data);
181         for_each_possible_cpu(cpu) {
182                 dm_kvfree(s->stat_percpu[cpu][0].histogram, s->histogram_alloc_size);
183                 dm_kvfree(s->stat_percpu[cpu], s->percpu_alloc_size);
184         }
185         dm_kvfree(s->stat_shared[0].tmp.histogram, s->histogram_alloc_size);
186         dm_kvfree(s, s->shared_alloc_size);
187 }
188
189 static int dm_stat_in_flight(struct dm_stat_shared *shared)
190 {
191         return atomic_read(&shared->in_flight[READ]) +
192                atomic_read(&shared->in_flight[WRITE]);
193 }
194
195 void dm_stats_init(struct dm_stats *stats)
196 {
197         int cpu;
198         struct dm_stats_last_position *last;
199
200         mutex_init(&stats->mutex);
201         INIT_LIST_HEAD(&stats->list);
202         stats->last = alloc_percpu(struct dm_stats_last_position);
203         for_each_possible_cpu(cpu) {
204                 last = per_cpu_ptr(stats->last, cpu);
205                 last->last_sector = (sector_t)ULLONG_MAX;
206                 last->last_rw = UINT_MAX;
207         }
208 }
209
210 void dm_stats_cleanup(struct dm_stats *stats)
211 {
212         size_t ni;
213         struct dm_stat *s;
214         struct dm_stat_shared *shared;
215
216         while (!list_empty(&stats->list)) {
217                 s = container_of(stats->list.next, struct dm_stat, list_entry);
218                 list_del(&s->list_entry);
219                 for (ni = 0; ni < s->n_entries; ni++) {
220                         shared = &s->stat_shared[ni];
221                         if (WARN_ON(dm_stat_in_flight(shared))) {
222                                 DMCRIT("leaked in-flight counter at index %lu "
223                                        "(start %llu, end %llu, step %llu): reads %d, writes %d",
224                                        (unsigned long)ni,
225                                        (unsigned long long)s->start,
226                                        (unsigned long long)s->end,
227                                        (unsigned long long)s->step,
228                                        atomic_read(&shared->in_flight[READ]),
229                                        atomic_read(&shared->in_flight[WRITE]));
230                         }
231                 }
232                 dm_stat_free(&s->rcu_head);
233         }
234         free_percpu(stats->last);
235 }
236
237 static int dm_stats_create(struct dm_stats *stats, sector_t start, sector_t end,
238                            sector_t step, unsigned stat_flags,
239                            unsigned n_histogram_entries,
240                            unsigned long long *histogram_boundaries,
241                            const char *program_id, const char *aux_data,
242                            void (*suspend_callback)(struct mapped_device *),
243                            void (*resume_callback)(struct mapped_device *),
244                            struct mapped_device *md)
245 {
246         struct list_head *l;
247         struct dm_stat *s, *tmp_s;
248         sector_t n_entries;
249         size_t ni;
250         size_t shared_alloc_size;
251         size_t percpu_alloc_size;
252         size_t histogram_alloc_size;
253         struct dm_stat_percpu *p;
254         int cpu;
255         int ret_id;
256         int r;
257
258         if (end < start || !step)
259                 return -EINVAL;
260
261         n_entries = end - start;
262         if (dm_sector_div64(n_entries, step))
263                 n_entries++;
264
265         if (n_entries != (size_t)n_entries || !(size_t)(n_entries + 1))
266                 return -EOVERFLOW;
267
268         shared_alloc_size = sizeof(struct dm_stat) + (size_t)n_entries * sizeof(struct dm_stat_shared);
269         if ((shared_alloc_size - sizeof(struct dm_stat)) / sizeof(struct dm_stat_shared) != n_entries)
270                 return -EOVERFLOW;
271
272         percpu_alloc_size = (size_t)n_entries * sizeof(struct dm_stat_percpu);
273         if (percpu_alloc_size / sizeof(struct dm_stat_percpu) != n_entries)
274                 return -EOVERFLOW;
275
276         histogram_alloc_size = (n_histogram_entries + 1) * (size_t)n_entries * sizeof(unsigned long long);
277         if (histogram_alloc_size / (n_histogram_entries + 1) != (size_t)n_entries * sizeof(unsigned long long))
278                 return -EOVERFLOW;
279
280         if (!check_shared_memory(shared_alloc_size + histogram_alloc_size +
281                                  num_possible_cpus() * (percpu_alloc_size + histogram_alloc_size)))
282                 return -ENOMEM;
283
284         s = dm_kvzalloc(shared_alloc_size, NUMA_NO_NODE);
285         if (!s)
286                 return -ENOMEM;
287
288         s->stat_flags = stat_flags;
289         s->n_entries = n_entries;
290         s->start = start;
291         s->end = end;
292         s->step = step;
293         s->shared_alloc_size = shared_alloc_size;
294         s->percpu_alloc_size = percpu_alloc_size;
295         s->histogram_alloc_size = histogram_alloc_size;
296
297         s->n_histogram_entries = n_histogram_entries;
298         s->histogram_boundaries = kmemdup(histogram_boundaries,
299                                           s->n_histogram_entries * sizeof(unsigned long long), GFP_KERNEL);
300         if (!s->histogram_boundaries) {
301                 r = -ENOMEM;
302                 goto out;
303         }
304
305         s->program_id = kstrdup(program_id, GFP_KERNEL);
306         if (!s->program_id) {
307                 r = -ENOMEM;
308                 goto out;
309         }
310         s->aux_data = kstrdup(aux_data, GFP_KERNEL);
311         if (!s->aux_data) {
312                 r = -ENOMEM;
313                 goto out;
314         }
315
316         for (ni = 0; ni < n_entries; ni++) {
317                 atomic_set(&s->stat_shared[ni].in_flight[READ], 0);
318                 atomic_set(&s->stat_shared[ni].in_flight[WRITE], 0);
319         }
320
321         if (s->n_histogram_entries) {
322                 unsigned long long *hi;
323                 hi = dm_kvzalloc(s->histogram_alloc_size, NUMA_NO_NODE);
324                 if (!hi) {
325                         r = -ENOMEM;
326                         goto out;
327                 }
328                 for (ni = 0; ni < n_entries; ni++) {
329                         s->stat_shared[ni].tmp.histogram = hi;
330                         hi += s->n_histogram_entries + 1;
331                 }
332         }
333
334         for_each_possible_cpu(cpu) {
335                 p = dm_kvzalloc(percpu_alloc_size, cpu_to_node(cpu));
336                 if (!p) {
337                         r = -ENOMEM;
338                         goto out;
339                 }
340                 s->stat_percpu[cpu] = p;
341                 if (s->n_histogram_entries) {
342                         unsigned long long *hi;
343                         hi = dm_kvzalloc(s->histogram_alloc_size, cpu_to_node(cpu));
344                         if (!hi) {
345                                 r = -ENOMEM;
346                                 goto out;
347                         }
348                         for (ni = 0; ni < n_entries; ni++) {
349                                 p[ni].histogram = hi;
350                                 hi += s->n_histogram_entries + 1;
351                         }
352                 }
353         }
354
355         /*
356          * Suspend/resume to make sure there is no i/o in flight,
357          * so that newly created statistics will be exact.
358          *
359          * (note: we couldn't suspend earlier because we must not
360          * allocate memory while suspended)
361          */
362         suspend_callback(md);
363
364         mutex_lock(&stats->mutex);
365         s->id = 0;
366         list_for_each(l, &stats->list) {
367                 tmp_s = container_of(l, struct dm_stat, list_entry);
368                 if (WARN_ON(tmp_s->id < s->id)) {
369                         r = -EINVAL;
370                         goto out_unlock_resume;
371                 }
372                 if (tmp_s->id > s->id)
373                         break;
374                 if (unlikely(s->id == INT_MAX)) {
375                         r = -ENFILE;
376                         goto out_unlock_resume;
377                 }
378                 s->id++;
379         }
380         ret_id = s->id;
381         list_add_tail_rcu(&s->list_entry, l);
382         mutex_unlock(&stats->mutex);
383
384         resume_callback(md);
385
386         return ret_id;
387
388 out_unlock_resume:
389         mutex_unlock(&stats->mutex);
390         resume_callback(md);
391 out:
392         dm_stat_free(&s->rcu_head);
393         return r;
394 }
395
396 static struct dm_stat *__dm_stats_find(struct dm_stats *stats, int id)
397 {
398         struct dm_stat *s;
399
400         list_for_each_entry(s, &stats->list, list_entry) {
401                 if (s->id > id)
402                         break;
403                 if (s->id == id)
404                         return s;
405         }
406
407         return NULL;
408 }
409
410 static int dm_stats_delete(struct dm_stats *stats, int id)
411 {
412         struct dm_stat *s;
413         int cpu;
414
415         mutex_lock(&stats->mutex);
416
417         s = __dm_stats_find(stats, id);
418         if (!s) {
419                 mutex_unlock(&stats->mutex);
420                 return -ENOENT;
421         }
422
423         list_del_rcu(&s->list_entry);
424         mutex_unlock(&stats->mutex);
425
426         /*
427          * vfree can't be called from RCU callback
428          */
429         for_each_possible_cpu(cpu)
430                 if (is_vmalloc_addr(s->stat_percpu) ||
431                     is_vmalloc_addr(s->stat_percpu[cpu][0].histogram))
432                         goto do_sync_free;
433         if (is_vmalloc_addr(s) ||
434             is_vmalloc_addr(s->stat_shared[0].tmp.histogram)) {
435 do_sync_free:
436                 synchronize_rcu_expedited();
437                 dm_stat_free(&s->rcu_head);
438         } else {
439                 ACCESS_ONCE(dm_stat_need_rcu_barrier) = 1;
440                 call_rcu(&s->rcu_head, dm_stat_free);
441         }
442         return 0;
443 }
444
445 static int dm_stats_list(struct dm_stats *stats, const char *program,
446                          char *result, unsigned maxlen)
447 {
448         struct dm_stat *s;
449         sector_t len;
450         unsigned sz = 0;
451
452         /*
453          * Output format:
454          *   <region_id>: <start_sector>+<length> <step> <program_id> <aux_data>
455          */
456
457         mutex_lock(&stats->mutex);
458         list_for_each_entry(s, &stats->list, list_entry) {
459                 if (!program || !strcmp(program, s->program_id)) {
460                         len = s->end - s->start;
461                         DMEMIT("%d: %llu+%llu %llu %s %s", s->id,
462                                 (unsigned long long)s->start,
463                                 (unsigned long long)len,
464                                 (unsigned long long)s->step,
465                                 s->program_id,
466                                 s->aux_data);
467                         if (s->stat_flags & STAT_PRECISE_TIMESTAMPS)
468                                 DMEMIT(" precise_timestamps");
469                         if (s->n_histogram_entries) {
470                                 unsigned i;
471                                 DMEMIT(" histogram:");
472                                 for (i = 0; i < s->n_histogram_entries; i++) {
473                                         if (i)
474                                                 DMEMIT(",");
475                                         DMEMIT("%llu", s->histogram_boundaries[i]);
476                                 }
477                         }
478                         DMEMIT("\n");
479                 }
480         }
481         mutex_unlock(&stats->mutex);
482
483         return 1;
484 }
485
486 static void dm_stat_round(struct dm_stat *s, struct dm_stat_shared *shared,
487                           struct dm_stat_percpu *p)
488 {
489         /*
490          * This is racy, but so is part_round_stats_single.
491          */
492         unsigned long long now, difference;
493         unsigned in_flight_read, in_flight_write;
494
495         if (likely(!(s->stat_flags & STAT_PRECISE_TIMESTAMPS)))
496                 now = jiffies;
497         else
498                 now = ktime_to_ns(ktime_get());
499
500         difference = now - shared->stamp;
501         if (!difference)
502                 return;
503
504         in_flight_read = (unsigned)atomic_read(&shared->in_flight[READ]);
505         in_flight_write = (unsigned)atomic_read(&shared->in_flight[WRITE]);
506         if (in_flight_read)
507                 p->io_ticks[READ] += difference;
508         if (in_flight_write)
509                 p->io_ticks[WRITE] += difference;
510         if (in_flight_read + in_flight_write) {
511                 p->io_ticks_total += difference;
512                 p->time_in_queue += (in_flight_read + in_flight_write) * difference;
513         }
514         shared->stamp = now;
515 }
516
517 static void dm_stat_for_entry(struct dm_stat *s, size_t entry,
518                               unsigned long bi_rw, sector_t len,
519                               struct dm_stats_aux *stats_aux, bool end,
520                               unsigned long duration_jiffies)
521 {
522         unsigned long idx = bi_rw & REQ_WRITE;
523         struct dm_stat_shared *shared = &s->stat_shared[entry];
524         struct dm_stat_percpu *p;
525
526         /*
527          * For strict correctness we should use local_irq_save/restore
528          * instead of preempt_disable/enable.
529          *
530          * preempt_disable/enable is racy if the driver finishes bios
531          * from non-interrupt context as well as from interrupt context
532          * or from more different interrupts.
533          *
534          * On 64-bit architectures the race only results in not counting some
535          * events, so it is acceptable.  On 32-bit architectures the race could
536          * cause the counter going off by 2^32, so we need to do proper locking
537          * there.
538          *
539          * part_stat_lock()/part_stat_unlock() have this race too.
540          */
541 #if BITS_PER_LONG == 32
542         unsigned long flags;
543         local_irq_save(flags);
544 #else
545         preempt_disable();
546 #endif
547         p = &s->stat_percpu[smp_processor_id()][entry];
548
549         if (!end) {
550                 dm_stat_round(s, shared, p);
551                 atomic_inc(&shared->in_flight[idx]);
552         } else {
553                 unsigned long long duration;
554                 dm_stat_round(s, shared, p);
555                 atomic_dec(&shared->in_flight[idx]);
556                 p->sectors[idx] += len;
557                 p->ios[idx] += 1;
558                 p->merges[idx] += stats_aux->merged;
559                 if (!(s->stat_flags & STAT_PRECISE_TIMESTAMPS)) {
560                         p->ticks[idx] += duration_jiffies;
561                         duration = jiffies_to_msecs(duration_jiffies);
562                 } else {
563                         p->ticks[idx] += stats_aux->duration_ns;
564                         duration = stats_aux->duration_ns;
565                 }
566                 if (s->n_histogram_entries) {
567                         unsigned lo = 0, hi = s->n_histogram_entries + 1;
568                         while (lo + 1 < hi) {
569                                 unsigned mid = (lo + hi) / 2;
570                                 if (s->histogram_boundaries[mid - 1] > duration) {
571                                         hi = mid;
572                                 } else {
573                                         lo = mid;
574                                 }
575
576                         }
577                         p->histogram[lo]++;
578                 }
579         }
580
581 #if BITS_PER_LONG == 32
582         local_irq_restore(flags);
583 #else
584         preempt_enable();
585 #endif
586 }
587
588 static void __dm_stat_bio(struct dm_stat *s, unsigned long bi_rw,
589                           sector_t bi_sector, sector_t end_sector,
590                           bool end, unsigned long duration_jiffies,
591                           struct dm_stats_aux *stats_aux)
592 {
593         sector_t rel_sector, offset, todo, fragment_len;
594         size_t entry;
595
596         if (end_sector <= s->start || bi_sector >= s->end)
597                 return;
598         if (unlikely(bi_sector < s->start)) {
599                 rel_sector = 0;
600                 todo = end_sector - s->start;
601         } else {
602                 rel_sector = bi_sector - s->start;
603                 todo = end_sector - bi_sector;
604         }
605         if (unlikely(end_sector > s->end))
606                 todo -= (end_sector - s->end);
607
608         offset = dm_sector_div64(rel_sector, s->step);
609         entry = rel_sector;
610         do {
611                 if (WARN_ON_ONCE(entry >= s->n_entries)) {
612                         DMCRIT("Invalid area access in region id %d", s->id);
613                         return;
614                 }
615                 fragment_len = todo;
616                 if (fragment_len > s->step - offset)
617                         fragment_len = s->step - offset;
618                 dm_stat_for_entry(s, entry, bi_rw, fragment_len,
619                                   stats_aux, end, duration_jiffies);
620                 todo -= fragment_len;
621                 entry++;
622                 offset = 0;
623         } while (unlikely(todo != 0));
624 }
625
626 void dm_stats_account_io(struct dm_stats *stats, unsigned long bi_rw,
627                          sector_t bi_sector, unsigned bi_sectors, bool end,
628                          unsigned long duration_jiffies,
629                          struct dm_stats_aux *stats_aux)
630 {
631         struct dm_stat *s;
632         sector_t end_sector;
633         struct dm_stats_last_position *last;
634         bool got_precise_time;
635
636         if (unlikely(!bi_sectors))
637                 return;
638
639         end_sector = bi_sector + bi_sectors;
640
641         if (!end) {
642                 /*
643                  * A race condition can at worst result in the merged flag being
644                  * misrepresented, so we don't have to disable preemption here.
645                  */
646                 last = raw_cpu_ptr(stats->last);
647                 stats_aux->merged =
648                         (bi_sector == (ACCESS_ONCE(last->last_sector) &&
649                                        ((bi_rw & (REQ_WRITE | REQ_DISCARD)) ==
650                                         (ACCESS_ONCE(last->last_rw) & (REQ_WRITE | REQ_DISCARD)))
651                                        ));
652                 ACCESS_ONCE(last->last_sector) = end_sector;
653                 ACCESS_ONCE(last->last_rw) = bi_rw;
654         }
655
656         rcu_read_lock();
657
658         got_precise_time = false;
659         list_for_each_entry_rcu(s, &stats->list, list_entry) {
660                 if (s->stat_flags & STAT_PRECISE_TIMESTAMPS && !got_precise_time) {
661                         if (!end)
662                                 stats_aux->duration_ns = ktime_to_ns(ktime_get());
663                         else
664                                 stats_aux->duration_ns = ktime_to_ns(ktime_get()) - stats_aux->duration_ns;
665                         got_precise_time = true;
666                 }
667                 __dm_stat_bio(s, bi_rw, bi_sector, end_sector, end, duration_jiffies, stats_aux);
668         }
669
670         rcu_read_unlock();
671 }
672
673 static void __dm_stat_init_temporary_percpu_totals(struct dm_stat_shared *shared,
674                                                    struct dm_stat *s, size_t x)
675 {
676         int cpu;
677         struct dm_stat_percpu *p;
678
679         local_irq_disable();
680         p = &s->stat_percpu[smp_processor_id()][x];
681         dm_stat_round(s, shared, p);
682         local_irq_enable();
683
684         shared->tmp.sectors[READ] = 0;
685         shared->tmp.sectors[WRITE] = 0;
686         shared->tmp.ios[READ] = 0;
687         shared->tmp.ios[WRITE] = 0;
688         shared->tmp.merges[READ] = 0;
689         shared->tmp.merges[WRITE] = 0;
690         shared->tmp.ticks[READ] = 0;
691         shared->tmp.ticks[WRITE] = 0;
692         shared->tmp.io_ticks[READ] = 0;
693         shared->tmp.io_ticks[WRITE] = 0;
694         shared->tmp.io_ticks_total = 0;
695         shared->tmp.time_in_queue = 0;
696
697         if (s->n_histogram_entries)
698                 memset(shared->tmp.histogram, 0, (s->n_histogram_entries + 1) * sizeof(unsigned long long));
699
700         for_each_possible_cpu(cpu) {
701                 p = &s->stat_percpu[cpu][x];
702                 shared->tmp.sectors[READ] += ACCESS_ONCE(p->sectors[READ]);
703                 shared->tmp.sectors[WRITE] += ACCESS_ONCE(p->sectors[WRITE]);
704                 shared->tmp.ios[READ] += ACCESS_ONCE(p->ios[READ]);
705                 shared->tmp.ios[WRITE] += ACCESS_ONCE(p->ios[WRITE]);
706                 shared->tmp.merges[READ] += ACCESS_ONCE(p->merges[READ]);
707                 shared->tmp.merges[WRITE] += ACCESS_ONCE(p->merges[WRITE]);
708                 shared->tmp.ticks[READ] += ACCESS_ONCE(p->ticks[READ]);
709                 shared->tmp.ticks[WRITE] += ACCESS_ONCE(p->ticks[WRITE]);
710                 shared->tmp.io_ticks[READ] += ACCESS_ONCE(p->io_ticks[READ]);
711                 shared->tmp.io_ticks[WRITE] += ACCESS_ONCE(p->io_ticks[WRITE]);
712                 shared->tmp.io_ticks_total += ACCESS_ONCE(p->io_ticks_total);
713                 shared->tmp.time_in_queue += ACCESS_ONCE(p->time_in_queue);
714                 if (s->n_histogram_entries) {
715                         unsigned i;
716                         for (i = 0; i < s->n_histogram_entries + 1; i++)
717                                 shared->tmp.histogram[i] += ACCESS_ONCE(p->histogram[i]);
718                 }
719         }
720 }
721
722 static void __dm_stat_clear(struct dm_stat *s, size_t idx_start, size_t idx_end,
723                             bool init_tmp_percpu_totals)
724 {
725         size_t x;
726         struct dm_stat_shared *shared;
727         struct dm_stat_percpu *p;
728
729         for (x = idx_start; x < idx_end; x++) {
730                 shared = &s->stat_shared[x];
731                 if (init_tmp_percpu_totals)
732                         __dm_stat_init_temporary_percpu_totals(shared, s, x);
733                 local_irq_disable();
734                 p = &s->stat_percpu[smp_processor_id()][x];
735                 p->sectors[READ] -= shared->tmp.sectors[READ];
736                 p->sectors[WRITE] -= shared->tmp.sectors[WRITE];
737                 p->ios[READ] -= shared->tmp.ios[READ];
738                 p->ios[WRITE] -= shared->tmp.ios[WRITE];
739                 p->merges[READ] -= shared->tmp.merges[READ];
740                 p->merges[WRITE] -= shared->tmp.merges[WRITE];
741                 p->ticks[READ] -= shared->tmp.ticks[READ];
742                 p->ticks[WRITE] -= shared->tmp.ticks[WRITE];
743                 p->io_ticks[READ] -= shared->tmp.io_ticks[READ];
744                 p->io_ticks[WRITE] -= shared->tmp.io_ticks[WRITE];
745                 p->io_ticks_total -= shared->tmp.io_ticks_total;
746                 p->time_in_queue -= shared->tmp.time_in_queue;
747                 local_irq_enable();
748                 if (s->n_histogram_entries) {
749                         unsigned i;
750                         for (i = 0; i < s->n_histogram_entries + 1; i++) {
751                                 local_irq_disable();
752                                 p = &s->stat_percpu[smp_processor_id()][x];
753                                 p->histogram[i] -= shared->tmp.histogram[i];
754                                 local_irq_enable();
755                         }
756                 }
757         }
758 }
759
760 static int dm_stats_clear(struct dm_stats *stats, int id)
761 {
762         struct dm_stat *s;
763
764         mutex_lock(&stats->mutex);
765
766         s = __dm_stats_find(stats, id);
767         if (!s) {
768                 mutex_unlock(&stats->mutex);
769                 return -ENOENT;
770         }
771
772         __dm_stat_clear(s, 0, s->n_entries, true);
773
774         mutex_unlock(&stats->mutex);
775
776         return 1;
777 }
778
779 /*
780  * This is like jiffies_to_msec, but works for 64-bit values.
781  */
782 static unsigned long long dm_jiffies_to_msec64(struct dm_stat *s, unsigned long long j)
783 {
784         unsigned long long result;
785         unsigned mult;
786
787         if (s->stat_flags & STAT_PRECISE_TIMESTAMPS)
788                 return j;
789
790         result = 0;
791         if (j)
792                 result = jiffies_to_msecs(j & 0x3fffff);
793         if (j >= 1 << 22) {
794                 mult = jiffies_to_msecs(1 << 22);
795                 result += (unsigned long long)mult * (unsigned long long)jiffies_to_msecs((j >> 22) & 0x3fffff);
796         }
797         if (j >= 1ULL << 44)
798                 result += (unsigned long long)mult * (unsigned long long)mult * (unsigned long long)jiffies_to_msecs(j >> 44);
799
800         return result;
801 }
802
803 static int dm_stats_print(struct dm_stats *stats, int id,
804                           size_t idx_start, size_t idx_len,
805                           bool clear, char *result, unsigned maxlen)
806 {
807         unsigned sz = 0;
808         struct dm_stat *s;
809         size_t x;
810         sector_t start, end, step;
811         size_t idx_end;
812         struct dm_stat_shared *shared;
813
814         /*
815          * Output format:
816          *   <start_sector>+<length> counters
817          */
818
819         mutex_lock(&stats->mutex);
820
821         s = __dm_stats_find(stats, id);
822         if (!s) {
823                 mutex_unlock(&stats->mutex);
824                 return -ENOENT;
825         }
826
827         idx_end = idx_start + idx_len;
828         if (idx_end < idx_start ||
829             idx_end > s->n_entries)
830                 idx_end = s->n_entries;
831
832         if (idx_start > idx_end)
833                 idx_start = idx_end;
834
835         step = s->step;
836         start = s->start + (step * idx_start);
837
838         for (x = idx_start; x < idx_end; x++, start = end) {
839                 shared = &s->stat_shared[x];
840                 end = start + step;
841                 if (unlikely(end > s->end))
842                         end = s->end;
843
844                 __dm_stat_init_temporary_percpu_totals(shared, s, x);
845
846                 DMEMIT("%llu+%llu %llu %llu %llu %llu %llu %llu %llu %llu %d %llu %llu %llu %llu",
847                        (unsigned long long)start,
848                        (unsigned long long)step,
849                        shared->tmp.ios[READ],
850                        shared->tmp.merges[READ],
851                        shared->tmp.sectors[READ],
852                        dm_jiffies_to_msec64(s, shared->tmp.ticks[READ]),
853                        shared->tmp.ios[WRITE],
854                        shared->tmp.merges[WRITE],
855                        shared->tmp.sectors[WRITE],
856                        dm_jiffies_to_msec64(s, shared->tmp.ticks[WRITE]),
857                        dm_stat_in_flight(shared),
858                        dm_jiffies_to_msec64(s, shared->tmp.io_ticks_total),
859                        dm_jiffies_to_msec64(s, shared->tmp.time_in_queue),
860                        dm_jiffies_to_msec64(s, shared->tmp.io_ticks[READ]),
861                        dm_jiffies_to_msec64(s, shared->tmp.io_ticks[WRITE]));
862                 if (s->n_histogram_entries) {
863                         unsigned i;
864                         for (i = 0; i < s->n_histogram_entries + 1; i++) {
865                                 DMEMIT("%s%llu", !i ? " " : ":", shared->tmp.histogram[i]);
866                         }
867                 }
868                 DMEMIT("\n");
869
870                 if (unlikely(sz + 1 >= maxlen))
871                         goto buffer_overflow;
872         }
873
874         if (clear)
875                 __dm_stat_clear(s, idx_start, idx_end, false);
876
877 buffer_overflow:
878         mutex_unlock(&stats->mutex);
879
880         return 1;
881 }
882
883 static int dm_stats_set_aux(struct dm_stats *stats, int id, const char *aux_data)
884 {
885         struct dm_stat *s;
886         const char *new_aux_data;
887
888         mutex_lock(&stats->mutex);
889
890         s = __dm_stats_find(stats, id);
891         if (!s) {
892                 mutex_unlock(&stats->mutex);
893                 return -ENOENT;
894         }
895
896         new_aux_data = kstrdup(aux_data, GFP_KERNEL);
897         if (!new_aux_data) {
898                 mutex_unlock(&stats->mutex);
899                 return -ENOMEM;
900         }
901
902         kfree(s->aux_data);
903         s->aux_data = new_aux_data;
904
905         mutex_unlock(&stats->mutex);
906
907         return 0;
908 }
909
910 static int parse_histogram(const char *h, unsigned *n_histogram_entries,
911                            unsigned long long **histogram_boundaries)
912 {
913         const char *q;
914         unsigned n;
915         unsigned long long last;
916
917         *n_histogram_entries = 1;
918         for (q = h; *q; q++)
919                 if (*q == ',')
920                         (*n_histogram_entries)++;
921
922         *histogram_boundaries = kmalloc(*n_histogram_entries * sizeof(unsigned long long), GFP_KERNEL);
923         if (!*histogram_boundaries)
924                 return -ENOMEM;
925
926         n = 0;
927         last = 0;
928         while (1) {
929                 unsigned long long hi;
930                 int s;
931                 char ch;
932                 s = sscanf(h, "%llu%c", &hi, &ch);
933                 if (!s || (s == 2 && ch != ','))
934                         return -EINVAL;
935                 if (hi <= last)
936                         return -EINVAL;
937                 last = hi;
938                 (*histogram_boundaries)[n] = hi;
939                 if (s == 1)
940                         return 0;
941                 h = strchr(h, ',') + 1;
942                 n++;
943         }
944 }
945
946 static int message_stats_create(struct mapped_device *md,
947                                 unsigned argc, char **argv,
948                                 char *result, unsigned maxlen)
949 {
950         int r;
951         int id;
952         char dummy;
953         unsigned long long start, end, len, step;
954         unsigned divisor;
955         const char *program_id, *aux_data;
956         unsigned stat_flags = 0;
957
958         unsigned n_histogram_entries = 0;
959         unsigned long long *histogram_boundaries = NULL;
960
961         struct dm_arg_set as, as_backup;
962         const char *a;
963         unsigned feature_args;
964
965         /*
966          * Input format:
967          *   <range> <step> [<extra_parameters> <parameters>] [<program_id> [<aux_data>]]
968          */
969
970         if (argc < 3)
971                 goto ret_einval;
972
973         as.argc = argc;
974         as.argv = argv;
975         dm_consume_args(&as, 1);
976
977         a = dm_shift_arg(&as);
978         if (!strcmp(a, "-")) {
979                 start = 0;
980                 len = dm_get_size(md);
981                 if (!len)
982                         len = 1;
983         } else if (sscanf(a, "%llu+%llu%c", &start, &len, &dummy) != 2 ||
984                    start != (sector_t)start || len != (sector_t)len)
985                 goto ret_einval;
986
987         end = start + len;
988         if (start >= end)
989                 goto ret_einval;
990
991         a = dm_shift_arg(&as);
992         if (sscanf(a, "/%u%c", &divisor, &dummy) == 1) {
993                 if (!divisor)
994                         return -EINVAL;
995                 step = end - start;
996                 if (do_div(step, divisor))
997                         step++;
998                 if (!step)
999                         step = 1;
1000         } else if (sscanf(a, "%llu%c", &step, &dummy) != 1 ||
1001                    step != (sector_t)step || !step)
1002                 goto ret_einval;
1003
1004         as_backup = as;
1005         a = dm_shift_arg(&as);
1006         if (a && sscanf(a, "%u%c", &feature_args, &dummy) == 1) {
1007                 while (feature_args--) {
1008                         a = dm_shift_arg(&as);
1009                         if (!a)
1010                                 goto ret_einval;
1011                         if (!strcasecmp(a, "precise_timestamps"))
1012                                 stat_flags |= STAT_PRECISE_TIMESTAMPS;
1013                         else if (!strncasecmp(a, "histogram:", 10)) {
1014                                 if (n_histogram_entries)
1015                                         goto ret_einval;
1016                                 if ((r = parse_histogram(a + 10, &n_histogram_entries, &histogram_boundaries)))
1017                                         goto ret;
1018                         } else
1019                                 goto ret_einval;
1020                 }
1021         } else {
1022                 as = as_backup;
1023         }
1024
1025         program_id = "-";
1026         aux_data = "-";
1027
1028         a = dm_shift_arg(&as);
1029         if (a)
1030                 program_id = a;
1031
1032         a = dm_shift_arg(&as);
1033         if (a)
1034                 aux_data = a;
1035
1036         if (as.argc)
1037                 goto ret_einval;
1038
1039         /*
1040          * If a buffer overflow happens after we created the region,
1041          * it's too late (the userspace would retry with a larger
1042          * buffer, but the region id that caused the overflow is already
1043          * leaked).  So we must detect buffer overflow in advance.
1044          */
1045         snprintf(result, maxlen, "%d", INT_MAX);
1046         if (dm_message_test_buffer_overflow(result, maxlen)) {
1047                 r = 1;
1048                 goto ret;
1049         }
1050
1051         id = dm_stats_create(dm_get_stats(md), start, end, step, stat_flags,
1052                              n_histogram_entries, histogram_boundaries, program_id, aux_data,
1053                              dm_internal_suspend_fast, dm_internal_resume_fast, md);
1054         if (id < 0) {
1055                 r = id;
1056                 goto ret;
1057         }
1058
1059         snprintf(result, maxlen, "%d", id);
1060
1061         r = 1;
1062         goto ret;
1063
1064 ret_einval:
1065         r = -EINVAL;
1066 ret:
1067         kfree(histogram_boundaries);
1068         return r;
1069 }
1070
1071 static int message_stats_delete(struct mapped_device *md,
1072                                 unsigned argc, char **argv)
1073 {
1074         int id;
1075         char dummy;
1076
1077         if (argc != 2)
1078                 return -EINVAL;
1079
1080         if (sscanf(argv[1], "%d%c", &id, &dummy) != 1 || id < 0)
1081                 return -EINVAL;
1082
1083         return dm_stats_delete(dm_get_stats(md), id);
1084 }
1085
1086 static int message_stats_clear(struct mapped_device *md,
1087                                unsigned argc, char **argv)
1088 {
1089         int id;
1090         char dummy;
1091
1092         if (argc != 2)
1093                 return -EINVAL;
1094
1095         if (sscanf(argv[1], "%d%c", &id, &dummy) != 1 || id < 0)
1096                 return -EINVAL;
1097
1098         return dm_stats_clear(dm_get_stats(md), id);
1099 }
1100
1101 static int message_stats_list(struct mapped_device *md,
1102                               unsigned argc, char **argv,
1103                               char *result, unsigned maxlen)
1104 {
1105         int r;
1106         const char *program = NULL;
1107
1108         if (argc < 1 || argc > 2)
1109                 return -EINVAL;
1110
1111         if (argc > 1) {
1112                 program = kstrdup(argv[1], GFP_KERNEL);
1113                 if (!program)
1114                         return -ENOMEM;
1115         }
1116
1117         r = dm_stats_list(dm_get_stats(md), program, result, maxlen);
1118
1119         kfree(program);
1120
1121         return r;
1122 }
1123
1124 static int message_stats_print(struct mapped_device *md,
1125                                unsigned argc, char **argv, bool clear,
1126                                char *result, unsigned maxlen)
1127 {
1128         int id;
1129         char dummy;
1130         unsigned long idx_start = 0, idx_len = ULONG_MAX;
1131
1132         if (argc != 2 && argc != 4)
1133                 return -EINVAL;
1134
1135         if (sscanf(argv[1], "%d%c", &id, &dummy) != 1 || id < 0)
1136                 return -EINVAL;
1137
1138         if (argc > 3) {
1139                 if (strcmp(argv[2], "-") &&
1140                     sscanf(argv[2], "%lu%c", &idx_start, &dummy) != 1)
1141                         return -EINVAL;
1142                 if (strcmp(argv[3], "-") &&
1143                     sscanf(argv[3], "%lu%c", &idx_len, &dummy) != 1)
1144                         return -EINVAL;
1145         }
1146
1147         return dm_stats_print(dm_get_stats(md), id, idx_start, idx_len, clear,
1148                               result, maxlen);
1149 }
1150
1151 static int message_stats_set_aux(struct mapped_device *md,
1152                                  unsigned argc, char **argv)
1153 {
1154         int id;
1155         char dummy;
1156
1157         if (argc != 3)
1158                 return -EINVAL;
1159
1160         if (sscanf(argv[1], "%d%c", &id, &dummy) != 1 || id < 0)
1161                 return -EINVAL;
1162
1163         return dm_stats_set_aux(dm_get_stats(md), id, argv[2]);
1164 }
1165
1166 int dm_stats_message(struct mapped_device *md, unsigned argc, char **argv,
1167                      char *result, unsigned maxlen)
1168 {
1169         int r;
1170
1171         /* All messages here must start with '@' */
1172         if (!strcasecmp(argv[0], "@stats_create"))
1173                 r = message_stats_create(md, argc, argv, result, maxlen);
1174         else if (!strcasecmp(argv[0], "@stats_delete"))
1175                 r = message_stats_delete(md, argc, argv);
1176         else if (!strcasecmp(argv[0], "@stats_clear"))
1177                 r = message_stats_clear(md, argc, argv);
1178         else if (!strcasecmp(argv[0], "@stats_list"))
1179                 r = message_stats_list(md, argc, argv, result, maxlen);
1180         else if (!strcasecmp(argv[0], "@stats_print"))
1181                 r = message_stats_print(md, argc, argv, false, result, maxlen);
1182         else if (!strcasecmp(argv[0], "@stats_print_clear"))
1183                 r = message_stats_print(md, argc, argv, true, result, maxlen);
1184         else if (!strcasecmp(argv[0], "@stats_set_aux"))
1185                 r = message_stats_set_aux(md, argc, argv);
1186         else
1187                 return 2; /* this wasn't a stats message */
1188
1189         if (r == -EINVAL)
1190                 DMWARN("Invalid parameters for message %s", argv[0]);
1191
1192         return r;
1193 }
1194
1195 int __init dm_statistics_init(void)
1196 {
1197         shared_memory_amount = 0;
1198         dm_stat_need_rcu_barrier = 0;
1199         return 0;
1200 }
1201
1202 void dm_statistics_exit(void)
1203 {
1204         if (dm_stat_need_rcu_barrier)
1205                 rcu_barrier();
1206         if (WARN_ON(shared_memory_amount))
1207                 DMCRIT("shared_memory_amount leaked: %lu", shared_memory_amount);
1208 }
1209
1210 module_param_named(stats_current_allocated_bytes, shared_memory_amount, ulong, S_IRUGO);
1211 MODULE_PARM_DESC(stats_current_allocated_bytes, "Memory currently used by statistics");