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