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