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