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