GNU Linux-libre 4.19.286-gnu1
[releases.git] / lib / debugobjects.c
1 /*
2  * Generic infrastructure for lifetime debugging of objects.
3  *
4  * Started by Thomas Gleixner
5  *
6  * Copyright (C) 2008, Thomas Gleixner <tglx@linutronix.de>
7  *
8  * For licencing details see kernel-base/COPYING
9  */
10
11 #define pr_fmt(fmt) "ODEBUG: " fmt
12
13 #include <linux/debugobjects.h>
14 #include <linux/interrupt.h>
15 #include <linux/sched.h>
16 #include <linux/sched/task_stack.h>
17 #include <linux/seq_file.h>
18 #include <linux/debugfs.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/kmemleak.h>
22
23 #define ODEBUG_HASH_BITS        14
24 #define ODEBUG_HASH_SIZE        (1 << ODEBUG_HASH_BITS)
25
26 #define ODEBUG_POOL_SIZE        1024
27 #define ODEBUG_POOL_MIN_LEVEL   256
28 #define ODEBUG_POOL_PERCPU_SIZE 64
29
30 #define ODEBUG_CHUNK_SHIFT      PAGE_SHIFT
31 #define ODEBUG_CHUNK_SIZE       (1 << ODEBUG_CHUNK_SHIFT)
32 #define ODEBUG_CHUNK_MASK       (~(ODEBUG_CHUNK_SIZE - 1))
33
34 struct debug_bucket {
35         struct hlist_head       list;
36         raw_spinlock_t          lock;
37 };
38
39 /*
40  * Debug object percpu free list
41  * Access is protected by disabling irq
42  */
43 struct debug_percpu_free {
44         struct hlist_head       free_objs;
45         int                     obj_free;
46 };
47
48 static DEFINE_PER_CPU(struct debug_percpu_free, percpu_obj_pool);
49
50 static struct debug_bucket      obj_hash[ODEBUG_HASH_SIZE];
51
52 static struct debug_obj         obj_static_pool[ODEBUG_POOL_SIZE] __initdata;
53
54 static DEFINE_RAW_SPINLOCK(pool_lock);
55
56 static HLIST_HEAD(obj_pool);
57 static HLIST_HEAD(obj_to_free);
58
59 /*
60  * Because of the presence of percpu free pools, obj_pool_free will
61  * under-count those in the percpu free pools. Similarly, obj_pool_used
62  * will over-count those in the percpu free pools. Adjustments will be
63  * made at debug_stats_show(). Both obj_pool_min_free and obj_pool_max_used
64  * can be off.
65  */
66 static int                      obj_pool_min_free = ODEBUG_POOL_SIZE;
67 static int                      obj_pool_free = ODEBUG_POOL_SIZE;
68 static int                      obj_pool_used;
69 static int                      obj_pool_max_used;
70 /* The number of objs on the global free list */
71 static int                      obj_nr_tofree;
72
73 static int                      debug_objects_maxchain __read_mostly;
74 static int __maybe_unused       debug_objects_maxchecked __read_mostly;
75 static int                      debug_objects_fixups __read_mostly;
76 static int                      debug_objects_warnings __read_mostly;
77 static int                      debug_objects_enabled __read_mostly
78                                 = CONFIG_DEBUG_OBJECTS_ENABLE_DEFAULT;
79 static int                      debug_objects_pool_size __read_mostly
80                                 = ODEBUG_POOL_SIZE;
81 static int                      debug_objects_pool_min_level __read_mostly
82                                 = ODEBUG_POOL_MIN_LEVEL;
83 static struct debug_obj_descr   *descr_test  __read_mostly;
84 static struct kmem_cache        *obj_cache __read_mostly;
85
86 /*
87  * Track numbers of kmem_cache_alloc()/free() calls done.
88  */
89 static int                      debug_objects_allocated;
90 static int                      debug_objects_freed;
91
92 static void free_obj_work(struct work_struct *work);
93 static DECLARE_WORK(debug_obj_work, free_obj_work);
94
95 static int __init enable_object_debug(char *str)
96 {
97         debug_objects_enabled = 1;
98         return 0;
99 }
100
101 static int __init disable_object_debug(char *str)
102 {
103         debug_objects_enabled = 0;
104         return 0;
105 }
106
107 early_param("debug_objects", enable_object_debug);
108 early_param("no_debug_objects", disable_object_debug);
109
110 static const char *obj_states[ODEBUG_STATE_MAX] = {
111         [ODEBUG_STATE_NONE]             = "none",
112         [ODEBUG_STATE_INIT]             = "initialized",
113         [ODEBUG_STATE_INACTIVE]         = "inactive",
114         [ODEBUG_STATE_ACTIVE]           = "active",
115         [ODEBUG_STATE_DESTROYED]        = "destroyed",
116         [ODEBUG_STATE_NOTAVAILABLE]     = "not available",
117 };
118
119 static void fill_pool(void)
120 {
121         gfp_t gfp = GFP_ATOMIC | __GFP_NORETRY | __GFP_NOWARN;
122         struct debug_obj *new, *obj;
123         unsigned long flags;
124
125         if (likely(obj_pool_free >= debug_objects_pool_min_level))
126                 return;
127
128         /*
129          * Reuse objs from the global free list; they will be reinitialized
130          * when allocating.
131          */
132         while (obj_nr_tofree && (obj_pool_free < obj_pool_min_free)) {
133                 raw_spin_lock_irqsave(&pool_lock, flags);
134                 /*
135                  * Recheck with the lock held as the worker thread might have
136                  * won the race and freed the global free list already.
137                  */
138                 if (obj_nr_tofree) {
139                         obj = hlist_entry(obj_to_free.first, typeof(*obj), node);
140                         hlist_del(&obj->node);
141                         obj_nr_tofree--;
142                         hlist_add_head(&obj->node, &obj_pool);
143                         obj_pool_free++;
144                 }
145                 raw_spin_unlock_irqrestore(&pool_lock, flags);
146         }
147
148         if (unlikely(!obj_cache))
149                 return;
150
151         while (obj_pool_free < debug_objects_pool_min_level) {
152
153                 new = kmem_cache_zalloc(obj_cache, gfp);
154                 if (!new)
155                         return;
156
157                 raw_spin_lock_irqsave(&pool_lock, flags);
158                 hlist_add_head(&new->node, &obj_pool);
159                 debug_objects_allocated++;
160                 obj_pool_free++;
161                 raw_spin_unlock_irqrestore(&pool_lock, flags);
162         }
163 }
164
165 /*
166  * Lookup an object in the hash bucket.
167  */
168 static struct debug_obj *lookup_object(void *addr, struct debug_bucket *b)
169 {
170         struct debug_obj *obj;
171         int cnt = 0;
172
173         hlist_for_each_entry(obj, &b->list, node) {
174                 cnt++;
175                 if (obj->object == addr)
176                         return obj;
177         }
178         if (cnt > debug_objects_maxchain)
179                 debug_objects_maxchain = cnt;
180
181         return NULL;
182 }
183
184 /*
185  * Allocate a new object from the hlist
186  */
187 static struct debug_obj *__alloc_object(struct hlist_head *list)
188 {
189         struct debug_obj *obj = NULL;
190
191         if (list->first) {
192                 obj = hlist_entry(list->first, typeof(*obj), node);
193                 hlist_del(&obj->node);
194         }
195
196         return obj;
197 }
198
199 static struct debug_obj *
200 alloc_object(void *addr, struct debug_bucket *b, struct debug_obj_descr *descr)
201 {
202         struct debug_percpu_free *percpu_pool;
203         struct debug_obj *obj;
204
205         if (likely(obj_cache)) {
206                 percpu_pool = this_cpu_ptr(&percpu_obj_pool);
207                 obj = __alloc_object(&percpu_pool->free_objs);
208                 if (obj) {
209                         percpu_pool->obj_free--;
210                         goto init_obj;
211                 }
212         }
213
214         raw_spin_lock(&pool_lock);
215         obj = __alloc_object(&obj_pool);
216         if (obj) {
217                 obj_pool_used++;
218                 if (obj_pool_used > obj_pool_max_used)
219                         obj_pool_max_used = obj_pool_used;
220
221                 obj_pool_free--;
222                 if (obj_pool_free < obj_pool_min_free)
223                         obj_pool_min_free = obj_pool_free;
224         }
225         raw_spin_unlock(&pool_lock);
226
227 init_obj:
228         if (obj) {
229                 obj->object = addr;
230                 obj->descr  = descr;
231                 obj->state  = ODEBUG_STATE_NONE;
232                 obj->astate = 0;
233                 hlist_add_head(&obj->node, &b->list);
234         }
235         return obj;
236 }
237
238 /*
239  * workqueue function to free objects.
240  *
241  * To reduce contention on the global pool_lock, the actual freeing of
242  * debug objects will be delayed if the pool_lock is busy.
243  */
244 static void free_obj_work(struct work_struct *work)
245 {
246         struct hlist_node *tmp;
247         struct debug_obj *obj;
248         unsigned long flags;
249         HLIST_HEAD(tofree);
250
251         if (!raw_spin_trylock_irqsave(&pool_lock, flags))
252                 return;
253
254         /*
255          * The objs on the pool list might be allocated before the work is
256          * run, so recheck if pool list it full or not, if not fill pool
257          * list from the global free list
258          */
259         while (obj_nr_tofree && obj_pool_free < debug_objects_pool_size) {
260                 obj = hlist_entry(obj_to_free.first, typeof(*obj), node);
261                 hlist_del(&obj->node);
262                 hlist_add_head(&obj->node, &obj_pool);
263                 obj_pool_free++;
264                 obj_nr_tofree--;
265         }
266
267         /*
268          * Pool list is already full and there are still objs on the free
269          * list. Move remaining free objs to a temporary list to free the
270          * memory outside the pool_lock held region.
271          */
272         if (obj_nr_tofree) {
273                 hlist_move_list(&obj_to_free, &tofree);
274                 debug_objects_freed += obj_nr_tofree;
275                 obj_nr_tofree = 0;
276         }
277         raw_spin_unlock_irqrestore(&pool_lock, flags);
278
279         hlist_for_each_entry_safe(obj, tmp, &tofree, node) {
280                 hlist_del(&obj->node);
281                 kmem_cache_free(obj_cache, obj);
282         }
283 }
284
285 static bool __free_object(struct debug_obj *obj)
286 {
287         unsigned long flags;
288         bool work;
289         struct debug_percpu_free *percpu_pool;
290
291         local_irq_save(flags);
292         /*
293          * Try to free it into the percpu pool first.
294          */
295         percpu_pool = this_cpu_ptr(&percpu_obj_pool);
296         if (obj_cache && percpu_pool->obj_free < ODEBUG_POOL_PERCPU_SIZE) {
297                 hlist_add_head(&obj->node, &percpu_pool->free_objs);
298                 percpu_pool->obj_free++;
299                 local_irq_restore(flags);
300                 return false;
301         }
302
303         raw_spin_lock(&pool_lock);
304         work = (obj_pool_free > debug_objects_pool_size) && obj_cache;
305         obj_pool_used--;
306
307         if (work) {
308                 obj_nr_tofree++;
309                 hlist_add_head(&obj->node, &obj_to_free);
310         } else {
311                 obj_pool_free++;
312                 hlist_add_head(&obj->node, &obj_pool);
313         }
314         raw_spin_unlock(&pool_lock);
315         local_irq_restore(flags);
316         return work;
317 }
318
319 /*
320  * Put the object back into the pool and schedule work to free objects
321  * if necessary.
322  */
323 static void free_object(struct debug_obj *obj)
324 {
325         if (__free_object(obj))
326                 schedule_work(&debug_obj_work);
327 }
328
329 /*
330  * We run out of memory. That means we probably have tons of objects
331  * allocated.
332  */
333 static void debug_objects_oom(void)
334 {
335         struct debug_bucket *db = obj_hash;
336         struct hlist_node *tmp;
337         HLIST_HEAD(freelist);
338         struct debug_obj *obj;
339         unsigned long flags;
340         int i;
341
342         pr_warn("Out of memory. ODEBUG disabled\n");
343
344         for (i = 0; i < ODEBUG_HASH_SIZE; i++, db++) {
345                 raw_spin_lock_irqsave(&db->lock, flags);
346                 hlist_move_list(&db->list, &freelist);
347                 raw_spin_unlock_irqrestore(&db->lock, flags);
348
349                 /* Now free them */
350                 hlist_for_each_entry_safe(obj, tmp, &freelist, node) {
351                         hlist_del(&obj->node);
352                         free_object(obj);
353                 }
354         }
355 }
356
357 /*
358  * We use the pfn of the address for the hash. That way we can check
359  * for freed objects simply by checking the affected bucket.
360  */
361 static struct debug_bucket *get_bucket(unsigned long addr)
362 {
363         unsigned long hash;
364
365         hash = hash_long((addr >> ODEBUG_CHUNK_SHIFT), ODEBUG_HASH_BITS);
366         return &obj_hash[hash];
367 }
368
369 static void debug_print_object(struct debug_obj *obj, char *msg)
370 {
371         struct debug_obj_descr *descr = obj->descr;
372         static int limit;
373
374         if (limit < 5 && descr != descr_test) {
375                 void *hint = descr->debug_hint ?
376                         descr->debug_hint(obj->object) : NULL;
377                 limit++;
378                 WARN(1, KERN_ERR "ODEBUG: %s %s (active state %u) "
379                                  "object type: %s hint: %pS\n",
380                         msg, obj_states[obj->state], obj->astate,
381                         descr->name, hint);
382         }
383         debug_objects_warnings++;
384 }
385
386 /*
387  * Try to repair the damage, so we have a better chance to get useful
388  * debug output.
389  */
390 static bool
391 debug_object_fixup(bool (*fixup)(void *addr, enum debug_obj_state state),
392                    void * addr, enum debug_obj_state state)
393 {
394         if (fixup && fixup(addr, state)) {
395                 debug_objects_fixups++;
396                 return true;
397         }
398         return false;
399 }
400
401 static void debug_object_is_on_stack(void *addr, int onstack)
402 {
403         int is_on_stack;
404         static int limit;
405
406         if (limit > 4)
407                 return;
408
409         is_on_stack = object_is_on_stack(addr);
410         if (is_on_stack == onstack)
411                 return;
412
413         limit++;
414         if (is_on_stack)
415                 pr_warn("object %p is on stack %p, but NOT annotated.\n", addr,
416                          task_stack_page(current));
417         else
418                 pr_warn("object %p is NOT on stack %p, but annotated.\n", addr,
419                          task_stack_page(current));
420
421         WARN_ON(1);
422 }
423
424 static struct debug_obj *lookup_object_or_alloc(void *addr, struct debug_bucket *b,
425                                                 struct debug_obj_descr *descr,
426                                                 bool onstack, bool alloc_ifstatic)
427 {
428         struct debug_obj *obj = lookup_object(addr, b);
429         enum debug_obj_state state = ODEBUG_STATE_NONE;
430
431         if (likely(obj))
432                 return obj;
433
434         /*
435          * debug_object_init() unconditionally allocates untracked
436          * objects. It does not matter whether it is a static object or
437          * not.
438          *
439          * debug_object_assert_init() and debug_object_activate() allow
440          * allocation only if the descriptor callback confirms that the
441          * object is static and considered initialized. For non-static
442          * objects the allocation needs to be done from the fixup callback.
443          */
444         if (unlikely(alloc_ifstatic)) {
445                 if (!descr->is_static_object || !descr->is_static_object(addr))
446                         return ERR_PTR(-ENOENT);
447                 /* Statically allocated objects are considered initialized */
448                 state = ODEBUG_STATE_INIT;
449         }
450
451         obj = alloc_object(addr, b, descr);
452         if (likely(obj)) {
453                 obj->state = state;
454                 debug_object_is_on_stack(addr, onstack);
455                 return obj;
456         }
457
458         /* Out of memory. Do the cleanup outside of the locked region */
459         debug_objects_enabled = 0;
460         return NULL;
461 }
462
463 static void debug_objects_fill_pool(void)
464 {
465         /*
466          * On RT enabled kernels the pool refill must happen in preemptible
467          * context:
468          */
469         if (!IS_ENABLED(CONFIG_PREEMPT_RT) || preemptible())
470                 fill_pool();
471 }
472
473 static void
474 __debug_object_init(void *addr, struct debug_obj_descr *descr, int onstack)
475 {
476         enum debug_obj_state state;
477         struct debug_bucket *db;
478         struct debug_obj *obj;
479         unsigned long flags;
480
481         debug_objects_fill_pool();
482
483         db = get_bucket((unsigned long) addr);
484
485         raw_spin_lock_irqsave(&db->lock, flags);
486
487         obj = lookup_object_or_alloc(addr, db, descr, onstack, false);
488         if (unlikely(!obj)) {
489                 raw_spin_unlock_irqrestore(&db->lock, flags);
490                 debug_objects_oom();
491                 return;
492         }
493
494         switch (obj->state) {
495         case ODEBUG_STATE_NONE:
496         case ODEBUG_STATE_INIT:
497         case ODEBUG_STATE_INACTIVE:
498                 obj->state = ODEBUG_STATE_INIT;
499                 break;
500
501         case ODEBUG_STATE_ACTIVE:
502                 state = obj->state;
503                 raw_spin_unlock_irqrestore(&db->lock, flags);
504                 debug_print_object(obj, "init");
505                 debug_object_fixup(descr->fixup_init, addr, state);
506                 return;
507
508         case ODEBUG_STATE_DESTROYED:
509                 raw_spin_unlock_irqrestore(&db->lock, flags);
510                 debug_print_object(obj, "init");
511                 return;
512         default:
513                 break;
514         }
515
516         raw_spin_unlock_irqrestore(&db->lock, flags);
517 }
518
519 /**
520  * debug_object_init - debug checks when an object is initialized
521  * @addr:       address of the object
522  * @descr:      pointer to an object specific debug description structure
523  */
524 void debug_object_init(void *addr, struct debug_obj_descr *descr)
525 {
526         if (!debug_objects_enabled)
527                 return;
528
529         __debug_object_init(addr, descr, 0);
530 }
531 EXPORT_SYMBOL_GPL(debug_object_init);
532
533 /**
534  * debug_object_init_on_stack - debug checks when an object on stack is
535  *                              initialized
536  * @addr:       address of the object
537  * @descr:      pointer to an object specific debug description structure
538  */
539 void debug_object_init_on_stack(void *addr, struct debug_obj_descr *descr)
540 {
541         if (!debug_objects_enabled)
542                 return;
543
544         __debug_object_init(addr, descr, 1);
545 }
546 EXPORT_SYMBOL_GPL(debug_object_init_on_stack);
547
548 /**
549  * debug_object_activate - debug checks when an object is activated
550  * @addr:       address of the object
551  * @descr:      pointer to an object specific debug description structure
552  * Returns 0 for success, -EINVAL for check failed.
553  */
554 int debug_object_activate(void *addr, struct debug_obj_descr *descr)
555 {
556         struct debug_obj o = { .object = addr, .state = ODEBUG_STATE_NOTAVAILABLE, .descr = descr };
557         enum debug_obj_state state;
558         struct debug_bucket *db;
559         struct debug_obj *obj;
560         unsigned long flags;
561         int ret;
562
563         if (!debug_objects_enabled)
564                 return 0;
565
566         debug_objects_fill_pool();
567
568         db = get_bucket((unsigned long) addr);
569
570         raw_spin_lock_irqsave(&db->lock, flags);
571
572         obj = lookup_object_or_alloc(addr, db, descr, false, true);
573         if (likely(!IS_ERR_OR_NULL(obj))) {
574                 bool print_object = false;
575
576                 switch (obj->state) {
577                 case ODEBUG_STATE_INIT:
578                 case ODEBUG_STATE_INACTIVE:
579                         obj->state = ODEBUG_STATE_ACTIVE;
580                         ret = 0;
581                         break;
582
583                 case ODEBUG_STATE_ACTIVE:
584                         state = obj->state;
585                         raw_spin_unlock_irqrestore(&db->lock, flags);
586                         debug_print_object(obj, "activate");
587                         ret = debug_object_fixup(descr->fixup_activate, addr, state);
588                         return ret ? 0 : -EINVAL;
589
590                 case ODEBUG_STATE_DESTROYED:
591                         print_object = true;
592                         ret = -EINVAL;
593                         break;
594                 default:
595                         ret = 0;
596                         break;
597                 }
598                 raw_spin_unlock_irqrestore(&db->lock, flags);
599                 if (print_object)
600                         debug_print_object(obj, "activate");
601                 return ret;
602         }
603
604         raw_spin_unlock_irqrestore(&db->lock, flags);
605
606         /* If NULL the allocation has hit OOM */
607         if (!obj) {
608                 debug_objects_oom();
609                 return 0;
610         }
611
612         /* Object is neither static nor tracked. It's not initialized */
613         debug_print_object(&o, "activate");
614         ret = debug_object_fixup(descr->fixup_activate, addr, ODEBUG_STATE_NOTAVAILABLE);
615         return ret ? 0 : -EINVAL;
616 }
617 EXPORT_SYMBOL_GPL(debug_object_activate);
618
619 /**
620  * debug_object_deactivate - debug checks when an object is deactivated
621  * @addr:       address of the object
622  * @descr:      pointer to an object specific debug description structure
623  */
624 void debug_object_deactivate(void *addr, struct debug_obj_descr *descr)
625 {
626         struct debug_bucket *db;
627         struct debug_obj *obj;
628         unsigned long flags;
629         bool print_object = false;
630
631         if (!debug_objects_enabled)
632                 return;
633
634         db = get_bucket((unsigned long) addr);
635
636         raw_spin_lock_irqsave(&db->lock, flags);
637
638         obj = lookup_object(addr, db);
639         if (obj) {
640                 switch (obj->state) {
641                 case ODEBUG_STATE_INIT:
642                 case ODEBUG_STATE_INACTIVE:
643                 case ODEBUG_STATE_ACTIVE:
644                         if (!obj->astate)
645                                 obj->state = ODEBUG_STATE_INACTIVE;
646                         else
647                                 print_object = true;
648                         break;
649
650                 case ODEBUG_STATE_DESTROYED:
651                         print_object = true;
652                         break;
653                 default:
654                         break;
655                 }
656         }
657
658         raw_spin_unlock_irqrestore(&db->lock, flags);
659         if (!obj) {
660                 struct debug_obj o = { .object = addr,
661                                        .state = ODEBUG_STATE_NOTAVAILABLE,
662                                        .descr = descr };
663
664                 debug_print_object(&o, "deactivate");
665         } else if (print_object) {
666                 debug_print_object(obj, "deactivate");
667         }
668 }
669 EXPORT_SYMBOL_GPL(debug_object_deactivate);
670
671 /**
672  * debug_object_destroy - debug checks when an object is destroyed
673  * @addr:       address of the object
674  * @descr:      pointer to an object specific debug description structure
675  */
676 void debug_object_destroy(void *addr, struct debug_obj_descr *descr)
677 {
678         enum debug_obj_state state;
679         struct debug_bucket *db;
680         struct debug_obj *obj;
681         unsigned long flags;
682         bool print_object = false;
683
684         if (!debug_objects_enabled)
685                 return;
686
687         db = get_bucket((unsigned long) addr);
688
689         raw_spin_lock_irqsave(&db->lock, flags);
690
691         obj = lookup_object(addr, db);
692         if (!obj)
693                 goto out_unlock;
694
695         switch (obj->state) {
696         case ODEBUG_STATE_NONE:
697         case ODEBUG_STATE_INIT:
698         case ODEBUG_STATE_INACTIVE:
699                 obj->state = ODEBUG_STATE_DESTROYED;
700                 break;
701         case ODEBUG_STATE_ACTIVE:
702                 state = obj->state;
703                 raw_spin_unlock_irqrestore(&db->lock, flags);
704                 debug_print_object(obj, "destroy");
705                 debug_object_fixup(descr->fixup_destroy, addr, state);
706                 return;
707
708         case ODEBUG_STATE_DESTROYED:
709                 print_object = true;
710                 break;
711         default:
712                 break;
713         }
714 out_unlock:
715         raw_spin_unlock_irqrestore(&db->lock, flags);
716         if (print_object)
717                 debug_print_object(obj, "destroy");
718 }
719 EXPORT_SYMBOL_GPL(debug_object_destroy);
720
721 /**
722  * debug_object_free - debug checks when an object is freed
723  * @addr:       address of the object
724  * @descr:      pointer to an object specific debug description structure
725  */
726 void debug_object_free(void *addr, struct debug_obj_descr *descr)
727 {
728         enum debug_obj_state state;
729         struct debug_bucket *db;
730         struct debug_obj *obj;
731         unsigned long flags;
732
733         if (!debug_objects_enabled)
734                 return;
735
736         db = get_bucket((unsigned long) addr);
737
738         raw_spin_lock_irqsave(&db->lock, flags);
739
740         obj = lookup_object(addr, db);
741         if (!obj)
742                 goto out_unlock;
743
744         switch (obj->state) {
745         case ODEBUG_STATE_ACTIVE:
746                 state = obj->state;
747                 raw_spin_unlock_irqrestore(&db->lock, flags);
748                 debug_print_object(obj, "free");
749                 debug_object_fixup(descr->fixup_free, addr, state);
750                 return;
751         default:
752                 hlist_del(&obj->node);
753                 raw_spin_unlock_irqrestore(&db->lock, flags);
754                 free_object(obj);
755                 return;
756         }
757 out_unlock:
758         raw_spin_unlock_irqrestore(&db->lock, flags);
759 }
760 EXPORT_SYMBOL_GPL(debug_object_free);
761
762 /**
763  * debug_object_assert_init - debug checks when object should be init-ed
764  * @addr:       address of the object
765  * @descr:      pointer to an object specific debug description structure
766  */
767 void debug_object_assert_init(void *addr, struct debug_obj_descr *descr)
768 {
769         struct debug_obj o = { .object = addr, .state = ODEBUG_STATE_NOTAVAILABLE, .descr = descr };
770         struct debug_bucket *db;
771         struct debug_obj *obj;
772         unsigned long flags;
773
774         if (!debug_objects_enabled)
775                 return;
776
777         debug_objects_fill_pool();
778
779         db = get_bucket((unsigned long) addr);
780
781         raw_spin_lock_irqsave(&db->lock, flags);
782         obj = lookup_object_or_alloc(addr, db, descr, false, true);
783         raw_spin_unlock_irqrestore(&db->lock, flags);
784         if (likely(!IS_ERR_OR_NULL(obj)))
785                 return;
786
787         /* If NULL the allocation has hit OOM */
788         if (!obj) {
789                 debug_objects_oom();
790                 return;
791         }
792
793         /* Object is neither tracked nor static. It's not initialized. */
794         debug_print_object(&o, "assert_init");
795         debug_object_fixup(descr->fixup_assert_init, addr, ODEBUG_STATE_NOTAVAILABLE);
796 }
797 EXPORT_SYMBOL_GPL(debug_object_assert_init);
798
799 /**
800  * debug_object_active_state - debug checks object usage state machine
801  * @addr:       address of the object
802  * @descr:      pointer to an object specific debug description structure
803  * @expect:     expected state
804  * @next:       state to move to if expected state is found
805  */
806 void
807 debug_object_active_state(void *addr, struct debug_obj_descr *descr,
808                           unsigned int expect, unsigned int next)
809 {
810         struct debug_bucket *db;
811         struct debug_obj *obj;
812         unsigned long flags;
813         bool print_object = false;
814
815         if (!debug_objects_enabled)
816                 return;
817
818         db = get_bucket((unsigned long) addr);
819
820         raw_spin_lock_irqsave(&db->lock, flags);
821
822         obj = lookup_object(addr, db);
823         if (obj) {
824                 switch (obj->state) {
825                 case ODEBUG_STATE_ACTIVE:
826                         if (obj->astate == expect)
827                                 obj->astate = next;
828                         else
829                                 print_object = true;
830                         break;
831
832                 default:
833                         print_object = true;
834                         break;
835                 }
836         }
837
838         raw_spin_unlock_irqrestore(&db->lock, flags);
839         if (!obj) {
840                 struct debug_obj o = { .object = addr,
841                                        .state = ODEBUG_STATE_NOTAVAILABLE,
842                                        .descr = descr };
843
844                 debug_print_object(&o, "active_state");
845         } else if (print_object) {
846                 debug_print_object(obj, "active_state");
847         }
848 }
849 EXPORT_SYMBOL_GPL(debug_object_active_state);
850
851 #ifdef CONFIG_DEBUG_OBJECTS_FREE
852 static void __debug_check_no_obj_freed(const void *address, unsigned long size)
853 {
854         unsigned long flags, oaddr, saddr, eaddr, paddr, chunks;
855         struct debug_obj_descr *descr;
856         enum debug_obj_state state;
857         struct debug_bucket *db;
858         struct hlist_node *tmp;
859         struct debug_obj *obj;
860         int cnt, objs_checked = 0;
861         bool work = false;
862
863         saddr = (unsigned long) address;
864         eaddr = saddr + size;
865         paddr = saddr & ODEBUG_CHUNK_MASK;
866         chunks = ((eaddr - paddr) + (ODEBUG_CHUNK_SIZE - 1));
867         chunks >>= ODEBUG_CHUNK_SHIFT;
868
869         for (;chunks > 0; chunks--, paddr += ODEBUG_CHUNK_SIZE) {
870                 db = get_bucket(paddr);
871
872 repeat:
873                 cnt = 0;
874                 raw_spin_lock_irqsave(&db->lock, flags);
875                 hlist_for_each_entry_safe(obj, tmp, &db->list, node) {
876                         cnt++;
877                         oaddr = (unsigned long) obj->object;
878                         if (oaddr < saddr || oaddr >= eaddr)
879                                 continue;
880
881                         switch (obj->state) {
882                         case ODEBUG_STATE_ACTIVE:
883                                 descr = obj->descr;
884                                 state = obj->state;
885                                 raw_spin_unlock_irqrestore(&db->lock, flags);
886                                 debug_print_object(obj, "free");
887                                 debug_object_fixup(descr->fixup_free,
888                                                    (void *) oaddr, state);
889                                 goto repeat;
890                         default:
891                                 hlist_del(&obj->node);
892                                 work |= __free_object(obj);
893                                 break;
894                         }
895                 }
896                 raw_spin_unlock_irqrestore(&db->lock, flags);
897
898                 if (cnt > debug_objects_maxchain)
899                         debug_objects_maxchain = cnt;
900
901                 objs_checked += cnt;
902         }
903
904         if (objs_checked > debug_objects_maxchecked)
905                 debug_objects_maxchecked = objs_checked;
906
907         /* Schedule work to actually kmem_cache_free() objects */
908         if (work)
909                 schedule_work(&debug_obj_work);
910 }
911
912 void debug_check_no_obj_freed(const void *address, unsigned long size)
913 {
914         if (debug_objects_enabled)
915                 __debug_check_no_obj_freed(address, size);
916 }
917 #endif
918
919 #ifdef CONFIG_DEBUG_FS
920
921 static int debug_stats_show(struct seq_file *m, void *v)
922 {
923         int cpu, obj_percpu_free = 0;
924
925         for_each_possible_cpu(cpu)
926                 obj_percpu_free += per_cpu(percpu_obj_pool.obj_free, cpu);
927
928         seq_printf(m, "max_chain     :%d\n", debug_objects_maxchain);
929         seq_printf(m, "max_checked   :%d\n", debug_objects_maxchecked);
930         seq_printf(m, "warnings      :%d\n", debug_objects_warnings);
931         seq_printf(m, "fixups        :%d\n", debug_objects_fixups);
932         seq_printf(m, "pool_free     :%d\n", obj_pool_free + obj_percpu_free);
933         seq_printf(m, "pool_pcp_free :%d\n", obj_percpu_free);
934         seq_printf(m, "pool_min_free :%d\n", obj_pool_min_free);
935         seq_printf(m, "pool_used     :%d\n", obj_pool_used - obj_percpu_free);
936         seq_printf(m, "pool_max_used :%d\n", obj_pool_max_used);
937         seq_printf(m, "on_free_list  :%d\n", obj_nr_tofree);
938         seq_printf(m, "objs_allocated:%d\n", debug_objects_allocated);
939         seq_printf(m, "objs_freed    :%d\n", debug_objects_freed);
940         return 0;
941 }
942
943 static int debug_stats_open(struct inode *inode, struct file *filp)
944 {
945         return single_open(filp, debug_stats_show, NULL);
946 }
947
948 static const struct file_operations debug_stats_fops = {
949         .open           = debug_stats_open,
950         .read           = seq_read,
951         .llseek         = seq_lseek,
952         .release        = single_release,
953 };
954
955 static int __init debug_objects_init_debugfs(void)
956 {
957         struct dentry *dbgdir, *dbgstats;
958
959         if (!debug_objects_enabled)
960                 return 0;
961
962         dbgdir = debugfs_create_dir("debug_objects", NULL);
963         if (!dbgdir)
964                 return -ENOMEM;
965
966         dbgstats = debugfs_create_file("stats", 0444, dbgdir, NULL,
967                                        &debug_stats_fops);
968         if (!dbgstats)
969                 goto err;
970
971         return 0;
972
973 err:
974         debugfs_remove(dbgdir);
975
976         return -ENOMEM;
977 }
978 __initcall(debug_objects_init_debugfs);
979
980 #else
981 static inline void debug_objects_init_debugfs(void) { }
982 #endif
983
984 #ifdef CONFIG_DEBUG_OBJECTS_SELFTEST
985
986 /* Random data structure for the self test */
987 struct self_test {
988         unsigned long   dummy1[6];
989         int             static_init;
990         unsigned long   dummy2[3];
991 };
992
993 static __initdata struct debug_obj_descr descr_type_test;
994
995 static bool __init is_static_object(void *addr)
996 {
997         struct self_test *obj = addr;
998
999         return obj->static_init;
1000 }
1001
1002 /*
1003  * fixup_init is called when:
1004  * - an active object is initialized
1005  */
1006 static bool __init fixup_init(void *addr, enum debug_obj_state state)
1007 {
1008         struct self_test *obj = addr;
1009
1010         switch (state) {
1011         case ODEBUG_STATE_ACTIVE:
1012                 debug_object_deactivate(obj, &descr_type_test);
1013                 debug_object_init(obj, &descr_type_test);
1014                 return true;
1015         default:
1016                 return false;
1017         }
1018 }
1019
1020 /*
1021  * fixup_activate is called when:
1022  * - an active object is activated
1023  * - an unknown non-static object is activated
1024  */
1025 static bool __init fixup_activate(void *addr, enum debug_obj_state state)
1026 {
1027         struct self_test *obj = addr;
1028
1029         switch (state) {
1030         case ODEBUG_STATE_NOTAVAILABLE:
1031                 return true;
1032         case ODEBUG_STATE_ACTIVE:
1033                 debug_object_deactivate(obj, &descr_type_test);
1034                 debug_object_activate(obj, &descr_type_test);
1035                 return true;
1036
1037         default:
1038                 return false;
1039         }
1040 }
1041
1042 /*
1043  * fixup_destroy is called when:
1044  * - an active object is destroyed
1045  */
1046 static bool __init fixup_destroy(void *addr, enum debug_obj_state state)
1047 {
1048         struct self_test *obj = addr;
1049
1050         switch (state) {
1051         case ODEBUG_STATE_ACTIVE:
1052                 debug_object_deactivate(obj, &descr_type_test);
1053                 debug_object_destroy(obj, &descr_type_test);
1054                 return true;
1055         default:
1056                 return false;
1057         }
1058 }
1059
1060 /*
1061  * fixup_free is called when:
1062  * - an active object is freed
1063  */
1064 static bool __init fixup_free(void *addr, enum debug_obj_state state)
1065 {
1066         struct self_test *obj = addr;
1067
1068         switch (state) {
1069         case ODEBUG_STATE_ACTIVE:
1070                 debug_object_deactivate(obj, &descr_type_test);
1071                 debug_object_free(obj, &descr_type_test);
1072                 return true;
1073         default:
1074                 return false;
1075         }
1076 }
1077
1078 static int __init
1079 check_results(void *addr, enum debug_obj_state state, int fixups, int warnings)
1080 {
1081         struct debug_bucket *db;
1082         struct debug_obj *obj;
1083         unsigned long flags;
1084         int res = -EINVAL;
1085
1086         db = get_bucket((unsigned long) addr);
1087
1088         raw_spin_lock_irqsave(&db->lock, flags);
1089
1090         obj = lookup_object(addr, db);
1091         if (!obj && state != ODEBUG_STATE_NONE) {
1092                 WARN(1, KERN_ERR "ODEBUG: selftest object not found\n");
1093                 goto out;
1094         }
1095         if (obj && obj->state != state) {
1096                 WARN(1, KERN_ERR "ODEBUG: selftest wrong state: %d != %d\n",
1097                        obj->state, state);
1098                 goto out;
1099         }
1100         if (fixups != debug_objects_fixups) {
1101                 WARN(1, KERN_ERR "ODEBUG: selftest fixups failed %d != %d\n",
1102                        fixups, debug_objects_fixups);
1103                 goto out;
1104         }
1105         if (warnings != debug_objects_warnings) {
1106                 WARN(1, KERN_ERR "ODEBUG: selftest warnings failed %d != %d\n",
1107                        warnings, debug_objects_warnings);
1108                 goto out;
1109         }
1110         res = 0;
1111 out:
1112         raw_spin_unlock_irqrestore(&db->lock, flags);
1113         if (res)
1114                 debug_objects_enabled = 0;
1115         return res;
1116 }
1117
1118 static __initdata struct debug_obj_descr descr_type_test = {
1119         .name                   = "selftest",
1120         .is_static_object       = is_static_object,
1121         .fixup_init             = fixup_init,
1122         .fixup_activate         = fixup_activate,
1123         .fixup_destroy          = fixup_destroy,
1124         .fixup_free             = fixup_free,
1125 };
1126
1127 static __initdata struct self_test obj = { .static_init = 0 };
1128
1129 static void __init debug_objects_selftest(void)
1130 {
1131         int fixups, oldfixups, warnings, oldwarnings;
1132         unsigned long flags;
1133
1134         local_irq_save(flags);
1135
1136         fixups = oldfixups = debug_objects_fixups;
1137         warnings = oldwarnings = debug_objects_warnings;
1138         descr_test = &descr_type_test;
1139
1140         debug_object_init(&obj, &descr_type_test);
1141         if (check_results(&obj, ODEBUG_STATE_INIT, fixups, warnings))
1142                 goto out;
1143         debug_object_activate(&obj, &descr_type_test);
1144         if (check_results(&obj, ODEBUG_STATE_ACTIVE, fixups, warnings))
1145                 goto out;
1146         debug_object_activate(&obj, &descr_type_test);
1147         if (check_results(&obj, ODEBUG_STATE_ACTIVE, ++fixups, ++warnings))
1148                 goto out;
1149         debug_object_deactivate(&obj, &descr_type_test);
1150         if (check_results(&obj, ODEBUG_STATE_INACTIVE, fixups, warnings))
1151                 goto out;
1152         debug_object_destroy(&obj, &descr_type_test);
1153         if (check_results(&obj, ODEBUG_STATE_DESTROYED, fixups, warnings))
1154                 goto out;
1155         debug_object_init(&obj, &descr_type_test);
1156         if (check_results(&obj, ODEBUG_STATE_DESTROYED, fixups, ++warnings))
1157                 goto out;
1158         debug_object_activate(&obj, &descr_type_test);
1159         if (check_results(&obj, ODEBUG_STATE_DESTROYED, fixups, ++warnings))
1160                 goto out;
1161         debug_object_deactivate(&obj, &descr_type_test);
1162         if (check_results(&obj, ODEBUG_STATE_DESTROYED, fixups, ++warnings))
1163                 goto out;
1164         debug_object_free(&obj, &descr_type_test);
1165         if (check_results(&obj, ODEBUG_STATE_NONE, fixups, warnings))
1166                 goto out;
1167
1168         obj.static_init = 1;
1169         debug_object_activate(&obj, &descr_type_test);
1170         if (check_results(&obj, ODEBUG_STATE_ACTIVE, fixups, warnings))
1171                 goto out;
1172         debug_object_init(&obj, &descr_type_test);
1173         if (check_results(&obj, ODEBUG_STATE_INIT, ++fixups, ++warnings))
1174                 goto out;
1175         debug_object_free(&obj, &descr_type_test);
1176         if (check_results(&obj, ODEBUG_STATE_NONE, fixups, warnings))
1177                 goto out;
1178
1179 #ifdef CONFIG_DEBUG_OBJECTS_FREE
1180         debug_object_init(&obj, &descr_type_test);
1181         if (check_results(&obj, ODEBUG_STATE_INIT, fixups, warnings))
1182                 goto out;
1183         debug_object_activate(&obj, &descr_type_test);
1184         if (check_results(&obj, ODEBUG_STATE_ACTIVE, fixups, warnings))
1185                 goto out;
1186         __debug_check_no_obj_freed(&obj, sizeof(obj));
1187         if (check_results(&obj, ODEBUG_STATE_NONE, ++fixups, ++warnings))
1188                 goto out;
1189 #endif
1190         pr_info("selftest passed\n");
1191
1192 out:
1193         debug_objects_fixups = oldfixups;
1194         debug_objects_warnings = oldwarnings;
1195         descr_test = NULL;
1196
1197         local_irq_restore(flags);
1198 }
1199 #else
1200 static inline void debug_objects_selftest(void) { }
1201 #endif
1202
1203 /*
1204  * Called during early boot to initialize the hash buckets and link
1205  * the static object pool objects into the poll list. After this call
1206  * the object tracker is fully operational.
1207  */
1208 void __init debug_objects_early_init(void)
1209 {
1210         int i;
1211
1212         for (i = 0; i < ODEBUG_HASH_SIZE; i++)
1213                 raw_spin_lock_init(&obj_hash[i].lock);
1214
1215         for (i = 0; i < ODEBUG_POOL_SIZE; i++)
1216                 hlist_add_head(&obj_static_pool[i].node, &obj_pool);
1217 }
1218
1219 /*
1220  * Convert the statically allocated objects to dynamic ones:
1221  */
1222 static int __init debug_objects_replace_static_objects(void)
1223 {
1224         struct debug_bucket *db = obj_hash;
1225         struct hlist_node *tmp;
1226         struct debug_obj *obj, *new;
1227         HLIST_HEAD(objects);
1228         int i, cnt = 0;
1229
1230         for (i = 0; i < ODEBUG_POOL_SIZE; i++) {
1231                 obj = kmem_cache_zalloc(obj_cache, GFP_KERNEL);
1232                 if (!obj)
1233                         goto free;
1234                 hlist_add_head(&obj->node, &objects);
1235         }
1236
1237         /*
1238          * When debug_objects_mem_init() is called we know that only
1239          * one CPU is up, so disabling interrupts is enough
1240          * protection. This avoids the lockdep hell of lock ordering.
1241          */
1242         local_irq_disable();
1243
1244         /* Remove the statically allocated objects from the pool */
1245         hlist_for_each_entry_safe(obj, tmp, &obj_pool, node)
1246                 hlist_del(&obj->node);
1247         /* Move the allocated objects to the pool */
1248         hlist_move_list(&objects, &obj_pool);
1249
1250         /* Replace the active object references */
1251         for (i = 0; i < ODEBUG_HASH_SIZE; i++, db++) {
1252                 hlist_move_list(&db->list, &objects);
1253
1254                 hlist_for_each_entry(obj, &objects, node) {
1255                         new = hlist_entry(obj_pool.first, typeof(*obj), node);
1256                         hlist_del(&new->node);
1257                         /* copy object data */
1258                         *new = *obj;
1259                         hlist_add_head(&new->node, &db->list);
1260                         cnt++;
1261                 }
1262         }
1263         local_irq_enable();
1264
1265         pr_debug("%d of %d active objects replaced\n",
1266                  cnt, obj_pool_used);
1267         return 0;
1268 free:
1269         hlist_for_each_entry_safe(obj, tmp, &objects, node) {
1270                 hlist_del(&obj->node);
1271                 kmem_cache_free(obj_cache, obj);
1272         }
1273         return -ENOMEM;
1274 }
1275
1276 /*
1277  * Called after the kmem_caches are functional to setup a dedicated
1278  * cache pool, which has the SLAB_DEBUG_OBJECTS flag set. This flag
1279  * prevents that the debug code is called on kmem_cache_free() for the
1280  * debug tracker objects to avoid recursive calls.
1281  */
1282 void __init debug_objects_mem_init(void)
1283 {
1284         int cpu;
1285
1286         if (!debug_objects_enabled)
1287                 return;
1288
1289         /*
1290          * Initialize the percpu object pools
1291          *
1292          * Initialization is not strictly necessary, but was done for
1293          * completeness.
1294          */
1295         for_each_possible_cpu(cpu)
1296                 INIT_HLIST_HEAD(&per_cpu(percpu_obj_pool.free_objs, cpu));
1297
1298         obj_cache = kmem_cache_create("debug_objects_cache",
1299                                       sizeof (struct debug_obj), 0,
1300                                       SLAB_DEBUG_OBJECTS | SLAB_NOLEAKTRACE,
1301                                       NULL);
1302
1303         if (!obj_cache || debug_objects_replace_static_objects()) {
1304                 debug_objects_enabled = 0;
1305                 kmem_cache_destroy(obj_cache);
1306                 pr_warn("out of memory.\n");
1307         } else
1308                 debug_objects_selftest();
1309 }