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