forked from TACC/ooops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrapper.c
1353 lines (1086 loc) · 38.7 KB
/
wrapper.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
/*************************************************************************
--------------------------------------------------------------------------
-- ooops License
--------------------------------------------------------------------------
--
-- ooops is licensed under the terms of the MIT license reproduced below.
-- This means that ooops is free software and can be used for both academic
-- and commercial purposes at absolutely no cost.
--
-- ----------------------------------------------------------------------
--
-- Copyright (C) 2018-2019 Lei Huang
--
-- Permission is hereby granted, free of charge, to any person obtaining
-- a copy of this software and associated documentation files (the
-- "Software"), to deal in the Software without restriction, including
-- without limitation the rights to use, copy, modify, merge, publish,
-- distribute, sublicense, and/or sell copies of the Software, and to
-- permit persons to whom the Software is furnished to do so, subject
-- to the following conditions:
--
-- The above copyright notice and this permission notice shall be
-- included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
-- BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
--------------------------------------------------------------------------
*************************************************************************/
// To compile,
// gcc -O2 -fPIC -shared -o wrapper.so wrapper.c -lrt -ldl
#include <stdio.h>
#include <execinfo.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <sys/stat.h>
#include <malloc.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <errno.h>
#include <elf.h>
#include <stdarg.h>
#define __USE_GNU
#define _GNU_SOURCE
#include <dlfcn.h>
#include <link.h>
#include <fcntl.h>
#define PTHREAD_MUTEXATTR_FLAG_PSHARED (0x80000000) // int
#define MAX_FS_SERVER (8) // max number of distinct file system server to be tracked.
#define MAX_REC (512) // number of record of file IO API call time stampe
#define MAX_REC_M ( (MAX_REC) - 1)
#define max(a,b) ( ( (a) >= (b) ) ? (a) : (b) )
#define MAX_LEN_FS_NAME (16)
#define MAX_FUNC (4) // We are using only two right now for open() and stat().
#define MAX_PATCH (16) // the max number of patches will be applied in glibc
#define CMDLINE_LEN (2048)
static int size_pt_mutex_t=0;
static int n_fs_server=0;
static char szFSTag[MAX_FS_SERVER][256];
static int FS_Tag[MAX_FS_SERVER];
static int FS_Tag_Len[MAX_FS_SERVER];
static unsigned long int img_libc_base=0, img_libpthread_base=0;
static unsigned long page_size, filter;
static int Inited=0;
static float freq;
static int IsLibpthreadLoaded=0;
static char szPathLibc[128]="";
static char szPathLibpthread[128];
static int func_addr[4], func_len[3];
static long int query_open_addr=0;
typedef struct{
long int base_addr, patch_addr;
int org_value;
}PATCH_REC;
static int nPatch=0; // the number of patches in glibc
PATCH_REC PatchList[MAX_PATCH];
static void Read_Config(void);
static void Get_Exe_Name(int pid, char szName[]);
static void Uninstall_Patches(void);
static void Take_a_Short_Nap(int nsec);
__thread char szUpdatedDir[2048];
static int Shm_Ready=0;
static int Limit_IO_Debug=0;
static struct timespec linux_rate;
__thread int Idx_fs_Server, Idx_fs_Server_CWD;
__thread uint64_t t_list[MAX_FS_SERVER][MAX_FUNC];
static uint64_t CallCount[MAX_FS_SERVER][MAX_FUNC];
static uint64_t nCallOpenDelayed[MAX_FS_SERVER], nCallStatDelayed[MAX_FS_SERVER];
struct elt {
int next, value, key;
};
struct dict {
int size; /* size of the pointer table */
int n; /* number of elements stored */
};
typedef struct dict *Dict;
#define HASH_TABLE_SIZE (512)
static void DictCreate(Dict d, int nSize, struct elt ** p_elt_list, int ** p_ht_table);
static void DictInsert(Dict d, int key, const int value, struct elt ** p_elt_list, int ** p_ht_table);
static int DictSearch(Dict d, int key, struct elt ** p_elt_list, int ** p_ht_table);
// sizeof(struct dict) + sizeof(int)*(d->size) + sizeof(struct elt)*(d->size)
static int hashint(int a)
{
a = a ^ (a>>4);
a = (a^0xdeadbeef) + (a<<5);
a = a ^ (a>>11);
return a;
}
void Init_Pointers(Dict d, struct elt ** p_elt_list, int ** p_ht_table)
{
*p_ht_table = (int *)((void *)d + sizeof(struct dict));
*p_elt_list = (struct elt *)((void *)d + sizeof(struct dict) + sizeof(int)*(d->size));
}
static void DictCreate(Dict d, int nSize, struct elt ** p_elt_list, int ** p_ht_table)
{
int i;
if(d == NULL) {
printf("d = NULL.\nThe memory for hash table is not allocated.\nQuit\n");
exit(1);
}
if(nSize) {
if(nSize) {
d->size = nSize;
}
d->n = 0;
}
Init_Pointers(d, p_elt_list, p_ht_table);
if(nSize) for(i = 0; i < d->size; i++) (*p_ht_table)[i] = -1;
}
// insert a new key-value pair into an existing dictionary
static void DictInsert(Dict d, int key, const int value, struct elt ** p_elt_list, int ** p_ht_table)
{
struct elt *e;
int h;
e = &( (*p_elt_list)[d->n]);
e->key = key;
e->value = value;
h = hashint(key) % HASH_TABLE_SIZE;
e->next = (*p_ht_table)[h];
(*p_ht_table)[h] = d->n;
d->n++;
}
static int DictSearch(Dict d, int key, struct elt ** p_elt_list, int ** p_ht_table)
{
int idx;
struct elt *e;
if(d->n == 0) return (-1);
idx = (*p_ht_table)[hashint(key) % HASH_TABLE_SIZE];
if(idx == -1) {
return (-1);
}
e = &( (*p_elt_list)[idx] );
while(1) {
if(e->key == key) {
return idx;
}
else {
idx = e->next;
if(idx == -1) { // end
return (-1);
}
e = &( (*p_elt_list)[idx] );
}
}
return -1;
}
static void Find_Func_Addr(void);
static float Get_Freq(void);
static void Update_CWD(void);
static void Check_FS_Server(char *szName); // return the index of FS server
static void GetTime(int idx);
static void Update_open_Count(int IdxFunc);
inline void pre_lxstat(void);
static void post_lxstat(void);
inline unsigned long int rdtscp(void);
typedef int (*org_chdir)(const char *path);
static org_chdir real_chdir=NULL;
typedef int (*org_open)(const char *pathname, int oflags,...);
static org_open real_open=NULL;
int chdir(const char *path)
{
int ret;
if(real_chdir) {
ret = real_chdir(path);
}
else {
real_chdir = (org_chdir)dlsym(RTLD_NEXT, "chdir");
ret = real_chdir(path);
}
Update_CWD();
return ret;
}
__thread int tid=-1;
typedef struct {
double dT_Open_Avg[MAX_FS_SERVER], dT_Stat_Avg[MAX_FS_SERVER];
double n_Open_Task[MAX_FS_SERVER], n_Stat_Task[MAX_FS_SERVER];
double dT_To_Sleep_in_Open[MAX_FS_SERVER], dT_To_Sleep_in_Stat[MAX_FS_SERVER];
}DATA_SLEEP, *PDATA_SLEEP;
//start waper related data and functions
static int Active=1;
static uint64_t t_Updated_Param=0;
static float Max_open_Freq[MAX_FS_SERVER];
static float Max_lxstat_Freq[MAX_FS_SERVER];
static float t_threshold_open[MAX_FS_SERVER];
static float t_threshold_lxstat[MAX_FS_SERVER];
static uint64_t t_threshold_open_int64[MAX_FS_SERVER];
static uint64_t t_threshold_lxstat_int64[MAX_FS_SERVER];
static uint64_t *p_Param_Mem_Ready=NULL;
static uint64_t *p_Disabled=NULL;
static uint64_t *p_t_Updated_Param=NULL;
static uint64_t *p_t_threshold_open_int64=NULL;
static uint64_t *p_t_threshold_lxstat_int64=NULL;
static int *p_tid_Open_List[MAX_FS_SERVER]; // tid list
static int *p_tid_Stat_List[MAX_FS_SERVER]; // tid list
static int shm_dT_fd;
static void *p_dT_shm=NULL; // ptr to shared memory
static int nSize_Shared_dT_Data=0;
DATA_SLEEP *p_Data_Sleep;
static float *p_param_freq=NULL; // freq
static int *p_param_func_addr=NULL; // beginning address of four functions
static int *p_param_func_len=NULL; // lengths of three functions
static char *p_FS_Tag_List[MAX_FS_SERVER]; // 16 bytes per record
static int *p_FS_Tag_Len;
static float *p_Max_open_Freq_Share=NULL;
static float *p_Max_lxstat_Freq_Share=NULL;
static int shm_param_fd; // fd for mutex
static void *p_param_shm=NULL; // ptr to shared memory
static int nSize_Shared_Param_Data=0;// the number of bytes of shared data
static void Update_Parameters(void); // update parameters from share memory area
static void Publish_Parameters(void); // upload parameters to shared memory area
static struct timespec tim1, tim2;
static void *p_shm=NULL; // ptr to shared memory
static pthread_mutex_t *p_futex_open=NULL; // ptr for pthread_mutex_t
static pthread_mutex_t *p_futex_lxstat=NULL; // ptr for pthread_mutex_t
static int *p_open_Count[MAX_FS_SERVER];
static int *p_lxstat_Count[MAX_FS_SERVER];
static int64_t *p_dT_list_open[MAX_FS_SERVER]; // the pointor to list of time stampes
static int64_t *p_dT_list_lxstat[MAX_FS_SERVER]; // the pointor to list of time stampes
static char mutex_name[64];
static int uid;
static int shm_fd; // fd for mutex
static int nSize_Shared_Data=0;// the number of bytes of shared data
static void Init_Shared_Mutex(void);
static void Close_Shared_Mutex(void);
inline void pre_lxstat(void)
{
if(Idx_fs_Server < 0) return; // not interested files. e.g., local disk I/O
t_list[Idx_fs_Server][1] = rdtscp(); // get time now
return;
}
inline unsigned long int rdtscp(void)
{
unsigned long int rax, rdx;
asm volatile ( "rdtscp\n" : "=a" (rax), "=d" (rdx) : : );
return (rdx << 32) + rax;
}
static void Update_CWD(void) // keep currect working directory updated!!!
{
int i;
if(getcwd(szUpdatedDir, 512) == NULL) {
printf("The size of szUpdatedDir needs to be increased.\nQuit\n");
}
Idx_fs_Server_CWD = -1;
for(i=0; i<n_fs_server; i++) { // check file name path
if( strncmp(szUpdatedDir, szFSTag[i], FS_Tag_Len[i]) == 0 ) {
Idx_fs_Server_CWD = i;
break;
}
}
// printf("Idx_fs_Server_CWD = %d\n", Idx_fs_Server_CWD);
}
static void Patch_Function_Call(void *func_addr, int size, int func_dist, int offset)
{
unsigned char *pbase, *p;
int i, p_addr_call, *p_int;
pbase = (unsigned char *)( ( (unsigned long)func_addr ) & filter ); // fast mod
if(mprotect(pbase, 0x2000, PROT_READ | PROT_WRITE | PROT_EXEC) != 0) { // two pages to make sure the code works when the modified code is around page boundary
printf("Error in executing mprotect().\n");
exit(1);
}
p = (unsigned char *)func_addr;
for(i=0; i<size; i++) {
if(p[i] == 0xE8) {
p_int = (int *)(p + i + 1);
p_addr_call = ( *p_int & 0xFFFFFFFF) + i + 5;
if(p_addr_call == func_dist) {
PatchList[nPatch].base_addr = (long int)pbase;
PatchList[nPatch].patch_addr = (long int)p_int;
PatchList[nPatch].org_value = *p_int;
nPatch++; // ????????????????????
*p_int = *p_int + offset;
// printf("Modified libc at: %p\n", p+i);
}
}
}
if(mprotect(pbase, 0x2000, PROT_READ | PROT_EXEC) != 0) { // two pages to make sure the code works when the modified code is around page boundary
printf("Error in executing mprotect().\n");
exit(1);
}
}
static void Patch_open_calls_in_libc(void)
{
int offset;
long int p_addr_call, addr_open, dist;
addr_open = query_open_addr;
if(IsLibpthreadLoaded) { // ~37 us
void *module;
module = dlopen(szPathLibpthread, RTLD_LAZY);
if(module == NULL) {
printf("Fail to dlopen: %s.\n", szPathLibpthread);
return;
}
real_open = (org_open)dlsym(module, "open64"); // open64 in libpthread will be called if applicable.
dlclose(module);
}
dist = abs(addr_open - (long int)open);
if(dist >= 0x80000000) {
printf("The distance between wrapper.so and libc.so is too far! Limit_IO will NOT work for C++ code.\n");
// exit(1);
}
else {
offset = (int)((long int)open - addr_open);
Patch_Function_Call( (void *)(addr_open + func_addr[1] - func_addr[0]), func_len[1], func_addr[0] - func_addr[1], offset);
Patch_Function_Call( (void *)(addr_open + func_addr[2] - func_addr[0]), func_len[2], func_addr[0] - func_addr[2], offset);
}
}
static int callback(struct dl_phdr_info *info, size_t size, void *data)
{
if(strstr(info->dlpi_name, "/libc.so")) {
strcpy(szPathLibc, info->dlpi_name);
// printf("Host: %s, %s\n", szHostName, szPathLibc);
img_libc_base = (info->dlpi_addr + info->dlpi_phdr[0].p_vaddr) & filter;
}
else if(strstr(info->dlpi_name, "/libpthread.so")) {
strcpy(szPathLibpthread, info->dlpi_name);
IsLibpthreadLoaded = 1;
img_libpthread_base = (info->dlpi_addr + info->dlpi_phdr[0].p_vaddr) & filter;
// printf("Host: %s, %s\n", szHostName, szPathLibpthread);
}
return 0;
}
#define MAX_LEN_CONFIG (8192)
#define MAX_NUM_CONFIG (4)
#define N_ITEM_PER_REC (10)
#pragma GCC push_options
#pragma GCC optimize ("-O0")
static void Read_Config(void)
{
int fd, i, Config_Use=-1;
char szBuff[MAX_LEN_CONFIG], *p, *p_Use;
int num_read, nReadItem;
float freq_list[MAX_NUM_CONFIG], f, f_Use=0.0f, f_Sys, df, df_Min=10.0;
char *szConfigName;
int nConfig=0, PosList[MAX_NUM_CONFIG*2];
int Tag_Start=0x6572663C, Tag_End=0x72662F3C; // "<fre" and "</fr"
char szItems[60][64]; // parameters
int nParam, Offset;
char szKey[128]="", szLen[8];
int NAME_TAG_LEN=16;
long int lKey=0;
char szHostNameShort[64], szHostName[128];
n_fs_server = 0;
for(i=0; i<MAX_FS_SERVER; i++) {
Max_open_Freq[i] = 60000.0; // set as a large number
Max_lxstat_Freq[i] = 60000.0; // set as a large number
}
szConfigName=getenv("IO_LIMIT_CONFIG");
if(szConfigName == NULL) {
return;
}
freq = Get_Freq(); // ~260 us
f_Sys = freq * 0.000000001; // GHz
fd = open(szConfigName, O_RDONLY, 0);
if(fd == -1) {
printf("Fail to open file: %s\n", szConfigName);
return;
}
num_read = read(fd, szBuff, MAX_LEN_CONFIG);
close(fd);
p = szBuff;
i=0;
while(i<num_read) {
if( (*( (int*)(p+i)) == Tag_Start) || (*( (int*)(p+i)) == Tag_End) ) {
PosList[nConfig] = i;
nConfig++;
}
i++;
}
for(i=0; i<nConfig; i+=2) { // find the closest frequency.
nReadItem = sscanf(szBuff + PosList[i] + 6, "%f", &f);
if(nReadItem == 1) {
freq_list[i>>1] = f;
df = (f > f_Sys) ? (f - f_Sys) : (f_Sys - f);
if( df < df_Min) {
df_Min = df;
f_Use = f;
Config_Use = i;
}
}
}
p_Use = szBuff + PosList[Config_Use] + 6;
while(1) {
if(*p_Use == 0xA) { // new line. Find the beginning of real parameter region
p_Use = p_Use + 1;
break;
}
p_Use = p_Use + 1;
}
szBuff[PosList[Config_Use + 1] - 1] = 0; // Find the end of parameter region
nParam = sscanf(p_Use, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
szItems[0], szItems[1], szItems[2], szItems[3], szItems[4], szItems[5], szItems[6], szItems[7], szItems[8], szItems[9],
szItems[10], szItems[11], szItems[12], szItems[13], szItems[14], szItems[15], szItems[16], szItems[17], szItems[18], szItems[19],
szItems[20], szItems[21], szItems[22], szItems[23], szItems[24], szItems[25], szItems[26], szItems[27], szItems[28], szItems[29],
szItems[30], szItems[31], szItems[32], szItems[33], szItems[34], szItems[35], szItems[36], szItems[37], szItems[38], szItems[39]);
n_fs_server = nParam / N_ITEM_PER_REC;
for(i=0; i<n_fs_server; i++) {
Offset = N_ITEM_PER_REC*i;
strcpy(szFSTag[i], szItems[Offset+1]);
FS_Tag_Len[i] = strlen(szFSTag[i]);
FS_Tag_Len[i] = (FS_Tag_Len[i] >= MAX_LEN_FS_NAME) ? (MAX_LEN_FS_NAME-1) : (FS_Tag_Len[i]);
t_threshold_open[i] = atof(szItems[Offset+3]);
Max_open_Freq[i] = atof(szItems[Offset+5]);
t_threshold_lxstat[i] = atof(szItems[Offset+7]);
Max_lxstat_Freq[i] = atof(szItems[Offset+9]);
if(Limit_IO_Debug) printf("Server %d: (%6.2f, %5.1f, %6.2f, %5.1f) on %s\n",
i, t_threshold_open[i], Max_open_Freq[i], t_threshold_lxstat[i], Max_lxstat_Freq[i], szFSTag[i]);
t_threshold_open[i] = t_threshold_open[i] * 0.000001 * freq; // tick number
t_threshold_lxstat[i] = t_threshold_lxstat[i] * 0.000001 * freq; // tick number
t_threshold_open_int64[i] = (uint64_t)t_threshold_open[i];
t_threshold_lxstat_int64[i] = (uint64_t)t_threshold_lxstat[i];
}
return;
}
#pragma GCC pop_options
static void Find_Func_Addr(void)
{
int fd, i, count=0;
struct stat file_stat;
void *map_start;
Elf64_Sym *symtab;
Elf64_Ehdr *header;
Elf64_Shdr *sections;
int strtab_offset=0;
void *pSymbBase=NULL;
int nSym=0, SymRecSize=0, SymOffset, RecAddr;
char *szSymName;
char szFunc_List[3][24]={"open64", "_IO_file_open", "_IO_file_fopen"};
stat(szPathLibc, &file_stat);
// printf("Size = %zu\n", file_stat.st_size);
fd = open(szPathLibc, O_RDONLY);
map_start = mmap(0, file_stat.st_size, PROT_READ, MAP_SHARED, fd, 0);
header = (Elf64_Ehdr *) map_start;
sections = (Elf64_Shdr *)((char *)map_start + header->e_shoff);
for (i = 0; i < header->e_shnum; i++) {
if ( (sections[i].sh_type == SHT_STRTAB) ) {
strtab_offset = (int)(sections[i].sh_offset);
break;
}
}
for (i = 0; i < header->e_shnum; i++) {
if ( (sections[i].sh_type == SHT_DYNSYM) || (sections[i].sh_type == SHT_SYMTAB) ) {
pSymbBase = (void*)(sections[i].sh_offset + map_start);
SymRecSize = sections[i].sh_entsize;
nSym = sections[i].sh_size / sections[i].sh_entsize;
break;
}
}
for(i=0; i<nSym; i++) {
RecAddr = SymRecSize*i;
// SymOffset = *( (int *)( pSymbBase + RecAddr ) ) & 0xFFFF;
SymOffset = *( (int *)( pSymbBase + RecAddr ) ) & 0xFFFFFFFF;
szSymName = (char *)( map_start + strtab_offset + SymOffset );
if( strcmp(szSymName, szFunc_List[0])==0 ) { // "open64"
func_addr[0] = *((int *)(pSymbBase + RecAddr + 8));
func_len[0] = *((int *)(pSymbBase + RecAddr + 16));
count++;
query_open_addr = (long int)(img_libc_base + ( (long int)(func_addr[0]) & 0xFFFFFFFF) );
}
else if( strcmp(szSymName, szFunc_List[1])==0 ) { // "_IO_file_open"
func_addr[1] = *((int *)(pSymbBase + RecAddr + 8));
func_len[1] = *((int *)(pSymbBase + RecAddr + 16));
count++;
}
else if( strcmp(szSymName, szFunc_List[2])==0 ) { // "_IO_file_fopen"
func_addr[2] = *((int *)(pSymbBase + RecAddr + 8));
func_len[2] = *((int *)(pSymbBase + RecAddr + 16));
count++;
}
if(count == 3) {
break;
}
}
munmap(map_start, file_stat.st_size);
close(fd);
}
#define N_SAMPLE_FOR_AVG (255)
static double Cal_Avg_dT(uint64_t *p_dT, int Idx)
{
double Mean = 0.0;
uint64_t Sum = 0, Mean_Est;
int i;
for(i=Idx-N_SAMPLE_FOR_AVG; i<=Idx; i++) {
Sum += p_dT[i];
}
Mean_Est = Sum >> 8; // same as Sum/2^8 = Sum / 256
return ((double)(1.0*Mean_Est));
}
static double Cal_Avg_N_IO_TASK(int *p_tid, int Idx)
{
char *p_Buff;
Dict p_Hash;
struct elt *elt_list;
int *ht_table=NULL;
int i, nBytes_Hash_Table, idx_rec, nTasks=0, nTaskMin;
char szExeName[256];
nBytes_Hash_Table = sizeof(struct dict) + sizeof(int)*HASH_TABLE_SIZE + sizeof(struct elt)*HASH_TABLE_SIZE;
p_Buff = malloc(nBytes_Hash_Table);
p_Hash = (struct dict *)p_Buff;
DictCreate(p_Hash, HASH_TABLE_SIZE, &elt_list, &ht_table); // init hash table
for(i=Idx-N_SAMPLE_FOR_AVG; i<=Idx; i++) {
idx_rec = DictSearch(p_Hash, p_tid[i], &elt_list, &ht_table);
if( idx_rec >= 0 ) { // existed
elt_list[idx_rec].value += 1;
}
else { // new key
DictInsert(p_Hash, p_tid[i], 1, &elt_list, &ht_table);
}
}
nTaskMin = (int)(0.8*(N_SAMPLE_FOR_AVG+1)/p_Hash->size);
for(i = 0; i < p_Hash->n; i++) {
if(elt_list[i].value > nTaskMin) {
nTasks++;
}
}
free(p_Buff);
return ((double)(nTasks));
}
static void post_lxstat(void)
{
uint64_t dt, t_New;
int idx_cur, nCall_New;
long int t_ns_Sleep;
if(t_Updated_Param != *p_t_Updated_Param) Update_Parameters();
if(Active == 0) {
return;
}
if( (Idx_fs_Server < 0) || (Shm_Ready == 0) ) return; // not interested files. e.g., local disk I/O
if(tid < 0) {
tid = syscall(SYS_gettid);
}
pthread_mutex_lock(p_futex_lxstat);
CallCount[Idx_fs_Server][1]++;
nCall_New = *(p_lxstat_Count[Idx_fs_Server]);
*(p_lxstat_Count[Idx_fs_Server]) = nCall_New + 1; // update the counter
pthread_mutex_unlock(p_futex_lxstat);
t_New = rdtscp();
dt = t_New - t_list[Idx_fs_Server][1];
// printf("In stat(), p_lxstat_Count = %lld\n", *(p_lxstat_Count[Idx_fs_Server]));
idx_cur = nCall_New & MAX_REC_M; // fast mod
if(tid < 0) {
tid = syscall(SYS_gettid);
}
p_tid_Stat_List[Idx_fs_Server][idx_cur] = tid;
p_dT_list_lxstat[Idx_fs_Server][idx_cur] = dt; // fill in current time stampe. Not used any more!!!
if( (idx_cur == N_SAMPLE_FOR_AVG) || (idx_cur == MAX_REC_M) ) { // update dT_Avg, t_Sleep and n_IO_TASK
p_Data_Sleep->dT_Stat_Avg[Idx_fs_Server] = Cal_Avg_dT(p_dT_list_lxstat[Idx_fs_Server], idx_cur);
p_Data_Sleep->n_Stat_Task[Idx_fs_Server] = Cal_Avg_N_IO_TASK(p_tid_Stat_List[Idx_fs_Server], idx_cur);
p_Data_Sleep->dT_To_Sleep_in_Stat[Idx_fs_Server] = (p_Data_Sleep->n_Stat_Task[Idx_fs_Server] / Max_lxstat_Freq[Idx_fs_Server]) - (p_Data_Sleep->dT_Stat_Avg[Idx_fs_Server] / freq);
// printf("Stat(): %d %lf %4.1lf %lf\n", *(p_lxstat_Count[Idx_fs_Server]), p_Data_Sleep->dT_Stat_Avg[Idx_fs_Server], p_Data_Sleep->n_Stat_Task[Idx_fs_Server], p_Data_Sleep->dT_To_Sleep_in_Stat[Idx_fs_Server]);
}
if( (dt > t_threshold_lxstat_int64[Idx_fs_Server]) || (p_Data_Sleep->dT_To_Sleep_in_Stat[Idx_fs_Server] > 1.0E-7) ) {
t_ns_Sleep = (long int)(1000000000.0*p_Data_Sleep->dT_To_Sleep_in_Stat[Idx_fs_Server]);
tim1.tv_sec = t_ns_Sleep/1000000000;
tim1.tv_nsec = t_ns_Sleep % 1000000000;
nanosleep(&tim1 , &tim2); // please note that nanosleep can NOT sleep precisely with given time. Uncertainty is at the order of tens microseconds.
nCallStatDelayed[Idx_fs_Server] = nCallStatDelayed[Idx_fs_Server] + 1;
}
return;
}
static void Update_open_Count(int IdxFunc)
{
uint64_t dt, t_New;
int idx_cur, nCall_New;
long int t_ns_Sleep;
if(t_Updated_Param != *p_t_Updated_Param) Update_Parameters();
if(Active == 0) {
return;
}
if(Shm_Ready == 0) return;
if(Idx_fs_Server < 0) return;
pthread_mutex_lock(p_futex_open);
nCall_New = *(p_open_Count[Idx_fs_Server]);
*(p_open_Count[Idx_fs_Server]) = nCall_New + 1; // update the counter
CallCount[Idx_fs_Server][IdxFunc]++;
pthread_mutex_unlock(p_futex_open);
t_New = rdtscp();
dt = t_New - t_list[Idx_fs_Server][0];
idx_cur = nCall_New & MAX_REC_M; // fast mod
if(tid < 0) {
tid = syscall(SYS_gettid);
}
p_tid_Open_List[Idx_fs_Server][idx_cur] = tid;
p_dT_list_open[Idx_fs_Server][idx_cur] = dt; // fill in current time stampe. Not used any more!!!
if( (idx_cur == N_SAMPLE_FOR_AVG) || (idx_cur == MAX_REC_M) ) { // update dT_Avg, t_Sleep and n_IO_TASK
p_Data_Sleep->dT_Open_Avg[Idx_fs_Server] = Cal_Avg_dT(p_dT_list_open[Idx_fs_Server], idx_cur);
p_Data_Sleep->n_Open_Task[Idx_fs_Server] = Cal_Avg_N_IO_TASK(p_tid_Open_List[Idx_fs_Server], idx_cur);
p_Data_Sleep->dT_To_Sleep_in_Open[Idx_fs_Server] = (p_Data_Sleep->n_Open_Task[Idx_fs_Server] / Max_open_Freq[Idx_fs_Server]) - (p_Data_Sleep->dT_Open_Avg[Idx_fs_Server] / freq);
// printf("Open(): %d %lf %4.1lf %lf\n", *(p_open_Count[Idx_fs_Server]), p_Data_Sleep->dT_Open_Avg[Idx_fs_Server], p_Data_Sleep->n_Open_Task[Idx_fs_Server], p_Data_Sleep->dT_To_Sleep_in_Open[Idx_fs_Server]);
}
if( (dt > t_threshold_open_int64[Idx_fs_Server]) || (p_Data_Sleep->dT_To_Sleep_in_Open[Idx_fs_Server] > 1.0E-7) ) {
t_ns_Sleep = (long int)(1000000000.0*p_Data_Sleep->dT_To_Sleep_in_Open[Idx_fs_Server]);
tim1.tv_sec = t_ns_Sleep/1000000000;
tim1.tv_nsec = t_ns_Sleep % 1000000000;
nanosleep(&tim1 , &tim2);
nCallOpenDelayed[Idx_fs_Server] = nCallOpenDelayed[Idx_fs_Server] + 1;
}
}
static void GetTime(int idx)
{
int IdxFunc;
if( (Idx_fs_Server < 0) || (n_fs_server < 1) ) return; // not interested files. e.g., local disk I/O
IdxFunc = idx >> 1; // the index of function. IdxFunc = idx/2
if( idx & 0x1 ) { // even number
Update_open_Count(IdxFunc);
}
else {
t_list[Idx_fs_Server][IdxFunc] = rdtscp(); // get current time stamp
}
return;
}
typedef int (*org_lxstat)(int __ver, const char *__filename, struct stat *__stat_buf);
static org_lxstat real_lxstat=NULL;
int lxstat(int __ver, const char *__filename, struct stat *__stat_buf)
{
int ret;
// if(Limit_IO_Debug) printf("DBG: lxstat(), file name = %s\n", __filename);
if(real_lxstat==NULL) {
real_lxstat = (org_lxstat)dlsym(RTLD_NEXT, "__lxstat");
}
if(Inited == 0) { // init() not finished yet
ret = real_lxstat(__ver, __filename, __stat_buf);
return ret;
}
Check_FS_Server((char*)__filename);
pre_lxstat();
ret = real_lxstat(__ver, __filename, __stat_buf);
if(Shm_Ready) post_lxstat();
return ret;
}
extern int __lxstat(int __ver, const char *__filename, struct stat *__stat_buf) __attribute__ ( (alias ("lxstat")) );
extern int __lxstat64(int __ver, const char *__filename, struct stat *__stat_buf) __attribute__ ( (alias ("lxstat")) );
typedef int (*org_xstat)(int __ver, const char *__filename, struct stat *__stat_buf);
static org_xstat real_xstat=NULL;
int xstat(int __ver, const char *__filename, struct stat *__stat_buf)
{
int ret;
// if(Limit_IO_Debug) printf("DBG: xstat(), file name = %s\n", __filename);
if(real_xstat==NULL) {
real_xstat = (org_lxstat)dlsym(RTLD_NEXT, "__xstat");
}
if(Inited == 0) { // init() not finished yet
ret = real_xstat(__ver, __filename, __stat_buf);
return ret;
}
Check_FS_Server((char*)__filename);
pre_lxstat();
ret = real_xstat(__ver, __filename, __stat_buf);
if(Shm_Ready) post_lxstat();
return ret;
}
extern int __xstat(int __ver, const char *__filename, struct stat *__stat_buf) __attribute__ ( (alias ("xstat")) );
extern int __xstat64(int __ver, const char *__filename, struct stat *__stat_buf) __attribute__ ( (alias ("xstat")) );
static void Check_FS_Server(char *szName) // handle everything needed here for open()!
{
int i;
Idx_fs_Server = -1;
for(i=0; i<n_fs_server; i++) { // check file name path. absolute path?
if( strncmp(szName, szFSTag[i], FS_Tag_Len[i]) == 0 ) {
Idx_fs_Server = i;
return;
}
}
if(szName[0] != '/') { // Using relative path. check current working directory.
Idx_fs_Server = Idx_fs_Server_CWD;
}
}
int open(const char *pathname, int oflags, ...)
{
int mode = 0, two_args=1;
int ret, *pFileName=(int*)pathname;
if (oflags & O_CREAT) {
va_list arg;
va_start (arg, oflags);
mode = va_arg (arg, int);
va_end (arg);
two_args=0;
}
// printf("DBG: open(), filename = %s\n", pathname);
if(real_open == NULL) {
real_open = (org_open)dlsym(RTLD_NEXT, "open");
}
if(Inited == 0) { // init() not finished yet
if(two_args) {
ret = real_open(pathname, oflags);
}
else {
ret = real_open(pathname, oflags, mode);
}
return ret;
}
Check_FS_Server((char*)pathname);
GetTime(0);
if(two_args) {
ret = real_open(pathname, oflags);
}
else {
ret = real_open(pathname, oflags, mode);
}
if(Shm_Ready) GetTime(1);
return ret;
}
extern int __open(const char *pathname, int oflags, ...) __attribute__ ( (alias ("open")) );
extern int open64(const char *pathname, int oflags, ...) __attribute__ ( (alias ("open")) );
extern int __open64(const char *pathname, int oflags, ...) __attribute__ ( (alias ("open")) );
static __attribute__((constructor)) void init()
{
char szLogName[256], szEnv[256], *szPath, szCodeName[256], szBuff[256], *szDBG, szExeName[512];
int i, pid;
size_pt_mutex_t = sizeof(pthread_mutex_t);
memset(CallCount, 0, sizeof(uint64_t)*MAX_FUNC*MAX_FS_SERVER);
// freq = Get_Freq(); // ~260 us
uid = getuid(); // ~ 10 us
pid = getpid();
Get_Exe_Name(pid, szExeName);
if(strcmp(szExeName, "ssh")==0) {
return;
}
if(getcwd(szUpdatedDir, 512) == NULL) {
printf("The size of szUpdatedDir needs to be increased.\nQuit\n");
}
szDBG = getenv("LIMIT_IO_DEBUG");
if(szDBG == NULL) {
Limit_IO_Debug = 0;
}
else {
Limit_IO_Debug = atoi(szDBG);
}
page_size = sysconf(_SC_PAGESIZE);
filter = ~(page_size - 1);
dl_iterate_phdr(callback, NULL); // get library full path. ~44 us
Init_Shared_Mutex(); // shared memory are ready! ~470 us.
Update_CWD();
for(i=0; i<MAX_FS_SERVER; i++) {
nCallOpenDelayed[i] = 0;
nCallStatDelayed[i] = 0;
}
int *p_mutex_attr;
pthread_mutexattr_t mattr;
p_mutex_attr = (int *)(&mattr);
*p_mutex_attr = PTHREAD_MUTEXATTR_FLAG_PSHARED; // PTHREAD_PROCESS_SHARED !!!!!!!!!!!!!!! Shared between processes
pthread_mutex_init(p_futex_open, &mattr);
pthread_mutex_init(p_futex_lxstat, &mattr);
Patch_open_calls_in_libc();
Shm_Ready = 1;
Inited = 1;
}
static __attribute__((destructor)) void finalize()
{
int i;
if(! Inited) return;
if(Limit_IO_Debug) {
for(i=0; i<n_fs_server; i++) {
printf("FS %-10s open_count = %6lld delayed_open_count = %6lld Accum_open_count = %6d lxstat_count = %6lld delayed_lxstat_count = %6lld Accum_lxstat_count = %6d\n",
szFSTag[i], CallCount[i][0], nCallOpenDelayed[i], *(p_open_Count[i]), CallCount[i][1], nCallStatDelayed[i], *(p_lxstat_Count[i]));
}
}
fflush(stdout);
Close_Shared_Mutex();
Uninstall_Patches();
}
#define BUFF_SIZE (160)