forked from lanl/coNCePTuaL
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogfilefuncs.c
3340 lines (2879 loc) · 118 KB
/
logfilefuncs.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
/* ----------------------------------------------------------------------
*
* coNCePTuaL run-time library:
* functions for manipulating log files
*
* By Scott Pakin <[email protected]>
*
* ----------------------------------------------------------------------
*
*
* Copyright (C) 2015, Los Alamos National Security, LLC
* All rights reserved.
*
* Copyright (2015). Los Alamos National Security, LLC. This software
* was produced under U.S. Government contract DE-AC52-06NA25396
* for Los Alamos National Laboratory (LANL), which is operated by
* Los Alamos National Security, LLC (LANS) for the U.S. Department
* of Energy. The U.S. Government has rights to use, reproduce,
* and distribute this software. NEITHER THE GOVERNMENT NOR LANS
* MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY
* FOR THE USE OF THIS SOFTWARE. If software is modified to produce
* derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* Additionally, redistribution and use in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Los Alamos National Security, LLC, Los Alamos
* National Laboratory, the U.S. Government, nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY LANS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LANS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* ----------------------------------------------------------------------
*/
#include "runtimelib.h"
#include "compiler_version.h"
/**********
* Macros *
**********/
/* ASCI Red lacks a realpath() function and a vsnprintf() function. */
#ifndef HAVE_REALPATH
# define realpath(ORIG, RESOLVED) NULL
#endif
#ifndef HAVE_VSNPRINTF
# define vsnprintf(S, N, FMT, AP) vsprintf (S, FMT, AP)
#endif
/* When building under Microsoft Windows with MinGW, "group" and
* "other" file-permission symbols are not defined. Define them here
* as synonyms for "user". When building under Microsoft Windows with
* the Microsoft C compiler, even S_IXUSR is undefined so we define
* that, too, if necessary. */
#ifndef S_IXUSR
# define S_IXUSR 00100
#endif
#ifndef S_IXGRP
# define S_IXGRP S_IXUSR
#endif
#ifndef S_IXOTH
# define S_IXOTH S_IXUSR
#endif
/* MinGW (under Microsoft Windows) doesn't define userID-related
* functions. */
#ifndef HAVE_GETUID
# define getuid() -1
#endif
#ifndef HAVE_GETEUID
# define geteuid() -1
# define getegid() -1
#endif
/* The Microsoft C compiler apparently lacks a definition of ssize_t. */
#ifndef HAVE_SSIZE_T
typedef long ssize_t;
#endif
/* Define strings to specify that we're writing to standard output or
* to an internal string. */
#define STANDARD_OUTPUT_NAME "<standard output>"
#define INTERNAL_STRING_NAME "<internal string>"
/* Define an arbitrary byte increment for resizing the log-contents string. */
#define LOG_CONTENTS_INCREMENT 8192
/*********************
* Type declarations *
*********************/
/* Define a type that describes a single column of a log file. */
typedef struct {
char *description; /* Textual description of a column (NULL=invalid column) */
LOG_AGGREGATE aggregate; /* Aggregate used to summarize the column */
double aggregate_param; /* Additional information specific to certain aggregates */
NCPTL_QUEUE *rawdata; /* Non-aggregated data values */
NCPTL_QUEUE *finaldata; /* Aggregated data values */
} LOG_COLUMN;
/* Define a type representing a {value, tally} pair in a histogram. */
typedef struct {
double value;
uint64_t tally;
} VALUE_TALLY;
/* Define a type for extra key:value pairs to write to the log file as
* comments. */
typedef struct {
char *key; /* Statically allocated string; NULL means "User comment N" */
char *value; /* Dynamically allocated string */
} LOG_COMMENT;
/* Define a type that encapsulates much of the state needed to
* represent a log file's contents. This makes it possible for one
* process to maintain multiple log files concurrently (e.g., in a
* multithreaded backend). */
typedef struct ncptl_log_file_state {
/* Handle to the log file or, alternatively, a string containing the
* text that would have been written to the log file. If logfile is
* NULL, then output is written to log_contents. However, both
* logfile and log_contents can be non-NULL. This occurs if the
* program invokes ncptl_log_get_contents() when output is written
* to logfile. */
FILE *logfile;
char *log_contents;
ncptl_int log_contents_used; /* # of valid bytes in log_contents */
ncptl_int log_contents_allocated; /* # of bytes allocated for log_contents */
/* Name of thie log file */
char *filename;
/* Process rank (PROCESSOR in the coNCePTuaL language) associated
* with this log file */
ncptl_int process_rank;
/* Store a database of key:value pairs written as comments to the
* log-file prologue. */
NCPTL_SET *log_database;
/* Current contents of the log file */
LOG_COLUMN *logfiledata; /* Current contents */
int log_columns_alloced; /* # of columns allocated */
int log_columns_used; /* # of valid columns */
int log_need_newline; /* 1=output a line break before the table */
/* Seconds after the epoch at which we created the log file */
time_t log_creation_time;
#ifdef HAVE_GETRUSAGE
/* Process time used at the point at which we created the log file */
uint64_t log_creation_process_time_user;
uint64_t log_creation_process_time_sys;
/* Major and minor page faults observed at the point at which we
* created the log file */
uint64_t major_faults; /* Major page faults */
uint64_t minor_faults; /* Minor page faults */
#endif
#ifdef USE_HPET
/* Values of ncptl_time() and ncptl_time_no_hpet() when we created
* the log file */
uint64_t log_creation_time_hpet; /* Value from ncptl_time() */
uint64_t log_creation_time_no_hpet; /* Value from ncptl_time_no_hpet() */
#endif
/* Number of interrupts seen since boot time at the point at which
* we created the log file */
uint64_t log_creation_interrupt_count;
/* Current contents of the {value, tally} histogram */
VALUE_TALLY *histnodes; /* All of the nodes in the histogram tree */
void *histtree; /* Histogram stored as a binary tree */
double *histvalues; /* List of unique values in the histogram */
double *histtallies; /* List of tallies associated with values */
int histnumpairs; /* # of {value, tally} pairs in the histogram */
/* Random variable used by find_k_median() (initialized by
* ncptl_log_open()) */
RNG_STATE random_state;
/* Maximum delay time in microseconds before file metadata
* operations. The actual delay time is a uniform-random number no
* greater than this value. */
uint64_t log_delay;
/* Data needed for checkpointing log files */
uint64_t last_checkpoint; /* Time of last checkpoint */
int suppress_emptying; /* 1=don't empty the log after committing data */
} NCPTL_LOG_FILE_STATE;
/************************************
* Imported variables and functions *
************************************/
extern char *ncptl_progname;
extern int ncptl_argc_copy;
extern char **ncptl_argv_copy;
extern uint64_t ncptl_time_overhead;
extern double ncptl_time_delta_mean;
extern double ncptl_time_delta_stddev;
extern double ncptl_sleep_mean;
extern double ncptl_sleep_stddev;
extern double ncptl_proc_time_delta_mean;
extern double ncptl_proc_time_delta_stddev;
extern int ncptl_no_trap_signal[NUM_SIGNALS];
extern int ncptl_fork_works;
extern uint64_t ncptl_cycles_per_usec;
extern SYSTEM_INFORMATION systeminfo;
#ifdef HAVE_BGPPERSONALITY
extern _BGP_Personality_t ncptl_bgp_personality;
#endif
#ifdef HAVE_BGLPERSONALITY
extern BGLPersonality ncptl_bgl_personality;
#endif
extern uint64_t ncptl_log_checkpoint_interval;
extern int ncptl_hpet_works;
extern void ncptl_init_genrand(RNG_STATE *, uint64_t);
extern int64_t ncptl_genrand_int63(RNG_STATE *);
extern uint64_t ncptl_genrand_int64(RNG_STATE *);
extern void ncptl_install_signal_handler (int, SIGHANDLER, SIGHANDLER *, int);
#ifdef HAVE_GETRUSAGE
extern uint64_t ncptl_process_time (int);
extern void ncptl_page_fault_count (uint64_t *, uint64_t *);
#endif
extern uint64_t ncptl_interrupt_count (void);
extern unsigned long ncptl_time_of_day (void);
extern void ncptl_log_commit_data (NCPTL_LOG_FILE_STATE *);
extern int ncptl_envvar_to_uint64 (const char *, uint64_t *);
extern ncptl_int ncptl_get_peak_memory_usage (void);
extern uint64_t ncptl_time_no_hpet (void);
/************************************
* Internal variables and functions *
************************************/
/* Dummy variable to prevent whiny C compilers from complaining about
* unused function parameters */
static volatile union {
int i;
void *vp;
} dummyvar;
/* Queue of all {value, tally} pairs encountered in a histogram. */
static NCPTL_QUEUE *histogram_data;
/* The number of digits per floating-point value to write to the
* log file */
static const int log_data_digits = 10;
/* Queue of extra log-file comments as specified on the command line
* or by a backend. These are entered into all log files. */
static NCPTL_QUEUE *extra_log_comments = NULL;
/* Queue of all log-file state we ever allocated */
static NCPTL_QUEUE *all_log_file_state = NULL;
/* Separator string for log-file sections */
static const char *log_section_separator = "###########################################################################\n";
/* Return the kth median of a list of values in linear time
* (probabilistically). WARNING: This operation destructively
* reorders the elements in DATA. */
static double find_k_median (NCPTL_LOG_FILE_STATE *logstate, double *data,
ncptl_int k, ncptl_int firstelt,
ncptl_int lastelt)
{
ncptl_int pivotelt; /* Row by which to partition the column */
double pivotvalue; /* Contents of LOGFILEDATA's row PIVOTROW, column COLUMN */
ncptl_int topsetsize; /* # of rows in the upper (smaller valued) partition */
ncptl_int i, j;
/* If we have only one element, we have nothing to do. */
if (firstelt == lastelt)
return data[firstelt];
/* Choose a pivot at random and swap it to the first element. */
pivotelt = ncptl_genrand_int63 (&logstate->random_state) % (lastelt-firstelt+1) + firstelt;
pivotvalue = data[pivotelt];
data[pivotelt] = data[firstelt];
data[firstelt] = pivotvalue;
/* Partition the data into elements less than or equal to PIVOTVALUE
* and elements greater than or equal to PIVOTVALUE. */
i = firstelt - 1;
j = lastelt + 1;
do {
/* Find the topmost element that's on the wrong side of the pivot. */
do {
j--;
}
while (data[j] > pivotvalue);
/* Find the bottommost element that's on the wrong side of the pivot. */
do {
i++;
}
while (data[i] < pivotvalue);
/* Swap the two misordered values. */
if (i < j) {
double swapval = data[i];
data[i] = data[j];
data[j] = swapval;
}
}
while (i < j);
/* Search exactly one of the two partitions. */
topsetsize = j - firstelt + 1;
if (k <= topsetsize)
return find_k_median (logstate, data, k, firstelt, j);
else
return find_k_median (logstate, data, k-topsetsize, j+1, lastelt);
}
/* Return the median of a column of LOGFILEDATA. */
static double find_median (NCPTL_LOG_FILE_STATE *logstate, double *data,
ncptl_int datalen)
{
if (datalen & 1)
/* Odd number of data values -- there's only one median. */
return find_k_median (logstate, data, (datalen+1)/2, 0, datalen-1);
else {
/* Even number of data values -- return the average of the two medians. */
double topmed, botmed;
topmed = find_k_median (logstate, data, (datalen+1)/2, 0, datalen-1);
botmed = find_k_median (logstate, data, (datalen+1)-(datalen+1)/2, 0, datalen-1);
return (topmed+botmed) / 2.0;
}
}
/* Return the nth percentile of a column of LOGFILEDATA. */
static double find_percentile (NCPTL_LOG_FILE_STATE *logstate, double *data,
ncptl_int datalen, double percentile)
{
double data_offset; /* Index into the sorted data */
ncptl_int floor_data_offset; /* Integral version of the above */
double lower_value, upper_value; /* Values read from data_offset and data_offset+1 */
/* Handle the simple cases first. */
if (percentile < 0.0 || percentile > 100.0)
ncptl_fatal ("Percentile %.25g is invalid (must be from 0 to 100)", percentile);
if (percentile == 0.0)
return data[0];
if (percentile == 100.0)
return data[datalen - 1];
/* Compute the percentile using a linear interpolation of the modes
* for the order statistics for the uniform distribution on [0,1].
* See http://en.wikipedia.org/wiki/Quantile for details. */
data_offset = (datalen - 1)*percentile/100.0 + 1.0;
floor_data_offset = (ncptl_int) floor(data_offset);
lower_value = find_k_median (logstate, data, floor_data_offset, 0, datalen-1);
upper_value = find_k_median (logstate, data, floor_data_offset + 1, 0, datalen-1);
return lower_value + (data_offset - (double)floor_data_offset)*(upper_value - lower_value);
}
/* Return the median absolute deviation of a column of LOGFILEDATA. */
static double find_mad (NCPTL_LOG_FILE_STATE *logstate, double *data,
ncptl_int datalen)
{
double median; /* Median of the given data */
double *abs_devs; /* Absolute deviations of the given data from the median */
double mad; /* Median of the above */
ncptl_int i;
median = find_median (logstate, data, datalen);
abs_devs = ncptl_malloc (datalen*sizeof(double), sizeof(double));
for (i=0; i<datalen; i++)
abs_devs[i] = fabs(data[i] - median);
mad = find_median (logstate, abs_devs, datalen);
ncptl_free(abs_devs);
return mad;
}
/* Return the sum of a list of values. */
static double find_sum (double *data, ncptl_int datalen)
{
double sum = 0.0;
ncptl_int i;
for (i=0; i<datalen; i++)
sum += data[i];
return sum;
}
/* Return the arithmetic mean of a list of values. */
static double find_mean (double *data, ncptl_int datalen)
{
return find_sum (data, datalen) / datalen;
}
/* Return the variance of a list of values. */
static double find_variance (double *data, ncptl_int datalen)
{
double variance = 0.0;
double mean;
ncptl_int i;
if (datalen <= 1)
return 0.0;
mean = find_mean (data, datalen);
for (i=0; i<datalen; i++) {
double num = data[i] - mean;
variance += num * num;
}
return variance / (datalen - 1.0); /* Unbiased */
}
/* Return the standard deviation of a list of values. */
static double find_std_dev (double *data, ncptl_int datalen)
{
return sqrt (find_variance (data, datalen));
}
/* Return the minimum of a list of values. */
static double find_minimum (double *data, ncptl_int datalen)
{
double min = LARGEST_DOUBLE_VALUE;
ncptl_int i;
for (i=0; i<datalen; i++)
if (min > data[i])
min = data[i];
return min;
}
/* Return the maximum of a list of values. */
static double find_maximum (double *data, ncptl_int datalen)
{
double max = -LARGEST_DOUBLE_VALUE;
ncptl_int i;
for (i=0; i<datalen; i++)
if (max < data[i])
max = data[i];
return max;
}
/* Return any value from a list of values but abort if there's more
* than one value represented. */
static double find_only (double *data, ncptl_int datalen)
{
double first = data[0];
int i;
for (i=1; i<datalen; i++)
if (data[i] != first)
ncptl_fatal ("Attempted to log more than one value in a \"THE\" column");
return first;
}
/* Return the final value from a list of values. */
static double find_final (double *data, ncptl_int datalen)
{
return data[datalen-1];
}
/* Return the harmonic mean of a list of values. */
static double find_harmonic_mean (double *data, ncptl_int datalen)
{
double sum = 0.0;
int i;
for (i=0; i<datalen; i++)
if (data[i])
sum += 1.0 / data[i];
else
ncptl_fatal ("Attempted to take the harmonic mean of a set containing a zero element");
return datalen / sum;
}
/* Return the geometric mean of a list of values. */
static double find_geometric_mean (double *data, ncptl_int datalen)
{
double product = 1.0;
int i;
for (i=0; i<datalen; i++)
if (data[i])
product *= data[i];
else
ncptl_fatal ("Attempted to take the geometric mean of a set containing a zero element");
return pow (product, 1.0/datalen);
}
/* Compare two values in a {value, tally} pair, returning one of -1,
* 0, or 1 a la strcmp(). This is used by qsort(). */
static int hist_compare_value_tally (const void *first, const void *second)
{
double firstval = ((VALUE_TALLY *)first)->value;
double secondval = ((VALUE_TALLY *)second)->value;
if (firstval < secondval)
return -1;
if (firstval > secondval)
return +1;
return 0;
}
/* Append VALUE and TALLY to the global HISTOGRAM_DATA queue. */
static void store_histogram_contents (void *value, void *tally)
{
VALUE_TALLY newdata;
newdata.value = *(double *)value;
newdata.tally = *(uint64_t *)tally;
ncptl_queue_push (histogram_data, (void *)&newdata);
}
/* Given a list of values and a queue, push a histogram of the values
* onto the queue, alternating values and tallies. */
static void produce_histogram (double *data, ncptl_int datalen, NCPTL_QUEUE *histQ)
{
NCPTL_SET *hist_set = ncptl_set_init (datalen, sizeof(double), sizeof(uint64_t));
ncptl_int num_unique_values; /* Unique {value, tally} pairs in the histogram */
VALUE_TALLY *sorted_histogram; /* Sorted list of {value, tally} pairs */
ncptl_int i;
/* Construct a set of {value, tally} pairs. */
for (i=0; i<datalen; i++) {
uint64_t *tally = (uint64_t *) ncptl_set_find (hist_set, (void *)&data[i]);
uint64_t newtally;
if (tally) {
newtally = 1 + *tally;
ncptl_set_remove (hist_set, (void *)&data[i]);
}
else
newtally = 1;
ncptl_set_insert (hist_set, (void *)&data[i], (void *)&newtally);
}
/* Walk the set, storing the unique values and tallies in the global
* variable HISTOGRAM_DATA. */
histogram_data = ncptl_queue_init (sizeof(VALUE_TALLY));
ncptl_set_walk (hist_set, store_histogram_contents);
num_unique_values = ncptl_queue_length(histogram_data);
sorted_histogram = (VALUE_TALLY *) ncptl_queue_contents(histogram_data, 0);
qsort ((void *)sorted_histogram, (size_t) num_unique_values,
sizeof(VALUE_TALLY), hist_compare_value_tally);
/* Push each {value, tally} pair onto HISTQ. */
for (i=0; i<num_unique_values; i++) {
double tally = (double) sorted_histogram[i].tally;
ncptl_queue_push (histQ, (void *) &sorted_histogram[i].value);
ncptl_queue_push (histQ, (void *) &tally);
}
/* Clean up. */
ncptl_set_empty (hist_set);
ncptl_free (hist_set);
ncptl_queue_empty (histogram_data);
ncptl_free (histogram_data);
}
/* Duplicate a string with all leading/trailing spaces removed and all
* other whitespace characters converted to an ordinary space. The
* caller must ncptl_free() the result. */
static char *trimstring (char *oldstring)
{
char *newstring = ncptl_strdup (oldstring);
char *cb, *ce;
/* Remove leading spaces. */
for (cb=newstring; isspace((int)*cb); cb++)
;
/* Remove trailing spaces. */
for (ce=newstring+strlen(newstring)-1; ce>=cb && isspace((int)*ce); ce--)
;
/* Shift the valid characters to the beginning of the string. */
*++ce = '\0';
(void) memmove (newstring, cb, ce-cb+1);
/* Replace whitespace with " ". */
for (cb=newstring; *cb; cb++)
if (isspace((int)*cb))
*cb = ' ';
/* Return the result. */
return newstring;
}
/* Determine clock wraparound time (problematic with a 32-bit cycle
* counter). */
static double clock_wraparound_time (void)
{
double wrapseconds = 0.0;
#if !defined(FORCE_GETTIMEOFDAY) && !defined(FORCE_MPI_WTIME)
# if NCPTL_TIMER_TYPE != 2
# ifdef HAVE_GET_CYCLES
if (sizeof(get_cycles()) < 8) {
wrapseconds = pow(2.0, 8.0*sizeof(get_cycles()));
wrapseconds /= ncptl_cycles_per_usec * 1.0e+6;
}
# elif defined(HAVE_SYS_SYSSGI_H) && defined(HAVE_SYSSGI)
if (syssgi(SGI_CYCLECNTR_SIZE) < 64) {
wrapseconds = pow(2.0, syssgi(SGI_CYCLECNTR_SIZE));
wrapseconds /= ncptl_cycles_per_usec * 1.0e+6;
}
# elif defined(HAVE_ALPHA_CPU) && defined(READ_CYCLE_COUNTER)
wrapseconds = pow(2.0, 32.0);
wrapseconds /= ncptl_cycles_per_usec * 1.0e+6;
# endif
# endif
# ifdef USE_HPET
if (ncptl_hpet_works)
wrapseconds = pow(2.0, 64.0) / 1e15;
# endif
#endif
return wrapseconds;
}
/* Full expand the name of an executable file. The result is returned
* as a pointer to a static buffer. */
static char *fully_expanded_path (char *shortpath)
{
static char expandedpath[PATH_MAX_VAR+1]; /* String to return */
char *pathvar = getenv("PATH"); /* PATH environment variable */
char *onedir; /* One directory in PATH */
/* Ensure we have a PATH variable. */
if (!pathvar) {
/* No path? Very strange, but do the best we can. */
if (!realpath (shortpath, expandedpath))
strcpy (expandedpath, shortpath);
return expandedpath;
}
/* Try each element of PATH in turn. Pray that there aren't any
* directories with ":" in their name. */
pathvar = ncptl_strdup (pathvar);
for (onedir=strtok(pathvar, ":"); onedir; onedir=strtok(NULL, ":")) {
char newpath[PATH_MAX_VAR+1]; /* onedir + shortpath */
struct stat pathinfo; /* Information about newpath */
uid_t my_uid = geteuid(); /* This process's user ID */
gid_t my_gid = getegid(); /* This process's group ID */
sprintf (newpath, "%s/%s", onedir, shortpath);
if (stat(newpath, &pathinfo)!=-1 && S_ISREG(pathinfo.st_mode) &&
(((pathinfo.st_mode&S_IXUSR) && my_uid==pathinfo.st_uid) ||
((pathinfo.st_mode&S_IXGRP) && my_gid==pathinfo.st_gid) ||
(pathinfo.st_mode&S_IXOTH))) {
/* The file exists and we can execute it. We must therefore
* have the right file. */
if (!realpath (newpath, expandedpath))
strcpy (expandedpath, newpath);
ncptl_free (pathvar);
return expandedpath;
}
}
/* We didn't find our path. I don't know how, but let's try to
* return something, anyway. */
ncptl_free (pathvar);
if (!realpath (shortpath, expandedpath))
strcpy (expandedpath, shortpath);
return expandedpath;
}
/* Compare two integers, returning one of -1, 0, or 1 a la strcmp().
* This is used by qsort(). */
static int compare_ncptl_ints (const void *first, const void *second)
{
ncptl_int firstval = *(ncptl_int *)first;
ncptl_int secondval = *(ncptl_int *)second;
if (firstval < secondval)
return -1;
if (firstval > secondval)
return +1;
return 0;
}
/* Destructively sort a list of numbers and return it as a string of
* comma-separated ranges. The caller must ncptl_free() the
* result. */
static char *numbers_to_ranges (ncptl_int *values, ncptl_int numvalues)
{
char *resultstr; /* String to return */
ncptl_int stringlen; /* Bytes allocated for the above */
char *endresultstr; /* Pointer to the NULL at the end of resultstr */
ncptl_int rangebegin; /* Starting value in the current range */
ncptl_int rangeend; /* Ending value in the current range */
ncptl_int i;
/* Allocate memory for the worst-case resulting string. */
for (i=0, stringlen=0; i<numvalues; i++) {
char onenum[25]; /* Storage for a single ASCII number */
sprintf (onenum, "%" NICS, values[i]);
stringlen += strlen (onenum) + 1; /* +1 for dash, comma, or NULL */
}
resultstr = ncptl_malloc (stringlen*sizeof(char), 0);
/* Sort the input list. */
qsort((void *)values, (size_t)numvalues, sizeof(ncptl_int), compare_ncptl_ints);
/* Construct a string of ranges. */
endresultstr = resultstr;
rangebegin = rangeend = values[0];
for (i=1; i<numvalues; i++) {
if (values[i] == values[i-1]+1)
/* Next sequential value -- extend the current range. */
rangeend = values[i];
else
if (values[i] > values[i-1]+1) {
/* Skipped value -- start a new range. */
if (rangebegin == rangeend)
sprintf (endresultstr, "%s%" NICS,
rangebegin == values[0] ? "" : ",", rangeend);
else
sprintf (endresultstr, "%s%" NICS "%c%" NICS,
rangebegin == values[0] ? "" : ",", rangebegin,
rangeend == rangebegin+1 ? ',' : '-', rangeend);
endresultstr += strlen (endresultstr);
rangebegin = rangeend = values[i];
}
}
/* Append the final range. */
if (rangebegin == rangeend)
sprintf (endresultstr, "%s%" NICS,
rangebegin == values[0] ? "" : ",", rangeend);
else
sprintf (endresultstr, "%s%" NICS "%c%" NICS,
rangebegin == values[0] ? "" : ",", rangebegin,
rangeend == rangebegin+1 ? ',' : '-', rangeend);
return resultstr;
}
/* Delay for a random number of microseconds. */
static void log_random_delay (NCPTL_LOG_FILE_STATE *logstate)
{
uint64_t usec_delay; /* Delay in microseconds. */
if (!logstate->log_delay)
return;
usec_delay = ncptl_genrand_int64 (&logstate->random_state) % logstate->log_delay;
ncptl_udelay (usec_delay, 0);
}
/* Write a string to the log file. Currently, no file error-checking is
* performed. */
static void log_printf (NCPTL_LOG_FILE_STATE *logstate, const char *format, ...)
{
va_list args;
va_start (args, format);
if (logstate->logfile)
/* File */
(void) vfprintf (logstate->logfile, format, args);
else {
/* String */
while (1) {
int bytes_available = (int) (logstate->log_contents_allocated - logstate->log_contents_used);
int bytes_needed = vsnprintf(&logstate->log_contents[logstate->log_contents_used-1], /* Overwrite the trailing '\0'. */
bytes_available, format, args);
if (bytes_needed == -1 || bytes_needed+1 >= bytes_available) {
/* We need to allocate more memory for log_contents and try again. */
if (bytes_needed < LOG_CONTENTS_INCREMENT)
bytes_needed = LOG_CONTENTS_INCREMENT;
logstate->log_contents_allocated += bytes_needed;
logstate->log_contents = ncptl_realloc(logstate->log_contents,
logstate->log_contents_allocated,
0);
}
else {
logstate->log_contents_used += bytes_needed;
break;
}
}
}
va_end (args);
}
/* Write a character to the log file. Currently, no error-checking is
* performed. */
static void log_putc (NCPTL_LOG_FILE_STATE *logstate, int onechar)
{
if (logstate->logfile)
/* File */
(void) fputc (onechar, logstate->logfile);
else {
/* String */
if (logstate->log_contents_used == logstate->log_contents_allocated) {
/* Allocate more memory. */
logstate->log_contents_allocated += LOG_CONTENTS_INCREMENT;
logstate->log_contents = ncptl_realloc(logstate->log_contents,
logstate->log_contents_allocated,
0);
}
logstate->log_contents[logstate->log_contents_used-1] = (char) onechar; /* Overwrite the trailing '\0'. */
logstate->log_contents[logstate->log_contents_used++] = '\0';
}
}
/* Flush the log file. Currently, no error-checking is performed. */
static void log_flush (NCPTL_LOG_FILE_STATE *logstate)
{
if (!logstate->logfile)
/* String */
return;
log_random_delay (logstate);
(void) fflush (logstate->logfile);
}
/* Write a key:value pair to the log file. This is intended to be
* used for outputting prologue/epilogue information. For
* convenience, the value argument is a printf()-like template
* followed by the corresponding data to plug in. */
static void log_key_value (NCPTL_LOG_FILE_STATE *logstate,
const char *key, const char *valuefmt, ...)
{
char keycopy[NCPTL_MAX_LINE_LEN]; /* Copied and padded version of KEY */
char value[NCPTL_MAX_LINE_LEN]; /* Formatted version of VALUEFMT */
void *prev_value; /* Value from a previous insertion of KEY */
va_list args; /* Arguments used to create VALUE */
char *cleankey; /* Copy of KEY with all colons replaced with periods */
char *colon; /* Pointer to the first colon in CLEANKEY */
/* Store a formatted version of VALUEFMT in VALUE and a padded
* version of KEY in KEYCOPY. */
va_start (args, valuefmt);
vsnprintf (value, NCPTL_MAX_LINE_LEN, valuefmt, args);
va_end (args);
memset (keycopy, 0, NCPTL_MAX_LINE_LEN);
strcpy (keycopy, key);
/* Add the key:value pair to the prologue/epilogue database. */
prev_value = ncptl_set_find (logstate->log_database, (void *) keycopy);
if (prev_value)
ncptl_set_remove (logstate->log_database, (void *) keycopy);
ncptl_set_insert (logstate->log_database, (void *) keycopy, (void *) value);
/* Write the key and value to the log file. */
cleankey = ncptl_strdup (key);
while ((colon=strchr(cleankey, ':')))
*colon = '.';
log_printf (logstate, "# %s: %s\n", cleankey, value);
ncptl_free (cleankey);
}
/* Log a key and a doubleword value but append an SI prefix to the value. */
static void log_key_value_SI (NCPTL_LOG_FILE_STATE *logstate,
const char *key, const double value,
const char *unitname, const char *unit,
const double unitsize, const char *extratext)
{
char *prefmults = " KMGTPEZY"; /* SI prefixes */
double abbrvalue = value; /* Abbreviated display of VALUE */
while (*(prefmults+1) && abbrvalue>unitsize) {
prefmults++;
abbrvalue /= unitsize;
}
if (*prefmults == ' ')
log_key_value (logstate, key, "%.0f %s%s", value, unitname, extratext);
else
log_key_value (logstate, key, "%.0f %s (%.1f %c%s)%s",
value, unitname, abbrvalue, *prefmults, unit, extratext);
}
/* Write an argc/argv[] argument array to the log file. */
static void log_write_command_line (NCPTL_LOG_FILE_STATE *logstate,
char *key, int argc, char **argv)
{
char *commandline; /* Entire command line */
size_t numbytes = 0; /* Min. # of bytes in the above */
char *clptr; /* Pointer into commandline[] */
int i;
size_t j;
/* Allocate more than enough space to store all command-line
* arguments. */
for (i=0; i<argc; i++)
numbytes += strlen(argv[i]) + 1;
clptr = commandline = (char *) ncptl_malloc (4*numbytes+2, 0);
/* Escape characters that are special to the shell. */
for (i=0; i<argc; i++) {
*clptr++ = ' ';
numbytes = strlen (argv[i]);
for (j=0; j<numbytes; j++)
switch (argv[i][j]) {
/* First, check for punctuation that *isn't* special. */
case '#':
case '%':
case '+':
case ',':
case '-':
case '.':
case '/':
case ':':
case '=':
case '@':
case '^':
case '_':
*clptr++ = argv[i][j];
break;
/* Of the remaining characters, only alphanumerics don't need
* to be escaped. */
default:
if (!isalnum((int)argv[i][j]))
*clptr++ = '\\';
if (iscntrl((int)argv[i][j])) {
/* Output control characters in octal. */
sprintf (clptr, "%03o", (int)argv[i][j]);
while (*clptr)
clptr++;
}
else
*clptr++ = argv[i][j];
break;
}
}
*clptr = '\0';
/* Output the command line and clean up. */
log_key_value (logstate, key, "%s", commandline+1);
ncptl_free (commandline);
}
#if PROC_CMD_LINE_TYPE == 2
/* Write the contents of /proc/<PID>/cmdline as a command line to the
* log file. Return 1 on success, 0 on failure. */
static int log_write_proc_cmdline (NCPTL_LOG_FILE_STATE *logstate,
char *key, char *filename)
{
int cmd_fd; /* File descriptor for filename */
char commandline[NCPTL_MAX_LINE_LEN]; /* Command line as a single string */
char *cmd_ptr = commandline; /* Pointer into commandline[] */
char *cmd_argv[NCPTL_MAX_LINE_LEN]; /* Pointers into commandline[] */
int cmd_argc = 0; /* Number of entries in cmd_argv[] */
ssize_t cmd_len; /* Number of bytes in commandline[] */