xref: /linux/kernel/trace/tracing_map.c (revision 817e148935dd76ce39bf468f51308ec77de87033)
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  */
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  */
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  */
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  */
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  */
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  */
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 
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 
136 int tracing_map_cmp_none(void *val_a, void *val_b)
137 {
138 	return 0;
139 }
140 
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 
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 
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  */
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  */
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  */
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 
287 static void tracing_map_array_clear(struct tracing_map_array *a)
288 {
289 	unsigned int i;
290 
291 	for (i = 0; i < a->n_pages; i++)
292 		memset(a->pages[i], 0, PAGE_SIZE);
293 }
294 
295 static void tracing_map_array_free(struct tracing_map_array *a)
296 {
297 	unsigned int i;
298 
299 	if (!a)
300 		return;
301 
302 	for (i = 0; i < a->n_pages; i++) {
303 		if (!a->pages[i])
304 			break;
305 		kmemleak_free(a->pages[i]);
306 		free_page((unsigned long)a->pages[i]);
307 	}
308 
309 	kfree(a);
310 }
311 
312 static struct tracing_map_array *tracing_map_array_alloc(unsigned int n_elts,
313 						  unsigned int entry_size)
314 {
315 	struct tracing_map_array *a;
316 	unsigned int entry_size_shift;
317 	unsigned int entries_per_page;
318 	unsigned int n_pages;
319 	unsigned int i;
320 
321 	entry_size_shift = fls(roundup_pow_of_two(entry_size) - 1);
322 	entries_per_page = PAGE_SIZE / (1 << entry_size_shift);
323 	n_pages = max(1, n_elts / entries_per_page);
324 
325 	a = kzalloc_flex(*a, pages, n_pages);
326 	if (!a)
327 		return NULL;
328 
329 	a->entry_size_shift = entry_size_shift;
330 	a->entries_per_page = entries_per_page;
331 	a->n_pages = n_pages;
332 	a->entry_shift = fls(a->entries_per_page) - 1;
333 	a->entry_mask = (1 << a->entry_shift) - 1;
334 
335 	for (i = 0; i < a->n_pages; i++) {
336 		a->pages[i] = (void *)get_zeroed_page(GFP_KERNEL);
337 		if (!a->pages[i])
338 			goto free;
339 		kmemleak_alloc(a->pages[i], PAGE_SIZE, 1, GFP_KERNEL);
340 	}
341  out:
342 	return a;
343  free:
344 	tracing_map_array_free(a);
345 	a = NULL;
346 
347 	goto out;
348 }
349 
350 static void tracing_map_elt_clear(struct tracing_map_elt *elt)
351 {
352 	unsigned i;
353 
354 	for (i = 0; i < elt->map->n_fields; i++)
355 		if (elt->fields[i].cmp_fn == tracing_map_cmp_atomic64)
356 			atomic64_set(&elt->fields[i].sum, 0);
357 
358 	for (i = 0; i < elt->map->n_vars; i++) {
359 		atomic64_set(&elt->vars[i], 0);
360 		elt->var_set[i] = false;
361 	}
362 
363 	if (elt->map->ops && elt->map->ops->elt_clear)
364 		elt->map->ops->elt_clear(elt);
365 }
366 
367 static void tracing_map_elt_init_fields(struct tracing_map_elt *elt)
368 {
369 	unsigned int i;
370 
371 	tracing_map_elt_clear(elt);
372 
373 	for (i = 0; i < elt->map->n_fields; i++) {
374 		elt->fields[i].cmp_fn = elt->map->fields[i].cmp_fn;
375 
376 		if (elt->fields[i].cmp_fn != tracing_map_cmp_atomic64)
377 			elt->fields[i].offset = elt->map->fields[i].offset;
378 	}
379 }
380 
381 static void __tracing_map_elt_free(struct tracing_map_elt *elt)
382 {
383 	if (!elt)
384 		return;
385 
386 	kfree(elt->fields);
387 	kfree(elt->vars);
388 	kfree(elt->var_set);
389 	kfree(elt->key);
390 	kfree(elt);
391 }
392 
393 static void tracing_map_elt_free(struct tracing_map_elt *elt)
394 {
395 	if (!elt)
396 		return;
397 
398 	/* Only objects initialized with alloc_elt() should be passed to free_elt().*/
399 	if (elt->map->ops && elt->map->ops->elt_free)
400 		elt->map->ops->elt_free(elt);
401 	__tracing_map_elt_free(elt);
402 }
403 
404 static struct tracing_map_elt *tracing_map_elt_alloc(struct tracing_map *map)
405 {
406 	struct tracing_map_elt *elt;
407 	int err = 0;
408 
409 	elt = kzalloc_obj(*elt);
410 	if (!elt)
411 		return ERR_PTR(-ENOMEM);
412 
413 	elt->map = map;
414 
415 	elt->key = kzalloc(map->key_size, GFP_KERNEL);
416 	if (!elt->key) {
417 		err = -ENOMEM;
418 		goto free;
419 	}
420 
421 	elt->fields = kzalloc_objs(*elt->fields, map->n_fields);
422 	if (!elt->fields) {
423 		err = -ENOMEM;
424 		goto free;
425 	}
426 
427 	elt->vars = kzalloc_objs(*elt->vars, map->n_vars);
428 	if (!elt->vars) {
429 		err = -ENOMEM;
430 		goto free;
431 	}
432 
433 	elt->var_set = kzalloc_objs(*elt->var_set, map->n_vars);
434 	if (!elt->var_set) {
435 		err = -ENOMEM;
436 		goto free;
437 	}
438 
439 	tracing_map_elt_init_fields(elt);
440 
441 	if (map->ops && map->ops->elt_alloc) {
442 		err = map->ops->elt_alloc(elt);
443 		if (err)
444 			goto free;
445 	}
446 	return elt;
447  free:
448 	__tracing_map_elt_free(elt);
449 
450 	return ERR_PTR(err);
451 }
452 
453 static struct tracing_map_elt *get_free_elt(struct tracing_map *map)
454 {
455 	struct tracing_map_elt *elt = NULL;
456 	int idx;
457 
458 	idx = atomic_fetch_add_unless(&map->next_elt, 1, map->max_elts);
459 	if (idx < map->max_elts) {
460 		elt = *(TRACING_MAP_ELT(map->elts, idx));
461 		if (map->ops && map->ops->elt_init)
462 			map->ops->elt_init(elt);
463 	}
464 
465 	return elt;
466 }
467 
468 static void tracing_map_free_elts(struct tracing_map *map)
469 {
470 	unsigned int i;
471 
472 	if (!map->elts)
473 		return;
474 
475 	for (i = 0; i < map->max_elts; i++) {
476 		tracing_map_elt_free(*(TRACING_MAP_ELT(map->elts, i)));
477 		*(TRACING_MAP_ELT(map->elts, i)) = NULL;
478 	}
479 
480 	tracing_map_array_free(map->elts);
481 	map->elts = NULL;
482 }
483 
484 static int tracing_map_alloc_elts(struct tracing_map *map)
485 {
486 	unsigned int i;
487 
488 	map->elts = tracing_map_array_alloc(map->max_elts,
489 					    sizeof(struct tracing_map_elt *));
490 	if (!map->elts)
491 		return -ENOMEM;
492 
493 	for (i = 0; i < map->max_elts; i++) {
494 		*(TRACING_MAP_ELT(map->elts, i)) = tracing_map_elt_alloc(map);
495 		if (IS_ERR(*(TRACING_MAP_ELT(map->elts, i)))) {
496 			*(TRACING_MAP_ELT(map->elts, i)) = NULL;
497 			tracing_map_free_elts(map);
498 
499 			return -ENOMEM;
500 		}
501 	}
502 
503 	return 0;
504 }
505 
506 static inline bool keys_match(void *key, void *test_key, unsigned key_size)
507 {
508 	bool match = true;
509 
510 	if (memcmp(key, test_key, key_size))
511 		match = false;
512 
513 	return match;
514 }
515 
516 static inline struct tracing_map_elt *
517 __tracing_map_insert(struct tracing_map *map, void *key, bool lookup_only)
518 {
519 	u32 idx, key_hash, test_key;
520 	int dup_try = 0;
521 	struct tracing_map_entry *entry;
522 	struct tracing_map_elt *val;
523 
524 	key_hash = jhash(key, map->key_size, 0);
525 	if (key_hash == 0)
526 		key_hash = 1;
527 	idx = key_hash >> (32 - (map->map_bits + 1));
528 
529 	while (1) {
530 		idx &= (map->map_size - 1);
531 		entry = TRACING_MAP_ENTRY(map->map, idx);
532 		test_key = entry->key;
533 
534 		if (test_key && test_key == key_hash) {
535 			val = READ_ONCE(entry->val);
536 			if (val &&
537 			    keys_match(key, val->key, map->key_size)) {
538 				if (!lookup_only)
539 					atomic64_inc(&map->hits);
540 				return val;
541 			} else if (unlikely(!val)) {
542 				/*
543 				 * The key is present. But, val (pointer to elt
544 				 * struct) is still NULL. which means some other
545 				 * thread is in the process of inserting an
546 				 * element.
547 				 *
548 				 * On top of that, it's key_hash is same as the
549 				 * one being inserted right now. So, it's
550 				 * possible that the element has the same
551 				 * key as well.
552 				 */
553 
554 				dup_try++;
555 				if (dup_try > map->map_size) {
556 					atomic64_inc(&map->drops);
557 					break;
558 				}
559 				continue;
560 			}
561 		}
562 
563 		if (!test_key) {
564 			if (lookup_only)
565 				break;
566 
567 			if (!cmpxchg(&entry->key, 0, key_hash)) {
568 				struct tracing_map_elt *elt;
569 
570 				elt = get_free_elt(map);
571 				if (!elt) {
572 					atomic64_inc(&map->drops);
573 					entry->key = 0;
574 					break;
575 				}
576 
577 				memcpy(elt->key, key, map->key_size);
578 				/*
579 				 * Ensure the initialization is visible and
580 				 * publish the elt.
581 				 */
582 				smp_wmb();
583 				WRITE_ONCE(entry->val, elt);
584 				atomic64_inc(&map->hits);
585 
586 				return entry->val;
587 			} else {
588 				/*
589 				 * cmpxchg() failed. Loop around once
590 				 * more to check what key was inserted.
591 				 */
592 				dup_try++;
593 				continue;
594 			}
595 		}
596 
597 		idx++;
598 	}
599 
600 	return NULL;
601 }
602 
603 /**
604  * tracing_map_insert - Insert key and/or retrieve val from a tracing_map
605  * @map: The tracing_map to insert into
606  * @key: The key to insert
607  *
608  * Inserts a key into a tracing_map and creates and returns a new
609  * tracing_map_elt for it, or if the key has already been inserted by
610  * a previous call, returns the tracing_map_elt already associated
611  * with it.  When the map was created, the number of elements to be
612  * allocated for the map was specified (internally maintained as
613  * 'max_elts' in struct tracing_map), and that number of
614  * tracing_map_elts was created by tracing_map_init().  This is the
615  * pre-allocated pool of tracing_map_elts that tracing_map_insert()
616  * will allocate from when adding new keys.  Once that pool is
617  * exhausted, tracing_map_insert() is useless and will return NULL to
618  * signal that state.  There are two user-visible tracing_map
619  * variables, 'hits' and 'drops', which are updated by this function.
620  * Every time an element is either successfully inserted or retrieved,
621  * the 'hits' value is incremented.  Every time an element insertion
622  * fails, the 'drops' value is incremented.
623  *
624  * This is a lock-free tracing map insertion function implementing a
625  * modified form of Cliff Click's basic insertion algorithm.  It
626  * requires the table size be a power of two.  To prevent any
627  * possibility of an infinite loop we always make the internal table
628  * size double the size of the requested table size (max_elts * 2).
629  * Likewise, we never reuse a slot or resize or delete elements - when
630  * we've reached max_elts entries, we simply return NULL once we've
631  * run out of entries.  Readers can at any point in time traverse the
632  * tracing map and safely access the key/val pairs.
633  *
634  * Return: the tracing_map_elt pointer val associated with the key.
635  * If this was a newly inserted key, the val will be a newly allocated
636  * and associated tracing_map_elt pointer val.  If the key wasn't
637  * found and the pool of tracing_map_elts has been exhausted, NULL is
638  * returned and no further insertions will succeed.
639  */
640 struct tracing_map_elt *tracing_map_insert(struct tracing_map *map, void *key)
641 {
642 	return __tracing_map_insert(map, key, false);
643 }
644 
645 /**
646  * tracing_map_lookup - Retrieve val from a tracing_map
647  * @map: The tracing_map to perform the lookup on
648  * @key: The key to look up
649  *
650  * Looks up key in tracing_map and if found returns the matching
651  * tracing_map_elt.  This is a lock-free lookup; see
652  * tracing_map_insert() for details on tracing_map and how it works.
653  * Every time an element is retrieved, the 'hits' value is
654  * incremented.  There is one user-visible tracing_map variable,
655  * 'hits', which is updated by this function.  Every time an element
656  * is successfully retrieved, the 'hits' value is incremented.  The
657  * 'drops' value is never updated by this function.
658  *
659  * Return: the tracing_map_elt pointer val associated with the key.
660  * If the key wasn't found, NULL is returned.
661  */
662 struct tracing_map_elt *tracing_map_lookup(struct tracing_map *map, void *key)
663 {
664 	return __tracing_map_insert(map, key, true);
665 }
666 
667 /**
668  * tracing_map_destroy - Destroy a tracing_map
669  * @map: The tracing_map to destroy
670  *
671  * Frees a tracing_map along with its associated array of
672  * tracing_map_elts.
673  *
674  * Callers should make sure there are no readers or writers actively
675  * reading or inserting into the map before calling this.
676  */
677 void tracing_map_destroy(struct tracing_map *map)
678 {
679 	if (!map)
680 		return;
681 
682 	tracing_map_free_elts(map);
683 
684 	tracing_map_array_free(map->map);
685 	kfree(map);
686 }
687 
688 /**
689  * tracing_map_clear - Clear a tracing_map
690  * @map: The tracing_map to clear
691  *
692  * Resets the tracing map to a cleared or initial state.  The
693  * tracing_map_elts are all cleared, and the array of struct
694  * tracing_map_entry is reset to an initialized state.
695  *
696  * Callers should make sure there are no writers actively inserting
697  * into the map before calling this.
698  */
699 void tracing_map_clear(struct tracing_map *map)
700 {
701 	unsigned int i;
702 
703 	atomic_set(&map->next_elt, 0);
704 	atomic64_set(&map->hits, 0);
705 	atomic64_set(&map->drops, 0);
706 
707 	tracing_map_array_clear(map->map);
708 
709 	for (i = 0; i < map->max_elts; i++)
710 		tracing_map_elt_clear(*(TRACING_MAP_ELT(map->elts, i)));
711 }
712 
713 static void set_sort_key(struct tracing_map *map,
714 			 struct tracing_map_sort_key *sort_key)
715 {
716 	map->sort_key = *sort_key;
717 }
718 
719 /**
720  * tracing_map_create - Create a lock-free map and element pool
721  * @map_bits: The size of the map (2 ** map_bits)
722  * @key_size: The size of the key for the map in bytes
723  * @ops: Optional client-defined tracing_map_ops instance
724  * @private_data: Client data associated with the map
725  *
726  * Creates and sets up a map to contain 2 ** map_bits number of
727  * elements (internally maintained as 'max_elts' in struct
728  * tracing_map).  Before using, map fields should be added to the map
729  * with tracing_map_add_sum_field() and tracing_map_add_key_field().
730  * tracing_map_init() should then be called to allocate the array of
731  * tracing_map_elts, in order to avoid allocating anything in the map
732  * insertion path.  The user-specified map size reflects the maximum
733  * number of elements that can be contained in the table requested by
734  * the user - internally we double that in order to keep the table
735  * sparse and keep collisions manageable.
736  *
737  * A tracing_map is a special-purpose map designed to aggregate or
738  * 'sum' one or more values associated with a specific object of type
739  * tracing_map_elt, which is attached by the map to a given key.
740  *
741  * tracing_map_create() sets up the map itself, and provides
742  * operations for inserting tracing_map_elts, but doesn't allocate the
743  * tracing_map_elts themselves, or provide a means for describing the
744  * keys or sums associated with the tracing_map_elts.  All
745  * tracing_map_elts for a given map have the same set of sums and
746  * keys, which are defined by the client using the functions
747  * tracing_map_add_key_field() and tracing_map_add_sum_field().  Once
748  * the fields are defined, the pool of elements allocated for the map
749  * can be created, which occurs when the client code calls
750  * tracing_map_init().
751  *
752  * When tracing_map_init() returns, tracing_map_elt elements can be
753  * inserted into the map using tracing_map_insert().  When called,
754  * tracing_map_insert() grabs a free tracing_map_elt from the pool, or
755  * finds an existing match in the map and in either case returns it.
756  * The client can then use tracing_map_update_sum() and
757  * tracing_map_read_sum() to update or read a given sum field for the
758  * tracing_map_elt.
759  *
760  * The client can at any point retrieve and traverse the current set
761  * of inserted tracing_map_elts in a tracing_map, via
762  * tracing_map_sort_entries().  Sorting can be done on any field,
763  * including keys.
764  *
765  * See tracing_map.h for a description of tracing_map_ops.
766  *
767  * Return: the tracing_map pointer if successful, ERR_PTR if not.
768  */
769 struct tracing_map *tracing_map_create(unsigned int map_bits,
770 				       unsigned int key_size,
771 				       const struct tracing_map_ops *ops,
772 				       void *private_data)
773 {
774 	struct tracing_map *map;
775 	unsigned int i;
776 
777 	if (map_bits < TRACING_MAP_BITS_MIN ||
778 	    map_bits > TRACING_MAP_BITS_MAX)
779 		return ERR_PTR(-EINVAL);
780 
781 	map = kzalloc_obj(*map);
782 	if (!map)
783 		return ERR_PTR(-ENOMEM);
784 
785 	map->map_bits = map_bits;
786 	map->max_elts = (1 << map_bits);
787 	atomic_set(&map->next_elt, 0);
788 
789 	map->map_size = (1 << (map_bits + 1));
790 	map->ops = ops;
791 
792 	map->private_data = private_data;
793 
794 	map->map = tracing_map_array_alloc(map->map_size,
795 					   sizeof(struct tracing_map_entry));
796 	if (!map->map)
797 		goto free;
798 
799 	map->key_size = key_size;
800 	for (i = 0; i < TRACING_MAP_KEYS_MAX; i++)
801 		map->key_idx[i] = -1;
802  out:
803 	return map;
804  free:
805 	tracing_map_destroy(map);
806 	map = ERR_PTR(-ENOMEM);
807 
808 	goto out;
809 }
810 
811 /**
812  * tracing_map_init - Allocate and clear a map's tracing_map_elts
813  * @map: The tracing_map to initialize
814  *
815  * Allocates a clears a pool of tracing_map_elts equal to the
816  * user-specified size of 2 ** map_bits (internally maintained as
817  * 'max_elts' in struct tracing_map).  Before using, the map fields
818  * should be added to the map with tracing_map_add_sum_field() and
819  * tracing_map_add_key_field().  tracing_map_init() should then be
820  * called to allocate the array of tracing_map_elts, in order to avoid
821  * allocating anything in the map insertion path.  The user-specified
822  * map size reflects the max number of elements requested by the user
823  * - internally we double that in order to keep the table sparse and
824  * keep collisions manageable.
825  *
826  * See tracing_map.h for a description of tracing_map_ops.
827  *
828  * Return: the tracing_map pointer if successful, ERR_PTR if not.
829  */
830 int tracing_map_init(struct tracing_map *map)
831 {
832 	int err;
833 
834 	if (map->n_fields < 2)
835 		return -EINVAL; /* need at least 1 key and 1 val */
836 
837 	err = tracing_map_alloc_elts(map);
838 	if (err)
839 		return err;
840 
841 	tracing_map_clear(map);
842 
843 	return err;
844 }
845 
846 static int cmp_entries_dup(const void *A, const void *B)
847 {
848 	const struct tracing_map_sort_entry *a, *b;
849 
850 	a = *(const struct tracing_map_sort_entry **)A;
851 	b = *(const struct tracing_map_sort_entry **)B;
852 
853 	return memcmp(a->key, b->key, a->elt->map->key_size);
854 }
855 
856 static int cmp_entries_sum(const void *A, const void *B)
857 {
858 	const struct tracing_map_elt *elt_a, *elt_b;
859 	const struct tracing_map_sort_entry *a, *b;
860 	struct tracing_map_sort_key *sort_key;
861 	struct tracing_map_field *field;
862 	tracing_map_cmp_fn_t cmp_fn;
863 	void *val_a, *val_b;
864 	int ret = 0;
865 
866 	a = *(const struct tracing_map_sort_entry **)A;
867 	b = *(const struct tracing_map_sort_entry **)B;
868 
869 	elt_a = a->elt;
870 	elt_b = b->elt;
871 
872 	sort_key = &elt_a->map->sort_key;
873 
874 	field = &elt_a->fields[sort_key->field_idx];
875 	cmp_fn = field->cmp_fn;
876 
877 	val_a = &elt_a->fields[sort_key->field_idx].sum;
878 	val_b = &elt_b->fields[sort_key->field_idx].sum;
879 
880 	ret = cmp_fn(val_a, val_b);
881 	if (sort_key->descending)
882 		ret = -ret;
883 
884 	return ret;
885 }
886 
887 static int cmp_entries_key(const void *A, const void *B)
888 {
889 	const struct tracing_map_elt *elt_a, *elt_b;
890 	const struct tracing_map_sort_entry *a, *b;
891 	struct tracing_map_sort_key *sort_key;
892 	struct tracing_map_field *field;
893 	tracing_map_cmp_fn_t cmp_fn;
894 	void *val_a, *val_b;
895 	int ret = 0;
896 
897 	a = *(const struct tracing_map_sort_entry **)A;
898 	b = *(const struct tracing_map_sort_entry **)B;
899 
900 	elt_a = a->elt;
901 	elt_b = b->elt;
902 
903 	sort_key = &elt_a->map->sort_key;
904 
905 	field = &elt_a->fields[sort_key->field_idx];
906 
907 	cmp_fn = field->cmp_fn;
908 
909 	val_a = elt_a->key + field->offset;
910 	val_b = elt_b->key + field->offset;
911 
912 	ret = cmp_fn(val_a, val_b);
913 	if (sort_key->descending)
914 		ret = -ret;
915 
916 	return ret;
917 }
918 
919 static void destroy_sort_entry(struct tracing_map_sort_entry *entry)
920 {
921 	if (!entry)
922 		return;
923 
924 	if (entry->elt_copied)
925 		tracing_map_elt_free(entry->elt);
926 
927 	kfree(entry);
928 }
929 
930 /**
931  * tracing_map_destroy_sort_entries - Destroy an array of sort entries
932  * @entries: The entries to destroy
933  * @n_entries: The number of entries in the array
934  *
935  * Destroy the elements returned by a tracing_map_sort_entries() call.
936  */
937 void tracing_map_destroy_sort_entries(struct tracing_map_sort_entry **entries,
938 				      unsigned int n_entries)
939 {
940 	unsigned int i;
941 
942 	for (i = 0; i < n_entries; i++)
943 		destroy_sort_entry(entries[i]);
944 
945 	vfree(entries);
946 }
947 
948 static struct tracing_map_sort_entry *
949 create_sort_entry(void *key, struct tracing_map_elt *elt)
950 {
951 	struct tracing_map_sort_entry *sort_entry;
952 
953 	sort_entry = kzalloc_obj(*sort_entry);
954 	if (!sort_entry)
955 		return NULL;
956 
957 	sort_entry->key = key;
958 	sort_entry->elt = elt;
959 
960 	return sort_entry;
961 }
962 
963 static void detect_dups(struct tracing_map_sort_entry **sort_entries,
964 		      int n_entries, unsigned int key_size)
965 {
966 	unsigned int total_dups = 0;
967 	int i;
968 	void *key;
969 
970 	if (n_entries < 2)
971 		return;
972 
973 	sort(sort_entries, n_entries, sizeof(struct tracing_map_sort_entry *),
974 	     (int (*)(const void *, const void *))cmp_entries_dup, NULL);
975 
976 	key = sort_entries[0]->key;
977 	for (i = 1; i < n_entries; i++) {
978 		if (!memcmp(sort_entries[i]->key, key, key_size)) {
979 			total_dups++;
980 			continue;
981 		}
982 		key = sort_entries[i]->key;
983 	}
984 
985 	WARN_ONCE(total_dups > 0,
986 		  "Duplicates detected: %d\n", total_dups);
987 }
988 
989 static bool is_key(struct tracing_map *map, unsigned int field_idx)
990 {
991 	unsigned int i;
992 
993 	for (i = 0; i < map->n_keys; i++)
994 		if (map->key_idx[i] == field_idx)
995 			return true;
996 	return false;
997 }
998 
999 static void sort_secondary(struct tracing_map *map,
1000 			   const struct tracing_map_sort_entry **entries,
1001 			   unsigned int n_entries,
1002 			   struct tracing_map_sort_key *primary_key,
1003 			   struct tracing_map_sort_key *secondary_key)
1004 {
1005 	int (*primary_fn)(const void *, const void *);
1006 	int (*secondary_fn)(const void *, const void *);
1007 	unsigned i, start = 0, n_sub = 1;
1008 
1009 	if (is_key(map, primary_key->field_idx))
1010 		primary_fn = cmp_entries_key;
1011 	else
1012 		primary_fn = cmp_entries_sum;
1013 
1014 	if (is_key(map, secondary_key->field_idx))
1015 		secondary_fn = cmp_entries_key;
1016 	else
1017 		secondary_fn = cmp_entries_sum;
1018 
1019 	for (i = 0; i < n_entries - 1; i++) {
1020 		const struct tracing_map_sort_entry **a = &entries[i];
1021 		const struct tracing_map_sort_entry **b = &entries[i + 1];
1022 
1023 		if (primary_fn(a, b) == 0) {
1024 			n_sub++;
1025 			if (i < n_entries - 2)
1026 				continue;
1027 		}
1028 
1029 		if (n_sub < 2) {
1030 			start = i + 1;
1031 			n_sub = 1;
1032 			continue;
1033 		}
1034 
1035 		set_sort_key(map, secondary_key);
1036 		sort(&entries[start], n_sub,
1037 		     sizeof(struct tracing_map_sort_entry *),
1038 		     (int (*)(const void *, const void *))secondary_fn, NULL);
1039 		set_sort_key(map, primary_key);
1040 
1041 		start = i + 1;
1042 		n_sub = 1;
1043 	}
1044 }
1045 
1046 /**
1047  * tracing_map_sort_entries - Sort the current set of tracing_map_elts in a map
1048  * @map: The tracing_map
1049  * @sort_keys: The sort key to use for sorting
1050  * @n_sort_keys: hitcount, always have at least one
1051  * @sort_entries: outval: pointer to allocated and sorted array of entries
1052  *
1053  * tracing_map_sort_entries() sorts the current set of entries in the
1054  * map and returns the list of tracing_map_sort_entries containing
1055  * them to the client in the sort_entries param.  The client can
1056  * access the struct tracing_map_elt element of interest directly as
1057  * the 'elt' field of a returned struct tracing_map_sort_entry object.
1058  *
1059  * The sort_key has only two fields: idx and descending.  'idx' refers
1060  * to the index of the field added via tracing_map_add_sum_field() or
1061  * tracing_map_add_key_field() when the tracing_map was initialized.
1062  * 'descending' is a flag that if set reverses the sort order, which
1063  * by default is ascending.
1064  *
1065  * The client should not hold on to the returned array but should use
1066  * it and call tracing_map_destroy_sort_entries() when done.
1067  *
1068  * Return: the number of sort_entries in the struct tracing_map_sort_entry
1069  * array, negative on error
1070  */
1071 int tracing_map_sort_entries(struct tracing_map *map,
1072 			     struct tracing_map_sort_key *sort_keys,
1073 			     unsigned int n_sort_keys,
1074 			     struct tracing_map_sort_entry ***sort_entries)
1075 {
1076 	int (*cmp_entries_fn)(const void *, const void *);
1077 	struct tracing_map_sort_entry *sort_entry, **entries;
1078 	int i, n_entries, ret;
1079 
1080 	entries = vmalloc_array(map->max_elts, sizeof(sort_entry));
1081 	if (!entries)
1082 		return -ENOMEM;
1083 
1084 	for (i = 0, n_entries = 0; i < map->map_size; i++) {
1085 		struct tracing_map_entry *entry;
1086 
1087 		entry = TRACING_MAP_ENTRY(map->map, i);
1088 
1089 		if (!entry->key || !entry->val)
1090 			continue;
1091 
1092 		entries[n_entries] = create_sort_entry(entry->val->key,
1093 						       entry->val);
1094 		if (!entries[n_entries++]) {
1095 			ret = -ENOMEM;
1096 			goto free;
1097 		}
1098 	}
1099 
1100 	if (n_entries == 0) {
1101 		ret = 0;
1102 		goto free;
1103 	}
1104 
1105 	if (n_entries == 1) {
1106 		*sort_entries = entries;
1107 		return 1;
1108 	}
1109 
1110 	detect_dups(entries, n_entries, map->key_size);
1111 
1112 	if (is_key(map, sort_keys[0].field_idx))
1113 		cmp_entries_fn = cmp_entries_key;
1114 	else
1115 		cmp_entries_fn = cmp_entries_sum;
1116 
1117 	set_sort_key(map, &sort_keys[0]);
1118 
1119 	sort(entries, n_entries, sizeof(struct tracing_map_sort_entry *),
1120 	     (int (*)(const void *, const void *))cmp_entries_fn, NULL);
1121 
1122 	if (n_sort_keys > 1)
1123 		sort_secondary(map,
1124 			       (const struct tracing_map_sort_entry **)entries,
1125 			       n_entries,
1126 			       &sort_keys[0],
1127 			       &sort_keys[1]);
1128 
1129 	*sort_entries = entries;
1130 
1131 	return n_entries;
1132  free:
1133 	tracing_map_destroy_sort_entries(entries, n_entries);
1134 
1135 	return ret;
1136 }
1137