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