xref: /linux/kernel/trace/tracing_map.c (revision 2c142b63c8ee982cdfdba49a616027c266294838)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * tracing_map - lock-free map for tracing
4  *
5  * Copyright (C) 2015 Tom Zanussi <tom.zanussi@linux.intel.com>
6  *
7  * tracing_map implementation inspired by lock-free map algorithms
8  * originated by Dr. Cliff Click:
9  *
10  * http://www.azulsystems.com/blog/cliff/2007-03-26-non-blocking-hashtable
11  * http://www.azulsystems.com/events/javaone_2007/2007_LockFreeHash.pdf
12  */
13 
14 #include <linux/vmalloc.h>
15 #include <linux/jhash.h>
16 #include <linux/slab.h>
17 #include <linux/sort.h>
18 #include <linux/kmemleak.h>
19 
20 #include "tracing_map.h"
21 #include "trace.h"
22 
23 /*
24  * NOTE: For a detailed description of the data structures used by
25  * these functions (such as tracing_map_elt) please see the overview
26  * of tracing_map data structures at the beginning of tracing_map.h.
27  */
28 
29 /**
30  * tracing_map_update_sum - Add a value to a tracing_map_elt's sum field
31  * @elt: The tracing_map_elt
32  * @i: The index of the given sum associated with the tracing_map_elt
33  * @n: The value to add to the sum
34  *
35  * Add n to sum i associated with the specified tracing_map_elt
36  * instance.  The index i is the index returned by the call to
37  * tracing_map_add_sum_field() when the tracing map was set up.
38  */
tracing_map_update_sum(struct tracing_map_elt * elt,unsigned int i,u64 n)39 void tracing_map_update_sum(struct tracing_map_elt *elt, unsigned int i, u64 n)
40 {
41 	atomic64_add(n, &elt->fields[i].sum);
42 }
43 
44 /**
45  * tracing_map_read_sum - Return the value of a tracing_map_elt's sum field
46  * @elt: The tracing_map_elt
47  * @i: The index of the given sum associated with the tracing_map_elt
48  *
49  * Retrieve the value of the sum i associated with the specified
50  * tracing_map_elt instance.  The index i is the index returned by the
51  * call to tracing_map_add_sum_field() when the tracing map was set
52  * up.
53  *
54  * Return: The sum associated with field i for elt.
55  */
tracing_map_read_sum(struct tracing_map_elt * elt,unsigned int i)56 u64 tracing_map_read_sum(struct tracing_map_elt *elt, unsigned int i)
57 {
58 	return (u64)atomic64_read(&elt->fields[i].sum);
59 }
60 
61 /**
62  * tracing_map_set_var - Assign a tracing_map_elt's variable field
63  * @elt: The tracing_map_elt
64  * @i: The index of the given variable associated with the tracing_map_elt
65  * @n: The value to assign
66  *
67  * Assign n to variable i associated with the specified tracing_map_elt
68  * instance.  The index i is the index returned by the call to
69  * tracing_map_add_var() when the tracing map was set up.
70  */
tracing_map_set_var(struct tracing_map_elt * elt,unsigned int i,u64 n)71 void tracing_map_set_var(struct tracing_map_elt *elt, unsigned int i, u64 n)
72 {
73 	atomic64_set(&elt->vars[i], n);
74 	elt->var_set[i] = true;
75 }
76 
77 /**
78  * tracing_map_var_set - Return whether or not a variable has been set
79  * @elt: The tracing_map_elt
80  * @i: The index of the given variable associated with the tracing_map_elt
81  *
82  * Return true if the variable has been set, false otherwise.  The
83  * index i is the index returned by the call to tracing_map_add_var()
84  * when the tracing map was set up.
85  */
tracing_map_var_set(struct tracing_map_elt * elt,unsigned int i)86 bool tracing_map_var_set(struct tracing_map_elt *elt, unsigned int i)
87 {
88 	return elt->var_set[i];
89 }
90 
91 /**
92  * tracing_map_read_var - Return the value of a tracing_map_elt's variable field
93  * @elt: The tracing_map_elt
94  * @i: The index of the given variable associated with the tracing_map_elt
95  *
96  * Retrieve the value of the variable i associated with the specified
97  * tracing_map_elt instance.  The index i is the index returned by the
98  * call to tracing_map_add_var() when the tracing map was set
99  * up.
100  *
101  * Return: The variable value associated with field i for elt.
102  */
tracing_map_read_var(struct tracing_map_elt * elt,unsigned int i)103 u64 tracing_map_read_var(struct tracing_map_elt *elt, unsigned int i)
104 {
105 	return (u64)atomic64_read(&elt->vars[i]);
106 }
107 
108 /**
109  * tracing_map_read_var_once - Return and reset a tracing_map_elt's variable field
110  * @elt: The tracing_map_elt
111  * @i: The index of the given variable associated with the tracing_map_elt
112  *
113  * Retrieve the value of the variable i associated with the specified
114  * tracing_map_elt instance, and reset the variable to the 'not set'
115  * state.  The index i is the index returned by the call to
116  * tracing_map_add_var() when the tracing map was set up.  The reset
117  * essentially makes the variable a read-once variable if it's only
118  * accessed using this function.
119  *
120  * Return: The variable value associated with field i for elt.
121  */
tracing_map_read_var_once(struct tracing_map_elt * elt,unsigned int i)122 u64 tracing_map_read_var_once(struct tracing_map_elt *elt, unsigned int i)
123 {
124 	elt->var_set[i] = false;
125 	return (u64)atomic64_read(&elt->vars[i]);
126 }
127 
tracing_map_cmp_string(void * val_a,void * val_b)128 int tracing_map_cmp_string(void *val_a, void *val_b)
129 {
130 	char *a = val_a;
131 	char *b = val_b;
132 
133 	return strcmp(a, b);
134 }
135 
tracing_map_cmp_none(void * val_a,void * val_b)136 int tracing_map_cmp_none(void *val_a, void *val_b)
137 {
138 	return 0;
139 }
140 
tracing_map_cmp_atomic64(void * val_a,void * val_b)141 static int tracing_map_cmp_atomic64(void *val_a, void *val_b)
142 {
143 	u64 a = atomic64_read((atomic64_t *)val_a);
144 	u64 b = atomic64_read((atomic64_t *)val_b);
145 
146 	return (a > b) ? 1 : ((a < b) ? -1 : 0);
147 }
148 
149 #define DEFINE_TRACING_MAP_CMP_FN(type)					\
150 static int tracing_map_cmp_##type(void *val_a, void *val_b)		\
151 {									\
152 	type a = (type)(*(u64 *)val_a);					\
153 	type b = (type)(*(u64 *)val_b);					\
154 									\
155 	return (a > b) ? 1 : ((a < b) ? -1 : 0);			\
156 }
157 
158 DEFINE_TRACING_MAP_CMP_FN(s64);
159 DEFINE_TRACING_MAP_CMP_FN(u64);
160 DEFINE_TRACING_MAP_CMP_FN(s32);
161 DEFINE_TRACING_MAP_CMP_FN(u32);
162 DEFINE_TRACING_MAP_CMP_FN(s16);
163 DEFINE_TRACING_MAP_CMP_FN(u16);
164 DEFINE_TRACING_MAP_CMP_FN(s8);
165 DEFINE_TRACING_MAP_CMP_FN(u8);
166 
tracing_map_cmp_num(int field_size,int field_is_signed)167 tracing_map_cmp_fn_t tracing_map_cmp_num(int field_size,
168 					 int field_is_signed)
169 {
170 	tracing_map_cmp_fn_t fn = tracing_map_cmp_none;
171 
172 	switch (field_size) {
173 	case 8:
174 		if (field_is_signed)
175 			fn = tracing_map_cmp_s64;
176 		else
177 			fn = tracing_map_cmp_u64;
178 		break;
179 	case 4:
180 		if (field_is_signed)
181 			fn = tracing_map_cmp_s32;
182 		else
183 			fn = tracing_map_cmp_u32;
184 		break;
185 	case 2:
186 		if (field_is_signed)
187 			fn = tracing_map_cmp_s16;
188 		else
189 			fn = tracing_map_cmp_u16;
190 		break;
191 	case 1:
192 		if (field_is_signed)
193 			fn = tracing_map_cmp_s8;
194 		else
195 			fn = tracing_map_cmp_u8;
196 		break;
197 	}
198 
199 	return fn;
200 }
201 
tracing_map_add_field(struct tracing_map * map,tracing_map_cmp_fn_t cmp_fn)202 static int tracing_map_add_field(struct tracing_map *map,
203 				 tracing_map_cmp_fn_t cmp_fn)
204 {
205 	int ret = -EINVAL;
206 
207 	if (map->n_fields < TRACING_MAP_FIELDS_MAX) {
208 		ret = map->n_fields;
209 		map->fields[map->n_fields++].cmp_fn = cmp_fn;
210 	}
211 
212 	return ret;
213 }
214 
215 /**
216  * tracing_map_add_sum_field - Add a field describing a tracing_map sum
217  * @map: The tracing_map
218  *
219  * Add a sum field to the key and return the index identifying it in
220  * the map and associated tracing_map_elts.  This is the index used
221  * for instance to update a sum for a particular tracing_map_elt using
222  * tracing_map_update_sum() or reading it via tracing_map_read_sum().
223  *
224  * Return: The index identifying the field in the map and associated
225  * tracing_map_elts, or -EINVAL on error.
226  */
tracing_map_add_sum_field(struct tracing_map * map)227 int tracing_map_add_sum_field(struct tracing_map *map)
228 {
229 	return tracing_map_add_field(map, tracing_map_cmp_atomic64);
230 }
231 
232 /**
233  * tracing_map_add_var - Add a field describing a tracing_map var
234  * @map: The tracing_map
235  *
236  * Add a var to the map and return the index identifying it in the map
237  * and associated tracing_map_elts.  This is the index used for
238  * instance to update a var for a particular tracing_map_elt using
239  * tracing_map_update_var() or reading it via tracing_map_read_var().
240  *
241  * Return: The index identifying the var in the map and associated
242  * tracing_map_elts, or -EINVAL on error.
243  */
tracing_map_add_var(struct tracing_map * map)244 int tracing_map_add_var(struct tracing_map *map)
245 {
246 	int ret = -EINVAL;
247 
248 	if (map->n_vars < TRACING_MAP_VARS_MAX)
249 		ret = map->n_vars++;
250 
251 	return ret;
252 }
253 
254 /**
255  * tracing_map_add_key_field - Add a field describing a tracing_map key
256  * @map: The tracing_map
257  * @offset: The offset within the key
258  * @cmp_fn: The comparison function that will be used to sort on the key
259  *
260  * Let the map know there is a key and that if it's used as a sort key
261  * to use cmp_fn.
262  *
263  * A key can be a subset of a compound key; for that purpose, the
264  * offset param is used to describe where within the compound key
265  * the key referenced by this key field resides.
266  *
267  * Return: The index identifying the field in the map and associated
268  * tracing_map_elts, or -EINVAL on error.
269  */
tracing_map_add_key_field(struct tracing_map * map,unsigned int offset,tracing_map_cmp_fn_t cmp_fn)270 int tracing_map_add_key_field(struct tracing_map *map,
271 			      unsigned int offset,
272 			      tracing_map_cmp_fn_t cmp_fn)
273 
274 {
275 	int idx = tracing_map_add_field(map, cmp_fn);
276 
277 	if (idx < 0)
278 		return idx;
279 
280 	map->fields[idx].offset = offset;
281 
282 	map->key_idx[map->n_keys++] = idx;
283 
284 	return idx;
285 }
286 
tracing_map_array_clear(struct tracing_map_array * a)287 static void tracing_map_array_clear(struct tracing_map_array *a)
288 {
289 	unsigned int i;
290 
291 	if (!a->pages)
292 		return;
293 
294 	for (i = 0; i < a->n_pages; i++)
295 		memset(a->pages[i], 0, PAGE_SIZE);
296 }
297 
tracing_map_array_free(struct tracing_map_array * a)298 static void tracing_map_array_free(struct tracing_map_array *a)
299 {
300 	unsigned int i;
301 
302 	if (!a)
303 		return;
304 
305 	if (!a->pages)
306 		goto free;
307 
308 	for (i = 0; i < a->n_pages; i++) {
309 		if (!a->pages[i])
310 			break;
311 		kmemleak_free(a->pages[i]);
312 		free_page((unsigned long)a->pages[i]);
313 	}
314 
315 	kfree(a->pages);
316 
317  free:
318 	kfree(a);
319 }
320 
tracing_map_array_alloc(unsigned int n_elts,unsigned int entry_size)321 static struct tracing_map_array *tracing_map_array_alloc(unsigned int n_elts,
322 						  unsigned int entry_size)
323 {
324 	struct tracing_map_array *a;
325 	unsigned int i;
326 
327 	a = kzalloc_obj(*a);
328 	if (!a)
329 		return NULL;
330 
331 	a->entry_size_shift = fls(roundup_pow_of_two(entry_size) - 1);
332 	a->entries_per_page = PAGE_SIZE / (1 << a->entry_size_shift);
333 	a->n_pages = n_elts / a->entries_per_page;
334 	if (!a->n_pages)
335 		a->n_pages = 1;
336 	a->entry_shift = fls(a->entries_per_page) - 1;
337 	a->entry_mask = (1 << a->entry_shift) - 1;
338 
339 	a->pages = kcalloc(a->n_pages, sizeof(void *), GFP_KERNEL);
340 	if (!a->pages)
341 		goto free;
342 
343 	for (i = 0; i < a->n_pages; i++) {
344 		a->pages[i] = (void *)get_zeroed_page(GFP_KERNEL);
345 		if (!a->pages[i])
346 			goto free;
347 		kmemleak_alloc(a->pages[i], PAGE_SIZE, 1, GFP_KERNEL);
348 	}
349  out:
350 	return a;
351  free:
352 	tracing_map_array_free(a);
353 	a = NULL;
354 
355 	goto out;
356 }
357 
tracing_map_elt_clear(struct tracing_map_elt * elt)358 static void tracing_map_elt_clear(struct tracing_map_elt *elt)
359 {
360 	unsigned i;
361 
362 	for (i = 0; i < elt->map->n_fields; i++)
363 		if (elt->fields[i].cmp_fn == tracing_map_cmp_atomic64)
364 			atomic64_set(&elt->fields[i].sum, 0);
365 
366 	for (i = 0; i < elt->map->n_vars; i++) {
367 		atomic64_set(&elt->vars[i], 0);
368 		elt->var_set[i] = false;
369 	}
370 
371 	if (elt->map->ops && elt->map->ops->elt_clear)
372 		elt->map->ops->elt_clear(elt);
373 }
374 
tracing_map_elt_init_fields(struct tracing_map_elt * elt)375 static void tracing_map_elt_init_fields(struct tracing_map_elt *elt)
376 {
377 	unsigned int i;
378 
379 	tracing_map_elt_clear(elt);
380 
381 	for (i = 0; i < elt->map->n_fields; i++) {
382 		elt->fields[i].cmp_fn = elt->map->fields[i].cmp_fn;
383 
384 		if (elt->fields[i].cmp_fn != tracing_map_cmp_atomic64)
385 			elt->fields[i].offset = elt->map->fields[i].offset;
386 	}
387 }
388 
__tracing_map_elt_free(struct tracing_map_elt * elt)389 static void __tracing_map_elt_free(struct tracing_map_elt *elt)
390 {
391 	if (!elt)
392 		return;
393 
394 	kfree(elt->fields);
395 	kfree(elt->vars);
396 	kfree(elt->var_set);
397 	kfree(elt->key);
398 	kfree(elt);
399 }
400 
tracing_map_elt_free(struct tracing_map_elt * elt)401 static void tracing_map_elt_free(struct tracing_map_elt *elt)
402 {
403 	if (!elt)
404 		return;
405 
406 	/* Only objects initialized with alloc_elt() should be passed to free_elt().*/
407 	if (elt->map->ops && elt->map->ops->elt_free)
408 		elt->map->ops->elt_free(elt);
409 	__tracing_map_elt_free(elt);
410 }
411 
tracing_map_elt_alloc(struct tracing_map * map)412 static struct tracing_map_elt *tracing_map_elt_alloc(struct tracing_map *map)
413 {
414 	struct tracing_map_elt *elt;
415 	int err = 0;
416 
417 	elt = kzalloc_obj(*elt);
418 	if (!elt)
419 		return ERR_PTR(-ENOMEM);
420 
421 	elt->map = map;
422 
423 	elt->key = kzalloc(map->key_size, GFP_KERNEL);
424 	if (!elt->key) {
425 		err = -ENOMEM;
426 		goto free;
427 	}
428 
429 	elt->fields = kzalloc_objs(*elt->fields, map->n_fields);
430 	if (!elt->fields) {
431 		err = -ENOMEM;
432 		goto free;
433 	}
434 
435 	elt->vars = kzalloc_objs(*elt->vars, map->n_vars);
436 	if (!elt->vars) {
437 		err = -ENOMEM;
438 		goto free;
439 	}
440 
441 	elt->var_set = kzalloc_objs(*elt->var_set, map->n_vars);
442 	if (!elt->var_set) {
443 		err = -ENOMEM;
444 		goto free;
445 	}
446 
447 	tracing_map_elt_init_fields(elt);
448 
449 	if (map->ops && map->ops->elt_alloc) {
450 		err = map->ops->elt_alloc(elt);
451 		if (err)
452 			goto free;
453 	}
454 	return elt;
455  free:
456 	__tracing_map_elt_free(elt);
457 
458 	return ERR_PTR(err);
459 }
460 
get_free_elt(struct tracing_map * map)461 static struct tracing_map_elt *get_free_elt(struct tracing_map *map)
462 {
463 	struct tracing_map_elt *elt = NULL;
464 	int idx;
465 
466 	idx = atomic_fetch_add_unless(&map->next_elt, 1, map->max_elts);
467 	if (idx < map->max_elts) {
468 		elt = *(TRACING_MAP_ELT(map->elts, idx));
469 		if (map->ops && map->ops->elt_init)
470 			map->ops->elt_init(elt);
471 	}
472 
473 	return elt;
474 }
475 
tracing_map_free_elts(struct tracing_map * map)476 static void tracing_map_free_elts(struct tracing_map *map)
477 {
478 	unsigned int i;
479 
480 	if (!map->elts)
481 		return;
482 
483 	for (i = 0; i < map->max_elts; i++) {
484 		tracing_map_elt_free(*(TRACING_MAP_ELT(map->elts, i)));
485 		*(TRACING_MAP_ELT(map->elts, i)) = NULL;
486 	}
487 
488 	tracing_map_array_free(map->elts);
489 	map->elts = NULL;
490 }
491 
tracing_map_alloc_elts(struct tracing_map * map)492 static int tracing_map_alloc_elts(struct tracing_map *map)
493 {
494 	unsigned int i;
495 
496 	map->elts = tracing_map_array_alloc(map->max_elts,
497 					    sizeof(struct tracing_map_elt *));
498 	if (!map->elts)
499 		return -ENOMEM;
500 
501 	for (i = 0; i < map->max_elts; i++) {
502 		*(TRACING_MAP_ELT(map->elts, i)) = tracing_map_elt_alloc(map);
503 		if (IS_ERR(*(TRACING_MAP_ELT(map->elts, i)))) {
504 			*(TRACING_MAP_ELT(map->elts, i)) = NULL;
505 			tracing_map_free_elts(map);
506 
507 			return -ENOMEM;
508 		}
509 	}
510 
511 	return 0;
512 }
513 
keys_match(void * key,void * test_key,unsigned key_size)514 static inline bool keys_match(void *key, void *test_key, unsigned key_size)
515 {
516 	bool match = true;
517 
518 	if (memcmp(key, test_key, key_size))
519 		match = false;
520 
521 	return match;
522 }
523 
524 static inline struct tracing_map_elt *
__tracing_map_insert(struct tracing_map * map,void * key,bool lookup_only)525 __tracing_map_insert(struct tracing_map *map, void *key, bool lookup_only)
526 {
527 	u32 idx, key_hash, test_key;
528 	int dup_try = 0;
529 	struct tracing_map_entry *entry;
530 	struct tracing_map_elt *val;
531 
532 	key_hash = jhash(key, map->key_size, 0);
533 	if (key_hash == 0)
534 		key_hash = 1;
535 	idx = key_hash >> (32 - (map->map_bits + 1));
536 
537 	while (1) {
538 		idx &= (map->map_size - 1);
539 		entry = TRACING_MAP_ENTRY(map->map, idx);
540 		test_key = entry->key;
541 
542 		if (test_key && test_key == key_hash) {
543 			val = READ_ONCE(entry->val);
544 			if (val &&
545 			    keys_match(key, val->key, map->key_size)) {
546 				if (!lookup_only)
547 					atomic64_inc(&map->hits);
548 				return val;
549 			} else if (unlikely(!val)) {
550 				/*
551 				 * The key is present. But, val (pointer to elt
552 				 * struct) is still NULL. which means some other
553 				 * thread is in the process of inserting an
554 				 * element.
555 				 *
556 				 * On top of that, it's key_hash is same as the
557 				 * one being inserted right now. So, it's
558 				 * possible that the element has the same
559 				 * key as well.
560 				 */
561 
562 				dup_try++;
563 				if (dup_try > map->map_size) {
564 					atomic64_inc(&map->drops);
565 					break;
566 				}
567 				continue;
568 			}
569 		}
570 
571 		if (!test_key) {
572 			if (lookup_only)
573 				break;
574 
575 			if (!cmpxchg(&entry->key, 0, key_hash)) {
576 				struct tracing_map_elt *elt;
577 
578 				elt = get_free_elt(map);
579 				if (!elt) {
580 					atomic64_inc(&map->drops);
581 					entry->key = 0;
582 					break;
583 				}
584 
585 				memcpy(elt->key, key, map->key_size);
586 				/*
587 				 * Ensure the initialization is visible and
588 				 * publish the elt.
589 				 */
590 				smp_wmb();
591 				WRITE_ONCE(entry->val, elt);
592 				atomic64_inc(&map->hits);
593 
594 				return entry->val;
595 			} else {
596 				/*
597 				 * cmpxchg() failed. Loop around once
598 				 * more to check what key was inserted.
599 				 */
600 				dup_try++;
601 				continue;
602 			}
603 		}
604 
605 		idx++;
606 	}
607 
608 	return NULL;
609 }
610 
611 /**
612  * tracing_map_insert - Insert key and/or retrieve val from a tracing_map
613  * @map: The tracing_map to insert into
614  * @key: The key to insert
615  *
616  * Inserts a key into a tracing_map and creates and returns a new
617  * tracing_map_elt for it, or if the key has already been inserted by
618  * a previous call, returns the tracing_map_elt already associated
619  * with it.  When the map was created, the number of elements to be
620  * allocated for the map was specified (internally maintained as
621  * 'max_elts' in struct tracing_map), and that number of
622  * tracing_map_elts was created by tracing_map_init().  This is the
623  * pre-allocated pool of tracing_map_elts that tracing_map_insert()
624  * will allocate from when adding new keys.  Once that pool is
625  * exhausted, tracing_map_insert() is useless and will return NULL to
626  * signal that state.  There are two user-visible tracing_map
627  * variables, 'hits' and 'drops', which are updated by this function.
628  * Every time an element is either successfully inserted or retrieved,
629  * the 'hits' value is incremented.  Every time an element insertion
630  * fails, the 'drops' value is incremented.
631  *
632  * This is a lock-free tracing map insertion function implementing a
633  * modified form of Cliff Click's basic insertion algorithm.  It
634  * requires the table size be a power of two.  To prevent any
635  * possibility of an infinite loop we always make the internal table
636  * size double the size of the requested table size (max_elts * 2).
637  * Likewise, we never reuse a slot or resize or delete elements - when
638  * we've reached max_elts entries, we simply return NULL once we've
639  * run out of entries.  Readers can at any point in time traverse the
640  * tracing map and safely access the key/val pairs.
641  *
642  * Return: the tracing_map_elt pointer val associated with the key.
643  * If this was a newly inserted key, the val will be a newly allocated
644  * and associated tracing_map_elt pointer val.  If the key wasn't
645  * found and the pool of tracing_map_elts has been exhausted, NULL is
646  * returned and no further insertions will succeed.
647  */
tracing_map_insert(struct tracing_map * map,void * key)648 struct tracing_map_elt *tracing_map_insert(struct tracing_map *map, void *key)
649 {
650 	return __tracing_map_insert(map, key, false);
651 }
652 
653 /**
654  * tracing_map_lookup - Retrieve val from a tracing_map
655  * @map: The tracing_map to perform the lookup on
656  * @key: The key to look up
657  *
658  * Looks up key in tracing_map and if found returns the matching
659  * tracing_map_elt.  This is a lock-free lookup; see
660  * tracing_map_insert() for details on tracing_map and how it works.
661  * Every time an element is retrieved, the 'hits' value is
662  * incremented.  There is one user-visible tracing_map variable,
663  * 'hits', which is updated by this function.  Every time an element
664  * is successfully retrieved, the 'hits' value is incremented.  The
665  * 'drops' value is never updated by this function.
666  *
667  * Return: the tracing_map_elt pointer val associated with the key.
668  * If the key wasn't found, NULL is returned.
669  */
tracing_map_lookup(struct tracing_map * map,void * key)670 struct tracing_map_elt *tracing_map_lookup(struct tracing_map *map, void *key)
671 {
672 	return __tracing_map_insert(map, key, true);
673 }
674 
675 /**
676  * tracing_map_destroy - Destroy a tracing_map
677  * @map: The tracing_map to destroy
678  *
679  * Frees a tracing_map along with its associated array of
680  * tracing_map_elts.
681  *
682  * Callers should make sure there are no readers or writers actively
683  * reading or inserting into the map before calling this.
684  */
tracing_map_destroy(struct tracing_map * map)685 void tracing_map_destroy(struct tracing_map *map)
686 {
687 	if (!map)
688 		return;
689 
690 	tracing_map_free_elts(map);
691 
692 	tracing_map_array_free(map->map);
693 	kfree(map);
694 }
695 
696 /**
697  * tracing_map_clear - Clear a tracing_map
698  * @map: The tracing_map to clear
699  *
700  * Resets the tracing map to a cleared or initial state.  The
701  * tracing_map_elts are all cleared, and the array of struct
702  * tracing_map_entry is reset to an initialized state.
703  *
704  * Callers should make sure there are no writers actively inserting
705  * into the map before calling this.
706  */
tracing_map_clear(struct tracing_map * map)707 void tracing_map_clear(struct tracing_map *map)
708 {
709 	unsigned int i;
710 
711 	atomic_set(&map->next_elt, 0);
712 	atomic64_set(&map->hits, 0);
713 	atomic64_set(&map->drops, 0);
714 
715 	tracing_map_array_clear(map->map);
716 
717 	for (i = 0; i < map->max_elts; i++)
718 		tracing_map_elt_clear(*(TRACING_MAP_ELT(map->elts, i)));
719 }
720 
set_sort_key(struct tracing_map * map,struct tracing_map_sort_key * sort_key)721 static void set_sort_key(struct tracing_map *map,
722 			 struct tracing_map_sort_key *sort_key)
723 {
724 	map->sort_key = *sort_key;
725 }
726 
727 /**
728  * tracing_map_create - Create a lock-free map and element pool
729  * @map_bits: The size of the map (2 ** map_bits)
730  * @key_size: The size of the key for the map in bytes
731  * @ops: Optional client-defined tracing_map_ops instance
732  * @private_data: Client data associated with the map
733  *
734  * Creates and sets up a map to contain 2 ** map_bits number of
735  * elements (internally maintained as 'max_elts' in struct
736  * tracing_map).  Before using, map fields should be added to the map
737  * with tracing_map_add_sum_field() and tracing_map_add_key_field().
738  * tracing_map_init() should then be called to allocate the array of
739  * tracing_map_elts, in order to avoid allocating anything in the map
740  * insertion path.  The user-specified map size reflects the maximum
741  * number of elements that can be contained in the table requested by
742  * the user - internally we double that in order to keep the table
743  * sparse and keep collisions manageable.
744  *
745  * A tracing_map is a special-purpose map designed to aggregate or
746  * 'sum' one or more values associated with a specific object of type
747  * tracing_map_elt, which is attached by the map to a given key.
748  *
749  * tracing_map_create() sets up the map itself, and provides
750  * operations for inserting tracing_map_elts, but doesn't allocate the
751  * tracing_map_elts themselves, or provide a means for describing the
752  * keys or sums associated with the tracing_map_elts.  All
753  * tracing_map_elts for a given map have the same set of sums and
754  * keys, which are defined by the client using the functions
755  * tracing_map_add_key_field() and tracing_map_add_sum_field().  Once
756  * the fields are defined, the pool of elements allocated for the map
757  * can be created, which occurs when the client code calls
758  * tracing_map_init().
759  *
760  * When tracing_map_init() returns, tracing_map_elt elements can be
761  * inserted into the map using tracing_map_insert().  When called,
762  * tracing_map_insert() grabs a free tracing_map_elt from the pool, or
763  * finds an existing match in the map and in either case returns it.
764  * The client can then use tracing_map_update_sum() and
765  * tracing_map_read_sum() to update or read a given sum field for the
766  * tracing_map_elt.
767  *
768  * The client can at any point retrieve and traverse the current set
769  * of inserted tracing_map_elts in a tracing_map, via
770  * tracing_map_sort_entries().  Sorting can be done on any field,
771  * including keys.
772  *
773  * See tracing_map.h for a description of tracing_map_ops.
774  *
775  * Return: the tracing_map pointer if successful, ERR_PTR if not.
776  */
tracing_map_create(unsigned int map_bits,unsigned int key_size,const struct tracing_map_ops * ops,void * private_data)777 struct tracing_map *tracing_map_create(unsigned int map_bits,
778 				       unsigned int key_size,
779 				       const struct tracing_map_ops *ops,
780 				       void *private_data)
781 {
782 	struct tracing_map *map;
783 	unsigned int i;
784 
785 	if (map_bits < TRACING_MAP_BITS_MIN ||
786 	    map_bits > TRACING_MAP_BITS_MAX)
787 		return ERR_PTR(-EINVAL);
788 
789 	map = kzalloc_obj(*map);
790 	if (!map)
791 		return ERR_PTR(-ENOMEM);
792 
793 	map->map_bits = map_bits;
794 	map->max_elts = (1 << map_bits);
795 	atomic_set(&map->next_elt, 0);
796 
797 	map->map_size = (1 << (map_bits + 1));
798 	map->ops = ops;
799 
800 	map->private_data = private_data;
801 
802 	map->map = tracing_map_array_alloc(map->map_size,
803 					   sizeof(struct tracing_map_entry));
804 	if (!map->map)
805 		goto free;
806 
807 	map->key_size = key_size;
808 	for (i = 0; i < TRACING_MAP_KEYS_MAX; i++)
809 		map->key_idx[i] = -1;
810  out:
811 	return map;
812  free:
813 	tracing_map_destroy(map);
814 	map = ERR_PTR(-ENOMEM);
815 
816 	goto out;
817 }
818 
819 /**
820  * tracing_map_init - Allocate and clear a map's tracing_map_elts
821  * @map: The tracing_map to initialize
822  *
823  * Allocates a clears a pool of tracing_map_elts equal to the
824  * user-specified size of 2 ** map_bits (internally maintained as
825  * 'max_elts' in struct tracing_map).  Before using, the map fields
826  * should be added to the map with tracing_map_add_sum_field() and
827  * tracing_map_add_key_field().  tracing_map_init() should then be
828  * called to allocate the array of tracing_map_elts, in order to avoid
829  * allocating anything in the map insertion path.  The user-specified
830  * map size reflects the max number of elements requested by the user
831  * - internally we double that in order to keep the table sparse and
832  * keep collisions manageable.
833  *
834  * See tracing_map.h for a description of tracing_map_ops.
835  *
836  * Return: the tracing_map pointer if successful, ERR_PTR if not.
837  */
tracing_map_init(struct tracing_map * map)838 int tracing_map_init(struct tracing_map *map)
839 {
840 	int err;
841 
842 	if (map->n_fields < 2)
843 		return -EINVAL; /* need at least 1 key and 1 val */
844 
845 	err = tracing_map_alloc_elts(map);
846 	if (err)
847 		return err;
848 
849 	tracing_map_clear(map);
850 
851 	return err;
852 }
853 
cmp_entries_dup(const void * A,const void * B)854 static int cmp_entries_dup(const void *A, const void *B)
855 {
856 	const struct tracing_map_sort_entry *a, *b;
857 
858 	a = *(const struct tracing_map_sort_entry **)A;
859 	b = *(const struct tracing_map_sort_entry **)B;
860 
861 	return memcmp(a->key, b->key, a->elt->map->key_size);
862 }
863 
cmp_entries_sum(const void * A,const void * B)864 static int cmp_entries_sum(const void *A, const void *B)
865 {
866 	const struct tracing_map_elt *elt_a, *elt_b;
867 	const struct tracing_map_sort_entry *a, *b;
868 	struct tracing_map_sort_key *sort_key;
869 	struct tracing_map_field *field;
870 	tracing_map_cmp_fn_t cmp_fn;
871 	void *val_a, *val_b;
872 	int ret = 0;
873 
874 	a = *(const struct tracing_map_sort_entry **)A;
875 	b = *(const struct tracing_map_sort_entry **)B;
876 
877 	elt_a = a->elt;
878 	elt_b = b->elt;
879 
880 	sort_key = &elt_a->map->sort_key;
881 
882 	field = &elt_a->fields[sort_key->field_idx];
883 	cmp_fn = field->cmp_fn;
884 
885 	val_a = &elt_a->fields[sort_key->field_idx].sum;
886 	val_b = &elt_b->fields[sort_key->field_idx].sum;
887 
888 	ret = cmp_fn(val_a, val_b);
889 	if (sort_key->descending)
890 		ret = -ret;
891 
892 	return ret;
893 }
894 
cmp_entries_key(const void * A,const void * B)895 static int cmp_entries_key(const void *A, const void *B)
896 {
897 	const struct tracing_map_elt *elt_a, *elt_b;
898 	const struct tracing_map_sort_entry *a, *b;
899 	struct tracing_map_sort_key *sort_key;
900 	struct tracing_map_field *field;
901 	tracing_map_cmp_fn_t cmp_fn;
902 	void *val_a, *val_b;
903 	int ret = 0;
904 
905 	a = *(const struct tracing_map_sort_entry **)A;
906 	b = *(const struct tracing_map_sort_entry **)B;
907 
908 	elt_a = a->elt;
909 	elt_b = b->elt;
910 
911 	sort_key = &elt_a->map->sort_key;
912 
913 	field = &elt_a->fields[sort_key->field_idx];
914 
915 	cmp_fn = field->cmp_fn;
916 
917 	val_a = elt_a->key + field->offset;
918 	val_b = elt_b->key + field->offset;
919 
920 	ret = cmp_fn(val_a, val_b);
921 	if (sort_key->descending)
922 		ret = -ret;
923 
924 	return ret;
925 }
926 
destroy_sort_entry(struct tracing_map_sort_entry * entry)927 static void destroy_sort_entry(struct tracing_map_sort_entry *entry)
928 {
929 	if (!entry)
930 		return;
931 
932 	if (entry->elt_copied)
933 		tracing_map_elt_free(entry->elt);
934 
935 	kfree(entry);
936 }
937 
938 /**
939  * tracing_map_destroy_sort_entries - Destroy an array of sort entries
940  * @entries: The entries to destroy
941  * @n_entries: The number of entries in the array
942  *
943  * Destroy the elements returned by a tracing_map_sort_entries() call.
944  */
tracing_map_destroy_sort_entries(struct tracing_map_sort_entry ** entries,unsigned int n_entries)945 void tracing_map_destroy_sort_entries(struct tracing_map_sort_entry **entries,
946 				      unsigned int n_entries)
947 {
948 	unsigned int i;
949 
950 	for (i = 0; i < n_entries; i++)
951 		destroy_sort_entry(entries[i]);
952 
953 	vfree(entries);
954 }
955 
956 static struct tracing_map_sort_entry *
create_sort_entry(void * key,struct tracing_map_elt * elt)957 create_sort_entry(void *key, struct tracing_map_elt *elt)
958 {
959 	struct tracing_map_sort_entry *sort_entry;
960 
961 	sort_entry = kzalloc_obj(*sort_entry);
962 	if (!sort_entry)
963 		return NULL;
964 
965 	sort_entry->key = key;
966 	sort_entry->elt = elt;
967 
968 	return sort_entry;
969 }
970 
detect_dups(struct tracing_map_sort_entry ** sort_entries,int n_entries,unsigned int key_size)971 static void detect_dups(struct tracing_map_sort_entry **sort_entries,
972 		      int n_entries, unsigned int key_size)
973 {
974 	unsigned int total_dups = 0;
975 	int i;
976 	void *key;
977 
978 	if (n_entries < 2)
979 		return;
980 
981 	sort(sort_entries, n_entries, sizeof(struct tracing_map_sort_entry *),
982 	     (int (*)(const void *, const void *))cmp_entries_dup, NULL);
983 
984 	key = sort_entries[0]->key;
985 	for (i = 1; i < n_entries; i++) {
986 		if (!memcmp(sort_entries[i]->key, key, key_size)) {
987 			total_dups++;
988 			continue;
989 		}
990 		key = sort_entries[i]->key;
991 	}
992 
993 	WARN_ONCE(total_dups > 0,
994 		  "Duplicates detected: %d\n", total_dups);
995 }
996 
is_key(struct tracing_map * map,unsigned int field_idx)997 static bool is_key(struct tracing_map *map, unsigned int field_idx)
998 {
999 	unsigned int i;
1000 
1001 	for (i = 0; i < map->n_keys; i++)
1002 		if (map->key_idx[i] == field_idx)
1003 			return true;
1004 	return false;
1005 }
1006 
sort_secondary(struct tracing_map * map,const struct tracing_map_sort_entry ** entries,unsigned int n_entries,struct tracing_map_sort_key * primary_key,struct tracing_map_sort_key * secondary_key)1007 static void sort_secondary(struct tracing_map *map,
1008 			   const struct tracing_map_sort_entry **entries,
1009 			   unsigned int n_entries,
1010 			   struct tracing_map_sort_key *primary_key,
1011 			   struct tracing_map_sort_key *secondary_key)
1012 {
1013 	int (*primary_fn)(const void *, const void *);
1014 	int (*secondary_fn)(const void *, const void *);
1015 	unsigned i, start = 0, n_sub = 1;
1016 
1017 	if (is_key(map, primary_key->field_idx))
1018 		primary_fn = cmp_entries_key;
1019 	else
1020 		primary_fn = cmp_entries_sum;
1021 
1022 	if (is_key(map, secondary_key->field_idx))
1023 		secondary_fn = cmp_entries_key;
1024 	else
1025 		secondary_fn = cmp_entries_sum;
1026 
1027 	for (i = 0; i < n_entries - 1; i++) {
1028 		const struct tracing_map_sort_entry **a = &entries[i];
1029 		const struct tracing_map_sort_entry **b = &entries[i + 1];
1030 
1031 		if (primary_fn(a, b) == 0) {
1032 			n_sub++;
1033 			if (i < n_entries - 2)
1034 				continue;
1035 		}
1036 
1037 		if (n_sub < 2) {
1038 			start = i + 1;
1039 			n_sub = 1;
1040 			continue;
1041 		}
1042 
1043 		set_sort_key(map, secondary_key);
1044 		sort(&entries[start], n_sub,
1045 		     sizeof(struct tracing_map_sort_entry *),
1046 		     (int (*)(const void *, const void *))secondary_fn, NULL);
1047 		set_sort_key(map, primary_key);
1048 
1049 		start = i + 1;
1050 		n_sub = 1;
1051 	}
1052 }
1053 
1054 /**
1055  * tracing_map_sort_entries - Sort the current set of tracing_map_elts in a map
1056  * @map: The tracing_map
1057  * @sort_keys: The sort key to use for sorting
1058  * @n_sort_keys: hitcount, always have at least one
1059  * @sort_entries: outval: pointer to allocated and sorted array of entries
1060  *
1061  * tracing_map_sort_entries() sorts the current set of entries in the
1062  * map and returns the list of tracing_map_sort_entries containing
1063  * them to the client in the sort_entries param.  The client can
1064  * access the struct tracing_map_elt element of interest directly as
1065  * the 'elt' field of a returned struct tracing_map_sort_entry object.
1066  *
1067  * The sort_key has only two fields: idx and descending.  'idx' refers
1068  * to the index of the field added via tracing_map_add_sum_field() or
1069  * tracing_map_add_key_field() when the tracing_map was initialized.
1070  * 'descending' is a flag that if set reverses the sort order, which
1071  * by default is ascending.
1072  *
1073  * The client should not hold on to the returned array but should use
1074  * it and call tracing_map_destroy_sort_entries() when done.
1075  *
1076  * Return: the number of sort_entries in the struct tracing_map_sort_entry
1077  * array, negative on error
1078  */
tracing_map_sort_entries(struct tracing_map * map,struct tracing_map_sort_key * sort_keys,unsigned int n_sort_keys,struct tracing_map_sort_entry *** sort_entries)1079 int tracing_map_sort_entries(struct tracing_map *map,
1080 			     struct tracing_map_sort_key *sort_keys,
1081 			     unsigned int n_sort_keys,
1082 			     struct tracing_map_sort_entry ***sort_entries)
1083 {
1084 	int (*cmp_entries_fn)(const void *, const void *);
1085 	struct tracing_map_sort_entry *sort_entry, **entries;
1086 	int i, n_entries, ret;
1087 
1088 	entries = vmalloc_array(map->max_elts, sizeof(sort_entry));
1089 	if (!entries)
1090 		return -ENOMEM;
1091 
1092 	for (i = 0, n_entries = 0; i < map->map_size; i++) {
1093 		struct tracing_map_entry *entry;
1094 
1095 		entry = TRACING_MAP_ENTRY(map->map, i);
1096 
1097 		if (!entry->key || !entry->val)
1098 			continue;
1099 
1100 		entries[n_entries] = create_sort_entry(entry->val->key,
1101 						       entry->val);
1102 		if (!entries[n_entries++]) {
1103 			ret = -ENOMEM;
1104 			goto free;
1105 		}
1106 	}
1107 
1108 	if (n_entries == 0) {
1109 		ret = 0;
1110 		goto free;
1111 	}
1112 
1113 	if (n_entries == 1) {
1114 		*sort_entries = entries;
1115 		return 1;
1116 	}
1117 
1118 	detect_dups(entries, n_entries, map->key_size);
1119 
1120 	if (is_key(map, sort_keys[0].field_idx))
1121 		cmp_entries_fn = cmp_entries_key;
1122 	else
1123 		cmp_entries_fn = cmp_entries_sum;
1124 
1125 	set_sort_key(map, &sort_keys[0]);
1126 
1127 	sort(entries, n_entries, sizeof(struct tracing_map_sort_entry *),
1128 	     (int (*)(const void *, const void *))cmp_entries_fn, NULL);
1129 
1130 	if (n_sort_keys > 1)
1131 		sort_secondary(map,
1132 			       (const struct tracing_map_sort_entry **)entries,
1133 			       n_entries,
1134 			       &sort_keys[0],
1135 			       &sort_keys[1]);
1136 
1137 	*sort_entries = entries;
1138 
1139 	return n_entries;
1140  free:
1141 	tracing_map_destroy_sort_entries(entries, n_entries);
1142 
1143 	return ret;
1144 }
1145