aboutsummaryrefslogtreecommitdiff
path: root/driver/gator_main.c
blob: a1ab776d991d85f8ca7d49e57fc5aeeac95f8bda (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
/**
 * Copyright (C) ARM Limited 2010-2011. All rights reserved.
 *
 * 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.
 *
 */

static unsigned long gator_protocol_version = 4;

#include "gator.h"
#include <linux/slab.h>
#include <linux/cpu.h>
#include <linux/sched.h>
#include <linux/irq.h>
#include <linux/vmalloc.h>
#include <linux/hardirq.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <asm/uaccess.h>

#ifndef CONFIG_GENERIC_TRACER
#ifndef CONFIG_TRACING
#warning gator requires the kernel to have CONFIG_GENERIC_TRACER or CONFIG_TRACING defined
#endif
#endif

#ifndef CONFIG_PROFILING
#warning gator requires the kernel to have CONFIG_PROFILING defined
#endif

#ifndef CONFIG_HIGH_RES_TIMERS
#warning gator requires the kernel to have CONFIG_HIGH_RES_TIMERS defined
#endif

#ifdef CONFIG_SMP
#ifndef CONFIG_LOCAL_TIMERS
#warning gator requires the kernel to have CONFIG_LOCAL_TIMERS defined on SMP systems
#endif
#endif

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 32)
#error kernels prior to 2.6.32 are not supported
#endif

/******************************************************************************
 * DEFINES
 ******************************************************************************/
#define BUFFER_SIZE_DEFAULT		(256*1024)
#define SYNC_FREQ_DEFAULT		1000

#define NO_COOKIE				0UL
#define INVALID_COOKIE			~0UL

#define PROTOCOL_FRAME				~0
#define PROTOCOL_START_TICK			1
#define PROTOCOL_END_TICK			3
#define PROTOCOL_START_BACKTRACE	5
#define PROTOCOL_END_BACKTRACE		7
#define PROTOCOL_COOKIE				9
#define PROTOCOL_SCHEDULER_TRACE	11
#define PROTOCOL_COUNTERS			13
#define PROTOCOL_ANNOTATE			15
#define PROTOCOL_CPU_SYNC			17

#if defined(__arm__)
#define PC_REG regs->ARM_pc
#else
#define PC_REG regs->ip
#endif

/******************************************************************************
 * PER CPU
 ******************************************************************************/
static unsigned long gator_cpu_cores;
static unsigned long gator_buffer_size;
static unsigned long gator_backtrace_depth;

static unsigned long gator_started;
static unsigned long gator_buffer_opened;
static unsigned long gator_timer_count;
static unsigned long gator_sync_freq;
static int gator_master_tick;
static DEFINE_MUTEX(start_mutex);
static DEFINE_MUTEX(gator_buffer_mutex);

unsigned long gator_net_traffic;

#define COMMIT_SIZE		128
#define COMMIT_MASK		(COMMIT_SIZE-1)
static DEFINE_SPINLOCK(gator_commit_lock);
static int *gator_commit;
static int gator_commit_read;
static int gator_commit_write;

static DECLARE_WAIT_QUEUE_HEAD(gator_buffer_wait);
static DEFINE_PER_CPU(int, gator_cpu_sync);
static DEFINE_PER_CPU(int, gator_cpu_tick);
static DEFINE_PER_CPU(int, gator_first_time);

/******************************************************************************
 * Prototypes
 ******************************************************************************/
static void gator_buffer_write_packed_int(int cpu, unsigned int x);
static void gator_buffer_write_string(int cpu, char *x);
static void gator_add_trace(int cpu, unsigned int address);
static uint64_t gator_get_time(void);

/******************************************************************************
 * Application Includes
 ******************************************************************************/
#include "gator_cookies.c"
#include "gator_trace_sched.c"
#include "gator_backtrace.c"
#include "gator_annotate.c"
#include "gator_events.c"
#include "gator_fs.c"

/******************************************************************************
 * Misc
 ******************************************************************************/
#if defined(__arm__)
u32 gator_cpuid(void)
{
	u32 val;
	asm volatile("mrc p15, 0, %0, c0, c0, 0" : "=r" (val));
	return (val >> 4) & 0xfff;
}
#endif

/******************************************************************************
 * Commit interface
 ******************************************************************************/
static int buffer_commit_ready(void)
{
	return (gator_commit_read != gator_commit_write);
}

static void buffer_commit_read(int *cpu, int *readval, int *writeval)
{
	int read = gator_commit_read;
	*cpu      = gator_commit[read+0];
	*readval  = gator_commit[read+1];
	*writeval = gator_commit[read+2];
	gator_commit_read = (read + 4) & COMMIT_MASK;
}

static void buffer_commit_write(int cpu, int readval, int writeval) {
	int write = gator_commit_write;
	gator_commit[write+0] = cpu;
	gator_commit[write+1] = readval;
	gator_commit[write+2] = writeval;
	gator_commit_write = (write + 4) & COMMIT_MASK;
}

/******************************************************************************
 * Buffer management
 ******************************************************************************/
static uint32_t use_buffer_size;
static uint32_t use_buffer_mask;
static DEFINE_PER_CPU(int, use_buffer_seq);
static DEFINE_PER_CPU(int, use_buffer_read);
static DEFINE_PER_CPU(int, use_buffer_write);
static DEFINE_PER_CPU(char *, use_buffer);

static void gator_buffer_write_packed_int(int cpu, unsigned int x)
{
	uint32_t write = per_cpu(use_buffer_write, cpu);
	uint32_t mask = use_buffer_mask;
	char *buffer = per_cpu(use_buffer, cpu);
	int write0 = (write + 0) & mask;
	int write1 = (write + 1) & mask;
	int write2 = (write + 2) & mask;
	int write3 = (write + 3) & mask;
	int write4 = (write + 4) & mask;
	int write5 = (write + 5) & mask;

	if ((x & 0xffffff80) == 0) {
		buffer[write0] = x & 0x7f;
		per_cpu(use_buffer_write, cpu) = write1;
	} else if ((x & 0xffffc000) == 0) {
		buffer[write0] = x | 0x80;
		buffer[write1] = (x>>7) & 0x7f;
		per_cpu(use_buffer_write, cpu) = write2;
	} else if ((x & 0xffe00000) == 0) {
		buffer[write0] = x | 0x80;
		buffer[write1] = (x>>7) | 0x80;
		buffer[write2] = (x>>14) & 0x7f;
		per_cpu(use_buffer_write, cpu) = write3;
	} else if ((x & 0xf0000000) == 0) {
		buffer[write0] = x | 0x80;
		buffer[write1] = (x>>7) | 0x80;
		buffer[write2] = (x>>14) | 0x80;
		buffer[write3] = (x>>21) & 0x7f;
		per_cpu(use_buffer_write, cpu) = write4;
	} else {
		buffer[write0] = x | 0x80;
		buffer[write1] = (x>>7) | 0x80;
		buffer[write2] = (x>>14) | 0x80;
		buffer[write3] = (x>>21) | 0x80;
		buffer[write4] = (x>>28) & 0x0f;
		per_cpu(use_buffer_write, cpu) = write5;
	}
}

static void gator_buffer_write_bytes(int cpu, char *x, int len)
{
	uint32_t write = per_cpu(use_buffer_write, cpu);
	uint32_t mask = use_buffer_mask;
	char *buffer = per_cpu(use_buffer, cpu);
	int i;

	for (i = 0; i < len; i++) {
		buffer[write] = x[i];
		write = (write + 1) & mask;
	}

	per_cpu(use_buffer_write, cpu) = write;
}

static void gator_buffer_write_string(int cpu, char *x)
{
	int len = strlen(x);
	gator_buffer_write_packed_int(cpu, len);
	gator_buffer_write_bytes(cpu, x, len);
}

static void gator_buffer_header(int cpu)
{
	gator_buffer_write_packed_int(cpu, PROTOCOL_FRAME);
	gator_buffer_write_packed_int(cpu, cpu);
	gator_buffer_write_packed_int(cpu, per_cpu(use_buffer_seq, cpu));
	per_cpu(use_buffer_seq, cpu)++;
}

static void gator_buffer_commit(int cpu)
{
	buffer_commit_write(cpu, per_cpu(use_buffer_read, cpu), per_cpu(use_buffer_write, cpu));
	per_cpu(use_buffer_read, cpu) = per_cpu(use_buffer_write, cpu);
	gator_buffer_header(cpu);
	wake_up(&gator_buffer_wait);
}

static void gator_buffer_check(int cpu, int tick)
{
	if (gator_sync_freq && !(tick % gator_sync_freq)) {
		int c, sync;
		spin_lock(&gator_commit_lock);
		// synchronize, if all online cpus have the same tick waypoint
		sync = per_cpu(gator_cpu_sync, cpu) = per_cpu(gator_cpu_tick, cpu);
		for_each_online_cpu(c) {
			if (sync != per_cpu(gator_cpu_sync, c)) {
				sync = 0;
				break;
			}
		}
		if (sync) {
			gator_buffer_write_packed_int(cpu, PROTOCOL_CPU_SYNC);
		}
		// commit the buffer
		gator_buffer_commit(cpu);
		spin_unlock(&gator_commit_lock);
	} else {
		int available = per_cpu(use_buffer_write, cpu) - per_cpu(use_buffer_read, cpu);
		if (available < 0) {
			available += use_buffer_size;
		}
		if (available >= ((use_buffer_size * 3) / 4)) {
			spin_lock(&gator_commit_lock);
			gator_buffer_commit(cpu);
			spin_unlock(&gator_commit_lock);
		}
	}
}

static void gator_add_trace(int cpu, unsigned int address)
{
	off_t offset = 0;
	unsigned long cookie = get_address_cookie(cpu, current, address & ~1, &offset);

	if (cookie == NO_COOKIE || cookie == INVALID_COOKIE) {
		offset = address;
	}

	gator_buffer_write_packed_int(cpu, offset & ~1);
	gator_buffer_write_packed_int(cpu, cookie);
}

static void gator_add_sample(int cpu, struct pt_regs * const regs)
{
	struct module *mod;
	unsigned int addr, cookie = 0;
	int inKernel = regs ? !user_mode(regs) : 1;
	unsigned long exec_cookie = !inKernel ? get_exec_cookie(cpu, current) : NO_COOKIE;

	gator_buffer_write_packed_int(cpu, PROTOCOL_START_BACKTRACE);

	// TGID::PID::inKernel
	gator_buffer_write_packed_int(cpu, exec_cookie);
	gator_buffer_write_packed_int(cpu, (unsigned int)current->tgid);
	gator_buffer_write_packed_int(cpu, (unsigned int)current->pid);
	gator_buffer_write_packed_int(cpu, inKernel);

	// get_irq_regs() will return NULL outside of IRQ context (e.g. nested IRQ)
	if (regs) {
		if (inKernel) {
			addr = PC_REG;
			mod = __module_address(addr);
			if (mod) {
				cookie = get_cookie(cpu, current, NULL, mod);
				addr = addr - (unsigned long)mod->module_core;
			}
			gator_buffer_write_packed_int(cpu, addr & ~1);
			gator_buffer_write_packed_int(cpu, cookie);
		} else {
			// Cookie+PC
			gator_add_trace(cpu, PC_REG);

			// Backtrace
			if (gator_backtrace_depth)
				arm_backtrace_eabi(cpu, regs, gator_backtrace_depth);
		}
	}

	gator_buffer_write_packed_int(cpu, PROTOCOL_END_BACKTRACE);
}

static void gator_write_packet(int cpu, int type, int len, int *buffer)
{
	int i;
	gator_buffer_write_packed_int(cpu, type);
	gator_buffer_write_packed_int(cpu, len);
	for (i = 0; i < len; i++) {
		gator_buffer_write_packed_int(cpu, buffer[i]);
	}
}

static void gator_write_annotate(int cpu, int len, int *buffer)
{
	int pos = 0;

	while (pos < len) {
		unsigned int tid = buffer[pos++];
		unsigned int bytes = buffer[pos++];
		unsigned int words = (bytes + 3) / 4;
		char *ptr = (char *)&buffer[pos];
		pos += words;

		gator_buffer_write_packed_int(cpu, PROTOCOL_ANNOTATE);
		gator_buffer_write_packed_int(cpu, tid);
		gator_buffer_write_packed_int(cpu, bytes);
		gator_buffer_write_bytes(cpu, ptr, bytes);
	}
}

/******************************************************************************
 * Interrupt Processing
 ******************************************************************************/
static gator_interface *gi = NULL;

static void gator_timer_interrupt(void)
{
	struct pt_regs * const regs = get_irq_regs();
	int cpu = raw_smp_processor_id();
	int *buffer, len, tick;
	gator_interface *i;

	// check full backtrace has enough space, otherwise may
	// have breaks between samples in the same callstack
	if (per_cpu(gator_first_time, cpu)) {
		per_cpu(gator_first_time, cpu) = 0;

		for (i = gi; i != NULL; i = i->next) {
			if (i->read) {
				i->read(NULL);
			}
		}
		return;
	}

	// Header
	gator_buffer_write_packed_int(cpu, PROTOCOL_START_TICK);			// Escape

	// Output scheduler
	len = gator_trace_sched_read(&buffer);
	if (len > 0) {
		gator_write_packet(cpu, PROTOCOL_SCHEDULER_TRACE, len, buffer);
	}

	// Output annotate
	len = gator_annotate_read(&buffer);
	if (len > 0)
		gator_write_annotate(cpu, len, buffer);

	// Output counters
	for (i = gi; i != NULL; i = i->next) {
		if (i->read) {
			len = i->read(&buffer);
			if (len > 0) {
				gator_write_packet(cpu, PROTOCOL_COUNTERS, len, buffer);
			}
		}
	}

	// Output backtrace
	gator_add_sample(cpu, regs);

	// Timer Tick
	tick = per_cpu(gator_cpu_tick, cpu);
	if (tick == gator_master_tick) {
		tick++;
		per_cpu(gator_cpu_tick, cpu) = gator_master_tick = tick;
	} else {
		per_cpu(gator_cpu_tick, cpu) = tick = gator_master_tick;
	}
	gator_write_packet(cpu, PROTOCOL_END_TICK, 1, &tick);

	// Check and commit; generally, commit is set to occur once per second
	gator_buffer_check(cpu, tick);
}

/******************************************************************************
 * hrtimer
 ******************************************************************************/
DEFINE_PER_CPU(struct hrtimer, percpu_hrtimer);
DEFINE_PER_CPU(int, hrtimer_is_active);
static int hrtimer_running;
static ktime_t profiling_interval;

static enum hrtimer_restart gator_hrtimer_notify(struct hrtimer *hrtimer)
{
	hrtimer_forward_now(hrtimer, profiling_interval);
	gator_timer_interrupt();
	return HRTIMER_RESTART;
}

static int gator_timer_init(void)
{
	return 0;
}

static void __gator_timer_offline(void *unused)
{
	int cpu = smp_processor_id();
	if (per_cpu(hrtimer_is_active, cpu)) {
		gator_interface *i;
		struct hrtimer *hrtimer = &per_cpu(percpu_hrtimer, cpu);
		hrtimer_cancel(hrtimer);
		per_cpu(hrtimer_is_active, cpu) = 0;
		gator_buffer_commit(cpu);

		// offline any events
		for (i = gi; i != NULL; i = i->next) {
			if (i->offline) {
				i->offline();
			}
		}
	}
}

static void gator_timer_offline(void)
{
	if (hrtimer_running) {
		hrtimer_running = 0;

		on_each_cpu(__gator_timer_offline, NULL, 1);

		// output a final sync point
		gator_buffer_write_packed_int(0, PROTOCOL_CPU_SYNC);
		gator_buffer_commit(0);
	}
}

static void __gator_timer_online(void *unused)
{
	int cpu = smp_processor_id();
	if (!per_cpu(hrtimer_is_active, cpu)) {
		gator_interface *i;
		struct hrtimer *hrtimer = &per_cpu(percpu_hrtimer, cpu);
		hrtimer_init(hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
		hrtimer->function = gator_hrtimer_notify;
		hrtimer_start(hrtimer, profiling_interval, HRTIMER_MODE_REL_PINNED);
		per_cpu(gator_cpu_tick, cpu) = 0;
		per_cpu(gator_first_time, cpu) = 1;
		per_cpu(hrtimer_is_active, cpu) = 1;

		// online any events
		for (i = gi; i != NULL; i = i->next) {
			if (i->online) {
				i->online();
			}
		}
	}
}

int gator_timer_online(unsigned long setup)
{
	if (!setup) {
		pr_err("gator: cannot start due to a system tick value of zero");
		return -1;
	} else if (hrtimer_running) {
		pr_notice("gator: high res timer already running");
		return 0;
	}

	hrtimer_running = 1;

	// calculate profiling interval
	profiling_interval = ns_to_ktime(1000000000UL / setup);

	// timer interrupt
	gator_master_tick = 0;
	on_each_cpu(__gator_timer_online, NULL, 1);

	return 0;
}

static uint64_t gator_get_time(void)
{
	struct timespec ts;
	uint64_t timestamp;

	ktime_get_ts(&ts);
	timestamp = timespec_to_ns(&ts);

	return timestamp;
}

/******************************************************************************
 * cpu online notifier
 ******************************************************************************/
static int __cpuinit gator_cpu_notify(struct notifier_block *self,
											unsigned long action, void *hcpu)
{
	long cpu = (long)hcpu;

	switch (action) {
		case CPU_ONLINE:
		case CPU_ONLINE_FROZEN:
			smp_call_function_single(cpu, __gator_timer_online, NULL, 1);
			break;
		case CPU_DOWN_PREPARE:
		case CPU_DOWN_PREPARE_FROZEN:
			smp_call_function_single(cpu, __gator_timer_offline, NULL, 1);
			break;
	}

	return NOTIFY_OK;
}

static struct notifier_block __refdata gator_cpu_notifier = {
	.notifier_call = gator_cpu_notify,
};

static int gator_notifier_start(void)
{
	return register_hotcpu_notifier(&gator_cpu_notifier);
}

static void gator_notifier_stop(void)
{
	unregister_hotcpu_notifier(&gator_cpu_notifier);
}

/******************************************************************************
 * Main
 ******************************************************************************/
int gator_event_install(int (*event_install)(gator_interface *))
{
	gator_interface *ni = (gator_interface*)kmalloc(sizeof(gator_interface), GFP_KERNEL);
	if (ni == NULL) {
		return -1;
	}

	ni->create_files = NULL;
	ni->init = NULL;
	ni->start = NULL;
	ni->stop = NULL;
	ni->online = NULL;
	ni->offline = NULL;
	ni->read = NULL;
	ni->next = NULL;

	// Initialize ni gator interface
	if (!event_install(ni)) {
		if (gi == NULL) {
			// Set gi to point to the first gator interface
			gi = ni;
		} else {
			// Link the gator interfaces
			gator_interface *i = gi;
			while (i->next) {
				i = i->next;
			}
			i->next = ni;
		}
	} else {
		kfree(ni);
	}

	return 0;
}

static int gator_init(void)
{
	gator_interface *i;
	int key = 0;

	if (gator_timer_init())
		return -1;
	if (gator_trace_sched_init())
		return -1;
	if (gator_annotate_init())
		return -1;

	// set up gator interface linked list structure
	if (gator_events_install())
		return -1;

	// initialize all events
	for (i = gi; i != NULL; i = i->next) {
		if (i->init) {
			if (i->init(&key)) {
				return -1;
			}
		}
	}

	return 0;
}

static int gator_start(void)
{
	gator_interface *i, *f;

	// start all events
	for (i = gi; i != NULL; i = i->next) {
		if (i->start) {
			if (i->start()) {
				goto events_failure;
			}
		}
	}

	if (gator_annotate_start())
		goto annotate_failure;
	if (gator_trace_sched_start())
		goto sched_failure;
	if (gator_timer_online(gator_timer_count))
		goto timer_failure;
	if (gator_notifier_start())
		goto notifier_failure;

	return 0;

notifier_failure:
	gator_timer_offline();
timer_failure:
	gator_trace_sched_stop();
sched_failure:
	gator_annotate_stop();
annotate_failure:
events_failure:
	for (f = gi; f != i; f = f->next) {
		f->stop();
	}

	return -1;
}

static void gator_stop(void)
{
	gator_interface *i;

	// stop all events
	for (i = gi; i != NULL; i = i->next) {
		if (i->stop) {
			i->stop();
		}
	}

	gator_annotate_stop();
	gator_trace_sched_stop();

	// stop all interrupt callback reads before tearing down other interfaces
	gator_timer_offline();
	gator_notifier_stop();
}

static void gator_exit(void)
{
	gator_interface *i = gi;

	while (i) {
		gator_interface *p = i;
		i = i->next;
		kfree(p);
	}
}

/******************************************************************************
 * Filesystem
 ******************************************************************************/
/* fopen("buffer") */
static int gator_op_setup(void)
{
	int err = 0;
	int cpu;

	mutex_lock(&start_mutex);

	use_buffer_size = gator_buffer_size;
	use_buffer_mask = use_buffer_size - 1;

	// must be a power of 2
	if (use_buffer_size & (use_buffer_size - 1)) {
		err = -ENOEXEC;
		goto setup_error;
	}

	gator_net_traffic = 0;

	gator_commit_read = gator_commit_write = 0;
	gator_commit = vmalloc(COMMIT_SIZE * sizeof(int));
	if (!gator_commit) {
		err = -ENOMEM;
		goto setup_error;
	}

	for_each_present_cpu(cpu) {
		per_cpu(use_buffer, cpu) = vmalloc(use_buffer_size);
		if (!per_cpu(use_buffer, cpu)) {
			err = -ENOMEM;
			goto setup_error;
		}

		per_cpu(gator_cpu_sync, cpu) = 0;
		per_cpu(gator_cpu_tick, cpu) = 0;

		per_cpu(use_buffer_seq, cpu) = 0;
		per_cpu(use_buffer_read, cpu) = 0;
		per_cpu(use_buffer_write, cpu) = 0;
		gator_buffer_header(cpu);
	}

setup_error:
	mutex_unlock(&start_mutex);
	return err;
}

/* Actually start profiling (echo 1>/dev/gator/enable) */
static int gator_op_start(void)
{
	int err = 0;

	mutex_lock(&start_mutex);

	if (gator_started || gator_start() || cookies_initialize())
		err = -EINVAL;
	else
		gator_started = 1;

	mutex_unlock(&start_mutex);

	return err;
}

/* echo 0>/dev/gator/enable */
static void gator_op_stop(void)
{
	mutex_lock(&start_mutex);

	if (gator_started) {
		gator_stop();

		mutex_lock(&gator_buffer_mutex);

		gator_started = 0;
		cookies_release();
		wake_up(&gator_buffer_wait);

		mutex_unlock(&gator_buffer_mutex);
	}

	mutex_unlock(&start_mutex);
}

static void gator_shutdown(void)
{
	int cpu;

	mutex_lock(&start_mutex);

	vfree(gator_commit);
	gator_commit = NULL;

	for_each_present_cpu(cpu) {
		mutex_lock(&gator_buffer_mutex);
		vfree(per_cpu(use_buffer, cpu));
		per_cpu(use_buffer, cpu) = NULL;
		per_cpu(use_buffer_seq, cpu) = 0;
		per_cpu(use_buffer_read, cpu) = 0;
		per_cpu(use_buffer_write, cpu) = 0;
		mutex_unlock(&gator_buffer_mutex);
	}

	mutex_unlock(&start_mutex);
}

static int gator_set_backtrace(unsigned long val)
{
	int err = 0;

	mutex_lock(&start_mutex);

	if (gator_started)
		err = -EBUSY;
	else
		gator_backtrace_depth = val;

	mutex_unlock(&start_mutex);

	return err;
}

static ssize_t enable_read(struct file *file, char __user *buf, size_t count, loff_t *offset)
{
	return gatorfs_ulong_to_user(gator_started, buf, count, offset);
}

static ssize_t enable_write(struct file *file, char const __user *buf, size_t count, loff_t *offset)
{
	unsigned long val;
	int retval;

	if (*offset)
		return -EINVAL;

	retval = gatorfs_ulong_from_user(&val, buf, count);
	if (retval)
		return retval;

	if (val)
		retval = gator_op_start();
	else
		gator_op_stop();

	if (retval)
		return retval;
	return count;
}

static const struct file_operations enable_fops = {
	.read		= enable_read,
	.write		= enable_write,
};

static int event_buffer_open(struct inode *inode, struct file *file)
{
	int err = -EPERM;

	if (!capable(CAP_SYS_ADMIN))
		return -EPERM;

	if (test_and_set_bit_lock(0, &gator_buffer_opened))
		return -EBUSY;

	if ((err = gator_op_setup()))
		goto fail;

	/* NB: the actual start happens from userspace
	 * echo 1 >/dev/gator/enable
	 */

	return 0;

fail:
	__clear_bit_unlock(0, &gator_buffer_opened);
	return err;
}

static int event_buffer_release(struct inode *inode, struct file *file)
{
	gator_op_stop();
	gator_shutdown();
	__clear_bit_unlock(0, &gator_buffer_opened);
	return 0;
}

static ssize_t event_buffer_read(struct file *file, char __user *buf,
				 size_t count, loff_t *offset)
{
	int retval = -EINVAL;
	int commit, length1, length2, read;
	char *buffer1, *buffer2;
	int cpu;

	/* do not handle partial reads */
	if (count != use_buffer_size || *offset)
		return -EINVAL;

	// sleep until the condition is true or a signal is received
	// the condition is checked each time gator_buffer_wait is woken up
	wait_event_interruptible(gator_buffer_wait, buffer_commit_ready() || !gator_started);

	if (signal_pending(current))
		return -EINTR;

	if (!buffer_commit_ready())
		return 0;

	buffer_commit_read(&cpu, &read, &commit);

	mutex_lock(&gator_buffer_mutex);

	retval = -EFAULT;

	/* May happen if the buffer is freed during pending reads. */
	if (!per_cpu(use_buffer, cpu)) {
		retval = -EFAULT;
		goto out;
	}

	/* determine the size of two halves */
	length1 = commit - read;
	length2 = 0;
	buffer1 = &(per_cpu(use_buffer, cpu)[read]);
	buffer2 = &(per_cpu(use_buffer, cpu)[0]);
	if (length1 < 0) {
		length1 = use_buffer_size - read;
		length2 = commit;
	}

	/* start, middle or end */
	if (length1 > 0) {
		if (copy_to_user(&buf[0], buffer1, length1)) {
			goto out;
		}
	}

	/* possible wrap around */
	if (length2 > 0) {
		if (copy_to_user(&buf[length1], buffer2, length2)) {
			goto out;
		}
	}

	retval = length1 + length2;

	/* kick just in case we've lost an SMP event */
	wake_up(&gator_buffer_wait);

out:
	// do not adjust network stats if in non-streaming buffer mode
	if (gator_sync_freq)
		gator_net_traffic += retval;
	mutex_unlock(&gator_buffer_mutex);
	return retval;
}

const struct file_operations gator_event_buffer_fops = {
	.open		= event_buffer_open,
	.release	= event_buffer_release,
	.read		= event_buffer_read,
};

static ssize_t depth_read(struct file *file, char __user *buf, size_t count, loff_t *offset)
{
	return gatorfs_ulong_to_user(gator_backtrace_depth, buf, count,
					offset);
}

static ssize_t depth_write(struct file *file, char const __user *buf, size_t count, loff_t *offset)
{
	unsigned long val;
	int retval;

	if (*offset)
		return -EINVAL;

	retval = gatorfs_ulong_from_user(&val, buf, count);
	if (retval)
		return retval;

	retval = gator_set_backtrace(val);

	if (retval)
		return retval;
	return count;
}

static const struct file_operations depth_fops = {
	.read		= depth_read,
	.write		= depth_write
};

static const char gator_cpu_type[] = "gator";

static ssize_t cpu_type_read(struct file *file, char __user *buf, size_t count, loff_t *offset)
{
	return gatorfs_str_to_user(gator_cpu_type, buf, count, offset);
}

static const struct file_operations cpu_type_fops = {
	.read		= cpu_type_read,
};

void gator_op_create_files(struct super_block *sb, struct dentry *root)
{
	struct dentry *dir;
	gator_interface *i;
	int cpu;

	/* reinitialize default values */
	gator_cpu_cores = 0;
	for_each_present_cpu(cpu) {
		gator_cpu_cores++;
	}
	gator_buffer_size =	BUFFER_SIZE_DEFAULT;
	gator_sync_freq = SYNC_FREQ_DEFAULT;

	gatorfs_create_file(sb, root, "enable", &enable_fops);
	gatorfs_create_file(sb, root, "buffer", &gator_event_buffer_fops);
	gatorfs_create_file(sb, root, "backtrace_depth", &depth_fops);
	gatorfs_create_file(sb, root, "cpu_type", &cpu_type_fops);
	gatorfs_create_ulong(sb, root, "cpu_cores", &gator_cpu_cores);
	gatorfs_create_ulong(sb, root, "buffer_size", &gator_buffer_size);
	gatorfs_create_ulong(sb, root, "tick", &gator_timer_count);
	gatorfs_create_ulong(sb, root, "sync_freq", &gator_sync_freq);
	gatorfs_create_ro_ulong(sb, root, "version", &gator_protocol_version);

	// Annotate interface
	gator_annotate_create_files(sb, root);

	// Linux Events
	dir = gatorfs_mkdir(sb, root, "events");
	for (i = gi; i != NULL; i = i->next) {
		if (i->create_files) {
			i->create_files(sb, dir);
		}
	}
}

/******************************************************************************
 * Module
 ******************************************************************************/
static int gator_initialized;

static int __init gator_module_init(void)
{
	if (gatorfs_register()) {
		return -1;
	}

	if (gator_init()) {
		gatorfs_unregister();
		return -1;
	}

	gator_initialized = 1;
#ifdef GATOR_DEBUG
	pr_err("gator_module_init");
#endif
	return 0;
}

static void __exit gator_module_exit(void)
{
#ifdef GATOR_DEBUG
	pr_err("gator_module_exit");
#endif
	tracepoint_synchronize_unregister();
	gatorfs_unregister();
	if (gator_initialized) {
		gator_initialized = 0;
		gator_exit();
	}
}

module_init(gator_module_init);
module_exit(gator_module_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("ARM Ltd");
MODULE_DESCRIPTION("Gator system profiler");