forked from kmrov/racehound
-
Notifications
You must be signed in to change notification settings - Fork 0
/
racehound_main.c
3186 lines (2726 loc) · 87.9 KB
/
racehound_main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* RaceHound can be used to detect data races in the kernel code in runtime.
*
* The ideas behind it are similar to those implemented in DataCollider tool
* for MS Windows, see John Erickson et. al., "Effective Data-Race Detection
* for the Kernel" - Proc. 9th USENIX Symposium on Operating Systems Design
* and Implementation (OSDI'10).
*
* The idea, in short:
*
* 1. Place a software breakpoint on an instruction that may access memory.
*
* 2. When the software breakpoint hits, determine the address and the size
* of the memory area the instruction is about to access.
*
* 3. Save the contents of that area (optional).
*
* 4. Place one or more hardware breakpoints on that memory area to detect
* accesses to it from any CPU. If the instruction is about to read from
* that memory, the hardware breakpoints need to detect the writes to it.
* If the instruction is about to write to that memory, the hardware
* breakpoints should look for both reads and writes.
*
* 5. Make a delay. If some code makes a conflicting access to that memory
* area during the delay, the hardware breakpoints might detect it.
*
* 6. Disarm the hardware breakpoints.
*
* 7. Check if the contents of that memory area have changed during the
* delay (optional). This may help detect conflicting accesses that the
* hardware breakpoints do not catch (DMA?).
*
* 8. Let the instruction execute as usual. */
/* ====================================================================== */
/* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* Copyright 2012 Nikita Komarov <nikita@kmrov.ru>
*
* 2012 Initial implementation by Nikita Komarov <nikita@kmrov.ru>,
* with enhancements by Andrey Tsyvarev <tsyvarev@ispras.ru>.
*
* 2013 Eugene Shatokhin <eugene.shatokhin@rosalab.ru>: rewrote the
* handling of the breakpoints to make it more robust.
* Added repeated-read checks, many other enhancements.
*
* 2014-2015 Eugene Shatokhin <eugene.shatokhin@rosalab.ru>: overhauled
* the structure of RaceHound as a whole, reimplemented
* handling of the software BPs with Kprobes, etc. */
/* ====================================================================== */
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/wait.h>
#include <linux/completion.h>
#include <linux/preempt.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/workqueue.h>
#include <linux/percpu.h>
#include <linux/smp.h>
#include <linux/sched.h>
#include <linux/rcupdate.h>
#include <linux/rculist.h>
#include <linux/irqflags.h>
#include <linux/hardirq.h>
#include <linux/debugfs.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/kallsyms.h>
#include <linux/kref.h>
#include <linux/uaccess.h>
#include <linux/kprobes.h>
#include <linux/perf_event.h>
#include <linux/hw_breakpoint.h>
#include <linux/stacktrace.h>
#include <linux/circ_buf.h>
#include <linux/hash.h>
#include <generated/utsrelease.h>
/* Do not #include <common/...> or other headers of the insn decoder here.
* They may conflict with the ones from the kernel #included via kprobes.h.
* Use the wrappers from insn_analysis.h instead. */
#include "insn_analysis.h"
#include "stackdepot.h"
#include "config.h"
#define RH_MSG_PREFIX "[rh] "
/* ====================================================================== */
/* Maximum stack depth for the stored stack traces. */
#define RH_STACK_DEPTH 64
/* Parameters of the hash table to store the races. */
#define RH_RACE_HASH_BITS 10
#define RH_RACE_HASH_SIZE (1UL << RH_RACE_HASH_BITS)
struct rh_race {
struct rh_race *next;
/* Handles to the stored stacks of the conflicting accesses.
* st[0] is always non-zero, st[1] is 0 if the race was found
* by the repeated read rather than by a HWBP hit.
* 'combined' is used for hashing. */
union {
u64 combined;
depot_stack_handle_t st[2];
} stacks;
/*
* IP (address of the instruction) and comm for each of the threads
* that accessed the given memory area.
*/
unsigned long ip0;
unsigned long ip1; /* 0 in case of repeated read */
char comm0[TASK_COMM_LEN];
char comm1[TASK_COMM_LEN];
/* Address and size of the accessed memory area. */
unsigned long addr;
unsigned int size;
/* For the deferred reporting of the race. */
struct work_struct work;
};
/* A mutex to protect the collection of found races. */
static DEFINE_MUTEX(race_mutex);
static struct rh_race *race_table[RH_RACE_HASH_SIZE];
/*
* We cannot place this declaration in stackdepot.h because the version
* of that file provided by the kernel is likely to take precedence.
*/
void depot_cleanup(void);
/*
* in_task() was introduced in the mainline commit
* 7c4788950ba5 "x86/uaccess, sched/preempt: Verify access_ok() context",
* which went into kernel 4.10.
*/
#if !defined(in_task)
#define in_task() (!(preempt_count() & \
(NMI_MASK | HARDIRQ_MASK | SOFTIRQ_OFFSET)))
#endif
/* ====================================================================== */
#if defined(KPROBE_INSN_SLOT_SIZE)
# define RH_INSN_SLOT_SIZE KPROBE_INSN_SLOT_SIZE
#else
# define RH_INSN_SLOT_SIZE MAX_INSN_SIZE
#endif
#if (( LINUX_VERSION_CODE >= KERNEL_VERSION(4, 5, 0) ) || \
( LINUX_VERSION_CODE >= KERNEL_VERSION(4, 4, 0) && \
UTS_UBUNTU_RELEASE_ABI >= 7 ) \
)
static inline void *module_core_addr(struct module *mod)
{
return mod->core_layout.base;
}
static inline unsigned int core_text_size(struct module *mod)
{
return mod->core_layout.text_size;
}
static inline void *module_init_addr(struct module *mod)
{
return mod->init_layout.base;
}
static inline unsigned int init_text_size(struct module *mod)
{
return mod->init_layout.text_size;
}
#else
static inline void *module_core_addr(struct module *mod)
{
return mod->module_core;
}
static inline unsigned int core_text_size(struct module *mod)
{
return mod->core_text_size;
}
static inline void *module_init_addr(struct module *mod)
{
return mod->module_init;
}
static inline unsigned int init_text_size(struct module *mod)
{
return mod->init_text_size;
}
#endif
/* ====================================================================== */
static struct dentry *debugfs_dir_dentry = NULL;
static const char *debugfs_dir_name = "racehound";
/* Counter for the found races.
* Write 0 to this file to reset the counter. */
static struct dentry *race_counter_file = NULL;
static atomic_t race_counter = ATOMIC_INIT(0);
struct dentry *bp_file = NULL;
/* This file ("events") shows the software breakpoints that have hit.
* The user space can use poll/epoll/select on it.
* The items are stored in a circular buffer (see below). The items are
* comsumed when read, freeing the space in the buffer. When the buffer is
* full, the new events are discarded. "events_lost" file will show the
* number of such discarded events. */
static struct dentry *events_file = NULL;
static struct dentry *events_lost_file = NULL;
/* ====================================================================== */
/* The maximum size of the memory area to check with repeated reads. */
#define RH_MAX_REP_READ_SIZE sizeof(unsigned long)
/* ====================================================================== */
static unsigned long delay = 0;
module_param(delay, ulong, S_IRUGO);
MODULE_PARM_DESC(delay,
"How long to delay execution of an instruction "
"waiting for the conflicting memory accesses (in milliseconds). "
"If 0, the delay of 5000/HZ ms (5 jiffies) will be used.");
/* ====================================================================== */
/* If RaceHound is about to unload, it will wait till its software BPs are
* no longer used. */
static wait_queue_head_t waitq;
static atomic_t bps_in_use = ATOMIC_INIT(0);
/* ====================================================================== */
/* It would be nice to get it some other way rather than look up by name.
* But that seems impossible unless this code is included into the kernel
* itself. */
static int (*do_arch_install_hwbp)(struct perf_event *bp);
static int (*do_arch_uninstall_hwbp)(struct perf_event *bp);
/* current_kprobe is not exported to the modules, so we get it via kallsyms
* too. */
static struct kprobe **p_current_kprobe;
/* set_memory_{ro,rw} functions are also not exported. */
static int (*do_set_memory_rw)(unsigned long addr, int numpages);
static int (*do_set_memory_ro)(unsigned long addr, int numpages);
/* Same for text_mutex. */
static struct mutex *p_text_mutex;
/* ====================================================================== */
/* The code of the kernel proper occupies the range [_text, _etext) in the
* address space. ".text" section starts at '_text' and ends at or before
* '_etext'. */
static unsigned long stext = 0;
static unsigned long etext = 0;
static unsigned int kernel_text_size = 0;
/* ====================================================================== */
#define RH_JMP_REL_OPCODE 0xe9 /* JMP near relative */
#define RH_JMP_REL_SIZE 5 /* Length of JMP near relative insn */
/* ====================================================================== */
/* A mutex to protect the lists of SW BPs and the related data. */
static DEFINE_MUTEX(swbp_mutex);
/* true if the requests to add/remove SW BPs should be processed, false if
* they should be ignored.
*
* Access this with swbp_mutex locked.
*
* This flag helps enable BP handling only when everything is ready for that
* and prevent the too early or too late requests. */
static bool bps_enabled = false;
/* ====================================================================== */
/* We'll need the addresses of the thunks below. */
void rh_thunk_pre(void);
void rh_thunk_post(void);
/* ====================================================================== */
/* A group of SW BPs for a given component of the kernel. */
struct swbp_group
{
/* The list of groups. */
struct list_head list;
/* Name of the kernel module the BPs belong to, NULL for the kernel
* proper. */
char *module_name;
/* The module the BP belongs to. NULL if the module is not loaded
* or if the BP is for the kernel proper. */
struct module *mod;
/* The SW BPs. Access this list with swbp_mutex locked. */
struct list_head bp_list;
};
static LIST_HEAD(swbp_group_list);
/* Parameters of a software breakpoint. */
struct swbp
{
/* The list of the BPs for a given component of the kernel. */
struct list_head list;
/* The Kprobe to be placed on the instruction of interest.
*
* [NB] Do not use kp.addr as an indicator of whether the SW BP is
* armed. If this is a BP set on a module anf that module is
* unloaded, kp.addr may remain non-NULL. */
struct kprobe kp;
/* The decoded instruction. The insn itself is in the Kprobe's insn
* slot. */
struct rh_insn *rh_insn;
/* The group the swbp instance belongs to. */
struct swbp_group *grp;
/* The user may request to remove the BP at any time. The handler
* for HW BPs may still use it however. So the structure is
* refcounted and will be deleted only if no longer used. */
struct kref kref;
/* Whether this SW BP is armed (active) or not. */
bool armed;
/* The size of the memory area that can be accessed by the insn, in
* bytes. For the string operations, it is the size of the basic
* element (1 for MOVSB, 2 for MOVSW, etc.) */
unsigned int base_size;
/* Whether the BP is for init area of the module or not. */
int is_init;
/* Offset of the insn to set the BP to in the core or init area. */
unsigned int offset;
/* If non-zero, this value will be used as a delay rather than the
* module parameter 'delay'. */
unsigned long delay;
/* A string represenation of this BP - for error reporting, etc. */
char *str_repr;
/* Allows to wait till the processing of this SW BP is complete. */
struct completion *completion;
};
/* The data needed to handle our SW BP when it is hit. */
struct swbp_hit
{
struct list_head list;
/* For deferred unref for swbp, etc. */
struct work_struct work;
/* The SW BP. */
struct swbp *swbp;
/* The task where this BP has been triggered. */
struct task_struct *task;
/* Here the register values are saved by the handler of a SW BP. */
struct pt_regs regs;
};
/* The list of the currently active swbp_hit instances. Access this list
* with hit_list_lock locked. */
static LIST_HEAD(hit_list);
static DEFINE_SPINLOCK(hit_list_lock);
/* The workqueue for the deferred unrefs for swbp instances and related
* tasks. Doing that involves unregister_kprobe() and synchronize_sched()
* which is not allowed in atomic context. But the insn in question and
* rh_do_after_insn() for it may happen to execute in an atomic context.
* So these tasks are handled by a workqueue instead. */
static struct workqueue_struct *wq = NULL;
/* ====================================================================== */
/* Prints a string representation of the swbp instance to the given buffer.
* See snprintf() for the details about the return value, 'buf', and 'size'.
*
* May be used in the SW BP handlers too, if needed. */
static int
snprintf_swbp(char *buf, size_t size, const struct swbp *swbp)
{
static const char *fmt = "%s%s%s+0x%x";
const char *component = "";
const char *sep = "";
if (swbp->grp->module_name) {
component = swbp->grp->module_name;
sep = ":";
}
return snprintf(buf, size, fmt, component, sep,
(swbp->is_init ? "init" : "core"),
swbp->offset);
}
static const char *
swbp_to_string(const struct swbp *swbp)
{
return swbp->str_repr;
}
/* [NB] Might sleep.
* Call this function with swbp_mutex locked. */
static struct swbp *
create_swbp(struct swbp_group *grp, int is_init, unsigned int offset,
unsigned long swbp_delay)
{
struct swbp *swbp;
int len;
swbp = kzalloc(sizeof(*swbp), GFP_KERNEL);
if (!swbp) {
pr_warning(RH_MSG_PREFIX "Not enough memory for struct swbp.\n");
return NULL;
}
swbp->armed = false;
swbp->is_init = is_init;
swbp->offset = offset;
swbp->delay = swbp_delay;
swbp->grp = grp;
len = snprintf_swbp(NULL, 0, swbp) + 1;
swbp->str_repr = kzalloc(len, GFP_KERNEL);
if (swbp->str_repr == NULL) {
kfree(swbp);
return NULL;
}
snprintf_swbp(swbp->str_repr, len, swbp);
kref_init(&swbp->kref); /* refcount is now 1 */
list_add(&swbp->list, &grp->bp_list);
return swbp;
}
/* The opposite of arm_swbp(), see below.
* When calling this function, make sure the handlers for this SW BP are not
* running at the moment.
*
* Call this function with swbp_mutex locked. */
static void
disarm_swbp(struct swbp *swbp)
{
if (!swbp->armed)
return;
unregister_kprobe(&swbp->kp);
kfree(swbp->rh_insn);
swbp->rh_insn = NULL;
swbp->armed = false;
}
/* Destroys struct swbp instance. The caller is responsible for disabling
* the SW BP first, removing the structure from the list, etc.
* The caller must ensure noone is using this struct swbp instance by the
* time this function is called. */
static void
destroy_swbp(struct kref *kref)
{
struct swbp *swbp = container_of(kref, typeof(*swbp), kref);
disarm_swbp(swbp);
/* This allows to wait till the processing of this SW BP is
* complete.
* Note that swbp->completion may be NULL in some cases: when
* RaceHound is about to unload or if destroy_swbp() is called when
* cleaning up after some errors, so we take care of that. */
if (swbp->completion)
complete(swbp->completion);
kfree(swbp->str_repr);
kfree(swbp);
}
/* ====================================================================== */
static bool is_rh_code(unsigned long addr)
{
unsigned long start = (unsigned long)module_core_addr(THIS_MODULE);
return (addr >= start && addr < start + core_text_size(THIS_MODULE));
}
/*
* This is similar to how KASAN uses stackdepot in the kernel 4.12, except
* RaceHound-specific filtering.
*
* If filter_rh is true the trace will start after the last stack entry that
* corresponds to racehound.ko, i.e. that entry and the higher ones will be
* skipped. May be convenient when reporting SW BP hits.
*
* If top_addr is non-zero, the stack trace will start from the entry with
* that value. May be convenient when reporting HW BP hits.
*/
static depot_stack_handle_t save_stack(bool filter_rh, unsigned long top_addr)
{
unsigned long entries[RH_STACK_DEPTH];
struct stack_trace trace = {
.nr_entries = 0,
.entries = entries,
.max_entries = RH_STACK_DEPTH,
.skip = 0
};
save_stack_trace(&trace);
if (trace.nr_entries != 0 &&
trace.entries[trace.nr_entries-1] == ULONG_MAX)
trace.nr_entries--;
if (filter_rh) {
unsigned int nr = trace.nr_entries;
trace.nr_entries = 0;
while (nr != 0) {
if (is_rh_code(entries[nr - 1]))
break;
++trace.nr_entries;
--nr;
}
if (!trace.nr_entries)
return 0;
trace.entries = &entries[nr];
}
if (top_addr) {
unsigned int i;
for (i = 0; i < trace.nr_entries; ++i) {
if (entries[i] == top_addr)
break;
}
if (i < trace.nr_entries) {
trace.nr_entries -= i;
trace.entries = &entries[i];
}
}
return depot_save_stack(&trace, GFP_ATOMIC);
}
/*
* If any of the memory accesses are from the init code of a module or if
* the module has already been unloaded, the stack traces will be printed
* with some addresses unresolved or resolved incorrectly. Should be
* acceptable.
*/
static void
report_race(const struct rh_race *race)
{
struct stack_trace trace0 = { .nr_entries = 0 };
struct stack_trace trace1 = { .nr_entries = 0 };
bool got_both_threads = (!!race->stacks.st[1]);
static const char *sep =
"=========================================================";
if (!race->stacks.st[0])
return;
depot_fetch_stack(race->stacks.st[0], &trace0);
if (!trace0.nr_entries)
return;
pr_warning(RH_MSG_PREFIX "%s\n", sep);
pr_warning(RH_MSG_PREFIX "Detected a data race on the the memory block at %p, size %u:\n",
(void *)race->addr, race->size);
pr_warning(RH_MSG_PREFIX "----- Thread #1, comm: %s ----- \n",
race->comm0);
pr_warning(RH_MSG_PREFIX "IP: [<%p>] %pS\n",
(void *)race->ip0, (void *)race->ip0);
print_stack_trace(&trace0, 0);
if (got_both_threads) {
depot_fetch_stack(race->stacks.st[1], &trace1);
if (!trace1.nr_entries)
return;
pr_warning(RH_MSG_PREFIX
"----- Thread #2, comm: %s ----- \n",
race->comm1);
pr_warning(RH_MSG_PREFIX "IP: right before [<%p>] %pS\n",
(void *)race->ip1, (void *)race->ip1);
print_stack_trace(&trace1, 0);
}
else {
pr_warning(
RH_MSG_PREFIX "----- Thread #2 - unknown, "
"the contents of the memory block changed during the delay. ----- \n");
}
pr_warning(RH_MSG_PREFIX "%s\n", sep);
}
static void
do_report_race_work(struct work_struct *work)
{
struct rh_race *race = container_of(work, struct rh_race, work);
struct rh_race **bucket;
struct rh_race *found;
int ret;
bucket = &race_table[hash_64(race->stacks.combined,
RH_RACE_HASH_BITS)];
/*
* Check if the race is new and if so, store it and report it.
* If the race is known (or if an error occurs), free the structure.
* The stored structures will be freed separately.
*/
ret = mutex_lock_killable(&race_mutex);
if (ret) {
pr_debug(RH_MSG_PREFIX "do_report_race_work: failed to lock the mutex.\n");
kfree(race);
return;
}
for (found = *bucket; found; found = found->next) {
if (found->stacks.st[0] == race->stacks.st[0] &&
found->stacks.st[1] == race->stacks.st[1] &&
found->ip0 == race->ip0 &&
found->ip1 == race->ip1) {
break;
}
}
if (!found) {
struct rh_race *tmp = *bucket;
*bucket = race;
race->next = tmp;
report_race(race);
}
else {
kfree(race);
}
mutex_unlock(&race_mutex);
}
/* ====================================================================== */
/* The maximum number of events that can be stored in the circular buffer
* and shown in "events" file. Must be a power of 2.
*
* See also: Documentation/circular-buffers.txt. */
#define RH_MAX_EVENTS_STORED 4096
struct event_buffer {
unsigned int head; /* new data are put here */
unsigned int tail; /* the data are read from here */
char **buf;
};
static struct event_buffer events;
/* Serializes the code reading and consuming the events. */
static DEFINE_MUTEX(event_consumer_mutex);
/* Serializes the code producing the events. */
static DEFINE_SPINLOCK(event_producer_lock);
/* A wait queue for the reader (consumer) to wait on until new events
* become available. */
static wait_queue_head_t eventq;
/* 1 if the file is available, that is can been opened, <= 0 if it is open
* already. */
static atomic_t events_file_available = ATOMIC_INIT(1);
/* The number of the lost events, i.e. the events discarded because the
* buffer was full. */
static atomic_t events_lost = ATOMIC_INIT(0);
static int __init
event_buffer_init(struct event_buffer *e)
{
e->head = 0;
e->tail = 0;
e->buf = kzalloc(sizeof(e->buf[0]) * RH_MAX_EVENTS_STORED,
GFP_KERNEL);
if (!e->buf)
return -ENOMEM;
return 0;
}
/* The events producers and consumers must not be running when this function
* is called. */
static void
event_buffer_destroy(struct event_buffer *e)
{
int i;
if (!e->buf)
return;
for (i = 0; i < RH_MAX_EVENTS_STORED; ++i)
kfree(e->buf[i]);
kfree(e->buf);
}
/* This helper adds an event (a SW BP was hit) to the buffer. Should be used
* by the producers of the events. A copy of the string representation of
* the SW BP is created for that, so the original SW BP may safely disappear
* while this event is still in the buffer.
*
* May be called in atomic context too. */
static void
report_swbp_hit_event(struct event_buffer *e, const char *str_swbp)
{
unsigned long flags;
unsigned int head;
unsigned int tail;
char *str;
BUG_ON(str_swbp == NULL);
spin_lock_irqsave(&event_producer_lock, flags);
/* The producer controls 'head' index. */
head = e->head;
/* Paired with smp_store_release() in events_file_read(). */
tail = smp_load_acquire(&e->tail);
if (CIRC_SPACE(head, tail, RH_MAX_EVENTS_STORED) < 1) {
/* no space left, discard the event */
atomic_inc(&events_lost);
goto out;
}
str = kstrdup(str_swbp, GFP_ATOMIC);
if (!str) {
pr_debug(RH_MSG_PREFIX "report_swbp_hit_event: out of memory.\n");
atomic_inc(&events_lost);
goto out;
}
e->buf[head] = str;
/* Paired with smp_load_acquire() in events_file_read(). */
smp_store_release(&e->head, (head + 1) & (RH_MAX_EVENTS_STORED - 1));
/* Documentation/circular-buffers.txt:
* wake_up() will make sure that the head is committed before
* waking anyone up. */
wake_up(&eventq);
out:
spin_unlock_irqrestore(&event_producer_lock, flags);
}
/* The event currently being read. The terminating 0 is replaced with '\n'.
* 'pos' - the index where to start reading, 'avail' - how many bytes can be
* read, at most (including the terminating '\n'). */
struct read_event {
char *str;
size_t pos;
size_t avail;
};
/* Make sure the file cannot be opened if it is already open.
* Note that it does not guarantee that no operations with this file will
* execute simultaneously. If an application is multithreaded, for
* example, these threads may be able to operate on this file concurrently.
* Still, this "single open" technique gives some protection which may help,
* if (unintentionally) several user-space readers are launched. */
static int
events_file_open(struct inode *inode, struct file *filp)
{
struct read_event *rev;
if (!atomic_dec_and_test(&events_file_available)) {
/* Some process has already opened this file. */
atomic_inc(&events_file_available);
return -EBUSY;
}
rev = kzalloc(sizeof(*rev), GFP_KERNEL);
if (!rev) {
atomic_inc(&events_file_available);
return -ENOMEM;
}
filp->private_data = rev;
return nonseekable_open(inode, filp);
}
static int
events_file_release(struct inode *inode, struct file *filp)
{
struct read_event *rev = filp->private_data;
if (rev) {
kfree(rev->str); /* in case it was not read to the end */
kfree(rev);
}
/* Make the file available again. */
atomic_inc(&events_file_available);
return 0;
}
static ssize_t
events_file_read(struct file *filp, char __user *buf, size_t count,
loff_t *f_pos)
{
int err;
ssize_t ret = 0;
struct read_event *rev = filp->private_data;
err = mutex_lock_killable(&event_consumer_mutex);
if (err != 0) {
pr_warning(RH_MSG_PREFIX "Failed to lock event_consumer_mutex\n");
return -EINTR;
}
/* We cannot assume how many bytes the reader would like to get.
* So we store the event currently being read in filp->private_data
* along with the current position in it. */
if (!rev->str) {
unsigned int head;
unsigned int tail;
/* All previous events (if any) have been fully read.
* Try to get the next one. */
/* Read the index first. */
head = smp_load_acquire(&events.head);
tail = events.tail;
if (CIRC_CNT(head, tail, RH_MAX_EVENTS_STORED) >= 1) {
rev->str = events.buf[tail];
events.buf[tail] = NULL;
if (!rev->str) {
pr_warning(
RH_MSG_PREFIX "events_file_read: unexpected empty event.\n");
ret = -EFAULT;
goto out;
}
rev->pos = 0;
rev->avail = strlen(rev->str);
/* Let it appear as one event per line. */
rev->str[rev->avail] = '\n';
++rev->avail;
/* Make sure the reading of events.buf[tail]
* completes before the update of 'tail' is seen. */
smp_store_release(
&events.tail,
(tail + 1) & (RH_MAX_EVENTS_STORED - 1));
}
else {
ret = -EAGAIN;
goto out;
}
}
/* Now we have something that can be read. */
if (count > rev->avail)
count = rev->avail;
if (copy_to_user(buf, &(rev->str[rev->pos]), count) != 0) {
ret = -EFAULT;
goto out;
}
rev->pos += count;
rev->avail -= count;
if (!rev->avail) {
/* Consumed the whole string, free it. */
kfree(rev->str);
rev->str = NULL;
}
*f_pos += count;
ret = count;
out:
mutex_unlock(&event_consumer_mutex);
return ret;
}
static unsigned int
events_file_poll(struct file *filp, poll_table *wait)
{
unsigned int ret = 0;
unsigned int err;
unsigned int head;
unsigned int tail;
poll_wait(filp, &eventq, wait);
err = mutex_lock_killable(&event_consumer_mutex);
if (err != 0) {
pr_warning(RH_MSG_PREFIX "Failed to lock event_consumer_mutex\n");
return ret;
}
/* We only check here if there are events available for reading
* but do not read them. If we find there are no events but some
* actually become available right now, it is OK.
* No additional barriers are needed. */
head = ACCESS_ONCE(events.head);
tail = events.tail; /* The consumer controls 'tail' index. */
if (CIRC_CNT(head, tail, RH_MAX_EVENTS_STORED) >= 1)
ret = POLLIN | POLLRDNORM;
mutex_unlock(&event_consumer_mutex);
return ret;
}
static const struct file_operations events_file_ops = {
.owner = THIS_MODULE,
.open = events_file_open,
.release = events_file_release,
.read = events_file_read,
.poll = events_file_poll,
};
/* ====================================================================== */
/* Kprobe's pre-handler. Returns 1 like setjmp_pre_handler() for Jprobes to
* avoid single-step.
*
* In case of errors (if it fails to create swbp_hit), it returns 0
* allowing the Kprobe do what it does by default: execute the insn and our
* empty post-handler. */
static int
kp_pre(struct kprobe *p, struct pt_regs *regs)
{
struct swbp *swbp = container_of(p, struct swbp, kp);
struct swbp_hit *swbp_hit;
unsigned long flags;
swbp_hit = kzalloc(sizeof(*swbp_hit), GFP_ATOMIC);
if (!swbp_hit) {
pr_warning(RH_MSG_PREFIX "Out of memory.\n");
/* [NB] The Kprobe has a post-handler, so "boost" will not
* be used. This is good, because the insn slot contains
* our jump after the insn and that jump must not be
* executed now. */
return 0;
}
swbp_hit->swbp = swbp;
swbp_hit->task = current;
swbp_hit->regs = *regs;
swbp_hit->regs.ip -= 1;
/* -1 because regs.ip is for the moment after int3 (0xcc) was hit.*/
/* regs->sp is not always saved by the kernel. Save the correct
* value here.
* [NB] Note that 'regs' is passed to kernel_stack_pointer() rather
* than &swbp_hit->regs. See the description and the code of that
* function for details. */
swbp_hit->regs.sp = kernel_stack_pointer(regs);
/* Make sure the swbp instance lives while it is needed. */
atomic_inc(&bps_in_use);
kref_get(&swbp->kref);
/* swbp_hit instances are placed to hit_list in a LIFO fashion.
* find_swbp_hit() looks for the first swbp_hit instance with
* task == current. This way, no problems should arise even if
* handling of an SW BP in the context of some process is
* interrupted by an IRQ where another SW BP hits. Another instance
* of swbp_hit with the same value of 'task' will be placed on the
* list. It will then be found by the handlers of that SW BP from
* IRQ as it should, then it will be removed from the list. After
* that, processing of the first SW BP may resume and will find
* its swbp_hit instance on the list, OK.*/
spin_lock_irqsave(&hit_list_lock, flags);
list_add(&swbp_hit->list, &hit_list);
spin_unlock_irqrestore(&hit_list_lock, flags);