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