]> granicus.if.org Git - sysstat/blob - sa_common.c
b2cec4ad319ce5065d7cd6befdf31d948eed2ae5
[sysstat] / sa_common.c
1 /*
2  * sar and sadf common routines.
3  * (C) 1999-2022 by Sebastien GODARD (sysstat <at> orange.fr)
4  *
5  ***************************************************************************
6  * This program is free software; you can redistribute it and/or modify it *
7  * under the terms of the GNU General Public License as published  by  the *
8  * Free Software Foundation; either version 2 of the License, or (at  your *
9  * option) any later version.                                              *
10  *                                                                         *
11  * This program is distributed in the hope that it  will  be  useful,  but *
12  * WITHOUT ANY WARRANTY; without the implied warranty  of  MERCHANTABILITY *
13  * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License *
14  * for more details.                                                       *
15  *                                                                         *
16  * You should have received a copy of the GNU General Public License along *
17  * with this program; if not, write to the Free Software Foundation, Inc., *
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA              *
19  ***************************************************************************
20  */
21
22 #include <stdio.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include <stdint.h>
26 #include <time.h>
27 #include <errno.h>
28 #include <unistd.h>     /* For STDOUT_FILENO, among others */
29 #include <dirent.h>
30 #include <fcntl.h>
31 #include <limits.h>
32 #include <libgen.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <ctype.h>
36
37 #include "version.h"
38 #include "sa.h"
39 #include "ioconf.h"
40
41 #ifdef USE_NLS
42 #include <locale.h>
43 #include <libintl.h>
44 #define _(string) gettext(string)
45 #else
46 #define _(string) (string)
47 #endif
48
49 int default_file_used = FALSE;
50 extern struct act_bitmap cpu_bitmap;
51 extern unsigned int dm_major;
52
53 unsigned int hdr_types_nr[] = {FILE_HEADER_ULL_NR, FILE_HEADER_UL_NR, FILE_HEADER_U_NR};
54 unsigned int act_types_nr[] = {FILE_ACTIVITY_ULL_NR, FILE_ACTIVITY_UL_NR, FILE_ACTIVITY_U_NR};
55 unsigned int rec_types_nr[] = {RECORD_HEADER_ULL_NR, RECORD_HEADER_UL_NR, RECORD_HEADER_U_NR};
56 unsigned int extra_desc_types_nr[] = {EXTRA_DESC_ULL_NR, EXTRA_DESC_UL_NR, EXTRA_DESC_U_NR};
57
58 /*
59  ***************************************************************************
60  * Look for activity in array.
61  *
62  * IN:
63  * @act         Array of activities.
64  * @act_flag    Activity flag to look for.
65  * @stop        TRUE if sysstat should exit when activity is not found.
66  *
67  * RETURNS:
68  * Position of activity in array, or -1 if not found (this may happen when
69  * reading data from a system activity file created by another version of
70  * sysstat).
71  ***************************************************************************
72  */
73 int get_activity_position(struct activity *act[], unsigned int act_flag, int stop)
74 {
75         int i;
76
77         for (i = 0; i < NR_ACT; i++) {
78                 if (act[i]->id == act_flag)
79                         return i;
80         }
81
82         if (stop) {
83                 PANIC((int) act_flag);
84         }
85
86         return -1;
87 }
88
89 /*
90  ***************************************************************************
91  * Count number of activities with given option.
92  *
93  * IN:
94  * @act                 Array of activities.
95  * @option              Option that activities should have to be counted
96  *                      (eg. AO_COLLECTED...)
97  * @count_outputs       TRUE if each output should be counted for activities with
98  *                      multiple outputs.
99  *
100  * RETURNS:
101  * Number of selected activities
102  ***************************************************************************
103  */
104 int get_activity_nr(struct activity *act[], unsigned int option, int count_outputs)
105 {
106         int i, n = 0;
107         unsigned int msk;
108
109         for (i = 0; i < NR_ACT; i++) {
110                 if ((act[i]->options & option) == option) {
111
112                         if (HAS_MULTIPLE_OUTPUTS(act[i]->options) && count_outputs) {
113                                 for (msk = 1; msk < 0x100; msk <<= 1) {
114                                         if ((act[i]->opt_flags & 0xff) & msk) {
115                                                 n++;
116                                         }
117                                 }
118                         }
119                         else {
120                                 n++;
121                         }
122                 }
123         }
124
125         return n;
126 }
127
128 /*
129  ***************************************************************************
130  * Look for the most recent of saDD and saYYYYMMDD to decide which one to
131  * use. If neither exists then use saDD by default.
132  *
133  * IN:
134  * @sa_dir      Directory where standard daily data files are saved.
135  * @rectime     Structure containing the current date.
136  *
137  * OUT:
138  * @sa_name     0 to use saDD data files,
139  *              1 to use saYYYYMMDD data files.
140  ***************************************************************************
141  */
142 void guess_sa_name(char *sa_dir, struct tm *rectime, int *sa_name)
143 {
144         char filename[MAX_FILE_LEN];
145         struct stat sb;
146         time_t sa_mtime;
147         long nsec;
148
149         /* Use saDD by default */
150         *sa_name = 0;
151
152         /* Look for saYYYYMMDD */
153         snprintf(filename, sizeof(filename),
154                  "%s/sa%04d%02d%02d", sa_dir,
155                  rectime->tm_year + 1900,
156                  rectime->tm_mon + 1,
157                  rectime->tm_mday);
158         filename[sizeof(filename) - 1] = '\0';
159
160         if (stat(filename, &sb) < 0)
161                 /* Cannot find or access saYYYYMMDD, so use saDD */
162                 return;
163         sa_mtime = sb.st_mtime;
164         nsec = sb.st_mtim.tv_nsec;
165
166         /* Look for saDD */
167         snprintf(filename, sizeof(filename),
168                  "%s/sa%02d", sa_dir,
169                  rectime->tm_mday);
170         filename[sizeof(filename) - 1] = '\0';
171
172         if (stat(filename, &sb) < 0) {
173                 /* Cannot find or access saDD, so use saYYYYMMDD */
174                 *sa_name = 1;
175                 return;
176         }
177
178         if ((sa_mtime > sb.st_mtime) ||
179             ((sa_mtime == sb.st_mtime) && (nsec > sb.st_mtim.tv_nsec))) {
180                 /* saYYYYMMDD is more recent than saDD, so use it */
181                 *sa_name = 1;
182         }
183 }
184
185 /*
186  ***************************************************************************
187  * Set current daily data file name.
188  *
189  * IN:
190  * @datafile    If not an empty string then this is the alternate directory
191  *              location where daily data files will be saved.
192  * @d_off       Day offset (number of days to go back in the past).
193  * @sa_name     0 for saDD data files,
194  *              1 for saYYYYMMDD data files,
195  *              -1 if unknown. In this case, will look for the most recent
196  *              of saDD and saYYYYMMDD and use it.
197  *
198  * OUT:
199  * @datafile    Name of daily data file.
200  ***************************************************************************
201  */
202 void set_default_file(char *datafile, int d_off, int sa_name)
203 {
204         char sa_dir[MAX_FILE_LEN];
205         struct tm rectime = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL};
206         int err = 0;
207
208         /* Set directory where daily data files will be saved */
209         if (datafile[0]) {
210                 strncpy(sa_dir, datafile, sizeof(sa_dir));
211         }
212         else {
213                 strncpy(sa_dir, SA_DIR, sizeof(sa_dir));
214         }
215         sa_dir[sizeof(sa_dir) - 1] = '\0';
216
217         get_time(&rectime, d_off);
218         if (sa_name < 0) {
219                 /*
220                  * Look for the most recent of saDD and saYYYYMMDD
221                  * and use it. If neither exists then use saDD.
222                  * sa_name is set accordingly.
223                  */
224                 guess_sa_name(sa_dir, &rectime, &sa_name);
225         }
226         if (sa_name) {
227                 /* Using saYYYYMMDD data files */
228                 err = snprintf(datafile, MAX_FILE_LEN,
229                                "%s/sa%04d%02d%02d", sa_dir,
230                                rectime.tm_year + 1900,
231                                rectime.tm_mon + 1,
232                                rectime.tm_mday);
233         }
234         else {
235                 /* Using saDD data files */
236                 err = snprintf(datafile, MAX_FILE_LEN,
237                                "%s/sa%02d", sa_dir,
238                                rectime.tm_mday);
239         }
240         datafile[MAX_FILE_LEN - 1] = '\0';
241
242         if ((err < 0) || (err >= MAX_FILE_LEN)) {
243                 fprintf(stderr, "%s: %s\n", __FUNCTION__, datafile);
244                 exit(1);
245         }
246
247         default_file_used = TRUE;
248
249 #ifdef DEBUG
250         fprintf(stderr, "%s: Datafile: %s\n", __FUNCTION__, datafile);
251 #endif
252 }
253
254 /*
255  ***************************************************************************
256  * Check data file type. If it is a directory then this is the alternate
257  * location where daily data files will be saved.
258  *
259  * IN:
260  * @datafile    Name of the daily data file. May be a directory.
261  * @d_off       Day offset (number of days to go back in the past).
262  * @sa_name     0 for saDD data files,
263  *              1 for saYYYYMMDD data files,
264  *              -1 if unknown. In this case, will look for the most recent
265  *              of saDD and saYYYYMMDD and use it.
266  *
267  *
268  * OUT:
269  * @datafile    Name of the daily data file. This is now a plain file, not
270  *              a directory.
271  *
272  * RETURNS:
273  * 1 if @datafile was a directory, and 0 otherwise.
274  ***************************************************************************
275  */
276 int check_alt_sa_dir(char *datafile, int d_off, int sa_name)
277 {
278         if (check_dir(datafile)) {
279                 /*
280                  * This is a directory: So append
281                  * the default file name to it.
282                  */
283                 set_default_file(datafile, d_off, sa_name);
284                 return 1;
285         }
286
287         return 0;
288 }
289
290 /*
291  ***************************************************************************
292  * Display sysstat version used to create system activity data file.
293  *
294  * IN:
295  * @st          Output stream (stderr or stdout).
296  * @file_magic  File magic header.
297  ***************************************************************************
298  */
299 void display_sa_file_version(FILE *st, struct file_magic *file_magic)
300 {
301         fprintf(st, _("File created by sar/sadc from sysstat version %d.%d.%d"),
302                 file_magic->sysstat_version,
303                 file_magic->sysstat_patchlevel,
304                 file_magic->sysstat_sublevel);
305
306         if (file_magic->sysstat_extraversion) {
307                 fprintf(st, ".%d", file_magic->sysstat_extraversion);
308         }
309         fprintf(st, "\n");
310 }
311
312 /*
313  ***************************************************************************
314  * An invalid system activity file has been opened for reading.
315  * If this file was created by an old version of sysstat, tell it to the
316  * user...
317  *
318  * IN:
319  * @fd          Descriptor of the file that has been opened.
320  * @file_magic  file_magic structure filled with file magic header data.
321  *              May contain invalid data.
322  * @file        Name of the file being read.
323  * @n           Number of bytes read while reading file magic header.
324  *              This function may also be called after failing to read file
325  *              standard header, or if CPU activity has not been found in
326  *              file. In this case, n is set to 0.
327  ***************************************************************************
328  */
329 void handle_invalid_sa_file(int fd, struct file_magic *file_magic, char *file,
330                             int n)
331 {
332         unsigned short fmt_magic;
333
334         fprintf(stderr, _("Invalid system activity file: %s\n"), file);
335
336         if (n == FILE_MAGIC_SIZE) {
337                 if ((file_magic->sysstat_magic == SYSSTAT_MAGIC) || (file_magic->sysstat_magic == SYSSTAT_MAGIC_SWAPPED)) {
338                         /* This is a sysstat file, but this file has an old format */
339                         display_sa_file_version(stderr, file_magic);
340
341                         fmt_magic = file_magic->sysstat_magic == SYSSTAT_MAGIC ?
342                                     file_magic->format_magic : __builtin_bswap16(file_magic->format_magic);
343                         fprintf(stderr,
344                                 _("Current sysstat version cannot read the format of this file (%#x)\n"),
345                                 fmt_magic);
346                         if (fmt_magic >= FORMAT_MAGIC_2171) {
347                                 fprintf(stderr,
348                                         _("Try to convert it to current format. Enter:\n\n"));
349                                 fprintf(stderr, "sadf -c %s > %s.new\n\n", file, file);
350                                 fprintf(stderr,
351                                         _("You should then be able to read the new file created (%s.new)\n"),
352                                         file);
353                         }
354                 }
355         }
356
357         close (fd);
358         exit(3);
359 }
360
361 /*
362  ***************************************************************************
363  * Display an error message then exit.
364  ***************************************************************************
365  */
366 void print_collect_error(void)
367 {
368         fprintf(stderr, _("Requested activities not available\n"));
369         exit(1);
370 }
371
372 /*
373  ***************************************************************************
374  * Fill system activity file magic header.
375  *
376  * IN:
377  * @file_magic  System activity file magic header.
378  ***************************************************************************
379  */
380 void enum_version_nr(struct file_magic *fm)
381 {
382         char *v;
383         char version[16];
384
385         fm->sysstat_extraversion = 0;
386
387         strcpy(version, VERSION);
388
389         /* Get version number */
390         if ((v = strtok(version, ".")) == NULL)
391                 return;
392         fm->sysstat_version = atoi(v) & 0xff;
393
394         /* Get patchlevel number */
395         if ((v = strtok(NULL, ".")) == NULL)
396                 return;
397         fm->sysstat_patchlevel = atoi(v) & 0xff;
398
399         /* Get sublevel number */
400         if ((v = strtok(NULL, ".")) == NULL)
401                 return;
402         fm->sysstat_sublevel = atoi(v) & 0xff;
403
404         /* Get extraversion number. Don't necessarily exist */
405         if ((v = strtok(NULL, ".")) == NULL)
406                 return;
407         fm->sysstat_extraversion = atoi(v) & 0xff;
408 }
409
410 /*
411  ***************************************************************************
412  * Write data to file. If the write() call was interrupted by a signal, try
413  * again so that the whole buffer can be written.
414  *
415  * IN:
416  * @fd          Output file descriptor.
417  * @buf         Data buffer.
418  * @nr_bytes    Number of bytes to write.
419  *
420  * RETURNS:
421  * Number of bytes written to file, or -1 on error.
422  ***************************************************************************
423  */
424 int write_all(int fd, const void *buf, int nr_bytes)
425 {
426         int block, offset = 0;
427         char *buffer = (char *) buf;
428
429         while (nr_bytes > 0) {
430
431                 block = write(fd, &buffer[offset], nr_bytes);
432
433                 if (block < 0) {
434                         if (errno == EINTR)
435                                 continue;
436                         return block;
437                 }
438                 if (block == 0)
439                         return offset;
440
441                 offset += block;
442                 nr_bytes -= block;
443         }
444
445         return offset;
446 }
447
448 #ifndef SOURCE_SADC
449 /*
450  ***************************************************************************
451  * Allocate structures.
452  *
453  * IN:
454  * @act Array of activities.
455  ***************************************************************************
456  */
457 void allocate_structures(struct activity *act[])
458 {
459         int i, j;
460
461         for (i = 0; i < NR_ACT; i++) {
462
463                 if (act[i]->nr_ini > 0) {
464
465                         /* Look for a possible overflow */
466                         check_overflow((size_t) act[i]->msize, (size_t) act[i]->nr_ini,
467                                        (size_t) act[i]->nr2);
468
469                         for (j = 0; j < 3; j++) {
470                                 SREALLOC(act[i]->buf[j], void,
471                                                 (size_t) act[i]->msize * (size_t) act[i]->nr_ini * (size_t) act[i]->nr2);
472                         }
473                         act[i]->nr_allocated = act[i]->nr_ini;
474                 }
475         }
476 }
477
478 /*
479  ***************************************************************************
480  * Free structures.
481  *
482  * IN:
483  * @act Array of activities.
484  ***************************************************************************
485  */
486 void free_structures(struct activity *act[])
487 {
488         int i, j;
489
490         for (i = 0; i < NR_ACT; i++) {
491                 if (act[i]->nr_allocated > 0) {
492                         for (j = 0; j < 3; j++) {
493                                 if (act[i]->buf[j]) {
494                                         free(act[i]->buf[j]);
495                                         act[i]->buf[j] = NULL;
496                                 }
497                         }
498                         act[i]->nr_allocated = 0;
499                 }
500         }
501 }
502
503 /*
504  ***************************************************************************
505  * Reallocate all the buffers for a given activity.
506  *
507  * IN:
508  * @a           Activity whose buffers need to be reallocated.
509  * @nr_min      Minimum number of items that the new buffers should be able
510  *              to receive.
511  ***************************************************************************
512  */
513 void reallocate_all_buffers(struct activity *a, __nr_t nr_min)
514 {
515         int j;
516         size_t nr_realloc;
517
518         if (nr_min <= 0) {
519                 nr_min = 1;
520         }
521         if (!a->nr_allocated) {
522                 nr_realloc = nr_min;
523         }
524         else {
525                 nr_realloc = a->nr_allocated;
526                 do {
527                         nr_realloc = nr_realloc * 2;
528                 }
529                 while (nr_realloc < nr_min);
530         }
531
532         for (j = 0; j < 3; j++) {
533                 SREALLOC(a->buf[j], void,
534                         (size_t) a->msize * nr_realloc * (size_t) a->nr2);
535                 /* Init additional space which has been allocated */
536                 if (a->nr_allocated) {
537                         memset(a->buf[j] + a->msize * a->nr_allocated * a->nr2, 0,
538                                (size_t) a->msize * (size_t) (nr_realloc - a->nr_allocated) * (size_t) a->nr2);
539                 }
540         }
541
542         a->nr_allocated = nr_realloc;
543 }
544
545 /*
546  ***************************************************************************
547  * Check if we are close enough to desired interval.
548  *
549  * IN:
550  * @uptime_ref  Uptime used as reference. This is the system uptime for the
551  *              first sample statistics, or the first system uptime after a
552  *              LINUX RESTART (in 1/100th of a second).
553  * @uptime      Current system uptime (in 1/100th of a second).
554  * @reset       TRUE if @last_uptime should be reset with @uptime_ref.
555  * @interval    Interval of time.
556  *
557  * RETURNS:
558  * TRUE if we are actually close enough to desired interval, FALSE otherwise.
559  ***************************************************************************
560 */
561 int next_slice(unsigned long long uptime_ref, unsigned long long uptime,
562                int reset, long interval)
563 {
564         unsigned long file_interval, entry;
565         static unsigned long long last_uptime = 0;
566         int min, max, pt1, pt2;
567         double f;
568
569         /* uptime is expressed in 1/100th of a second */
570         if (!last_uptime || reset) {
571                 last_uptime = uptime_ref;
572         }
573
574         /* Interval cannot be greater than 0xffffffff here */
575         f = ((double) ((uptime - last_uptime) & 0xffffffff)) / 100;
576         file_interval = (unsigned long) f;
577         if ((f * 10) - (file_interval * 10) >= 5) {
578                 file_interval++; /* Rounding to correct value */
579         }
580
581         last_uptime = uptime;
582
583         if (interval == 1)
584                 /* Smallest time interval: Always close enough to desired interval */
585                 return TRUE;
586
587         /*
588          * A few notes about the "algorithm" used here to display selected entries
589          * from the system activity file (option -f with -i flag):
590          * Let Iu be the interval value given by the user on the command line,
591          *     In the interval between current and previous sample,
592          * and En the current sample (identified by its time stamp) in the file.
593          * En will ne displayed if there is an integer p so that:
594          * p * Iu belongs to [En - In/2, En + In/2[.
595          */
596         f = ((double) ((uptime - uptime_ref) & 0xffffffff)) / 100;
597         entry = (unsigned long) f;
598         if ((f * 10) - (entry * 10) >= 5) {
599                 entry++;
600         }
601
602         min = entry - (file_interval / 2);
603         max = entry + (file_interval / 2) + (file_interval & 0x1);
604         pt1 = (entry / interval) * interval;
605         pt2 = ((entry / interval) + 1) * interval;
606
607         return (((pt1 >= min) && (pt1 < max)) || ((pt2 >= min) && (pt2 < max)));
608 }
609
610 /*
611  ***************************************************************************
612  * Use time stamp to fill tstamp structure.
613  *
614  * IN:
615  * @timestamp   Timestamp to decode (format: HH:MM:SS).
616  *
617  * OUT:
618  * @tse         Structure containing the decoded timestamp.
619  *
620  * RETURNS:
621  * 0 if the timestamp has been successfully decoded, 1 otherwise.
622  ***************************************************************************
623  */
624 int decode_timestamp(char timestamp[], struct tstamp *tse)
625 {
626         timestamp[2] = timestamp[5] = '\0';
627         tse->tm_sec  = atoi(&timestamp[6]);
628         tse->tm_min  = atoi(&timestamp[3]);
629         tse->tm_hour = atoi(timestamp);
630
631         if ((tse->tm_sec < 0) || (tse->tm_sec > 59) ||
632             (tse->tm_min < 0) || (tse->tm_min > 59) ||
633             (tse->tm_hour < 0) || (tse->tm_hour > 23))
634                 return 1;
635
636         tse->use = TRUE;
637
638         return 0;
639 }
640
641 /*
642  ***************************************************************************
643  * Compare two timestamps.
644  *
645  * IN:
646  * @rectime     Date and time for current sample.
647  * @tse         Timestamp used as reference.
648  * @cross_day   TRUE if a new day has been started.
649  *
650  * RETURNS:
651  * A positive value if @rectime is greater than @tse,
652  * a negative one otherwise.
653  ***************************************************************************
654  */
655 int datecmp(struct tm *rectime, struct tstamp *tse, int cross_day)
656 {
657         int tm_hour = rectime->tm_hour;
658
659         if (cross_day) {
660                 /*
661                  * This is necessary if we want to properly handle something like:
662                  * sar -s time_start -e time_end with
663                  * time_start(day D) > time_end(day D+1)
664                  */
665                 tm_hour += 24;
666         }
667
668         if (tm_hour == tse->tm_hour) {
669                 if (rectime->tm_min == tse->tm_min)
670                         return (rectime->tm_sec - tse->tm_sec);
671                 else
672                         return (rectime->tm_min - tse->tm_min);
673         }
674         else
675                 return (tm_hour - tse->tm_hour);
676 }
677
678 /*
679  ***************************************************************************
680  * Parse a timestamp entered on the command line (hh:mm[:ss]) and decode it.
681  *
682  * IN:
683  * @argv                Arguments list.
684  * @opt                 Index in the arguments list.
685  * @def_timestamp       Default timestamp to use.
686  *
687  * OUT:
688  * @tse                 Structure containing the decoded timestamp.
689  *
690  * RETURNS:
691  * 0 if the timestamp has been successfully decoded, 1 otherwise.
692  ***************************************************************************
693  */
694 int parse_timestamp(char *argv[], int *opt, struct tstamp *tse,
695                     const char *def_timestamp)
696 {
697         char timestamp[9];
698
699         if (argv[++(*opt)]) {
700                 switch (strlen(argv[*opt])) {
701
702                         case 5:
703                                 strncpy(timestamp, argv[(*opt)++], 5);
704                                 timestamp[5] = '\0';
705                                 strcat(timestamp, ":00");
706                                 break;
707
708                         case 8:
709                                 strncpy(timestamp, argv[(*opt)++], 8);
710                                 break;
711
712                         default:
713                                 strncpy(timestamp, def_timestamp, 8);
714                                 break;
715                 }
716         } else {
717                 strncpy(timestamp, def_timestamp, 8);
718         }
719         timestamp[8] = '\0';
720
721         return decode_timestamp(timestamp, tse);
722 }
723
724 /*
725  ***************************************************************************
726  * Set interval value.
727  *
728  * IN:
729  * @record_hdr_curr     Record with current sample statistics.
730  * @record_hdr_prev     Record with previous sample statistics.
731  *
732  * OUT:
733  * @itv                 Interval of time in 1/100th of a second.
734  ***************************************************************************
735  */
736 void get_itv_value(struct record_header *record_hdr_curr,
737                    struct record_header *record_hdr_prev,
738                    unsigned long long *itv)
739 {
740         /* Interval value in jiffies */
741         *itv = get_interval(record_hdr_prev->uptime_cs,
742                             record_hdr_curr->uptime_cs);
743 }
744
745 /*
746  ***************************************************************************
747  * Fill the rectime structure with the file's creation date, based on file's
748  * time data saved in file header.
749  * The resulting timestamp is expressed in the locale of the file creator or
750  * in the user's own locale, depending on whether option -t has been used
751  * or not.
752  *
753  * IN:
754  * @flags       Flags for common options and system state.
755  * @file_hdr    System activity file standard header.
756  *
757  * OUT:
758  * @rectime     Date (and possibly time) from file header. Only the date,
759  *              not the time, should be used by the caller.
760  ***************************************************************************
761  */
762 void get_file_timestamp_struct(uint64_t flags, struct tm *rectime,
763                                struct file_header *file_hdr)
764 {
765         time_t t = file_hdr->sa_ust_time;
766
767         if (PRINT_TRUE_TIME(flags)) {
768                 /* Get local time. This is just to fill fields with a default value. */
769                 get_time(rectime, 0);
770
771                 rectime->tm_mday = file_hdr->sa_day;
772                 rectime->tm_mon  = file_hdr->sa_month;
773                 rectime->tm_year = file_hdr->sa_year;
774                 /*
775                  * Call mktime() to set DST (Daylight Saving Time) flag.
776                  * Has anyone a better way to do it?
777                  */
778                 rectime->tm_hour = rectime->tm_min = rectime->tm_sec = 0;
779                 mktime(rectime);
780         }
781         else {
782                 localtime_r(&t, rectime);
783         }
784 }
785
786 /*
787  ***************************************************************************
788  * Print report header.
789  *
790  * IN:
791  * @flags       Flags for common options and system state.
792  * @file_hdr    System activity file standard header.
793  *
794  * OUT:
795  * @rectime     Date and time from file header.
796  ***************************************************************************
797  */
798 void print_report_hdr(uint64_t flags, struct tm *rectime,
799                       struct file_header *file_hdr)
800 {
801
802         /* Get date of file creation */
803         get_file_timestamp_struct(flags, rectime, file_hdr);
804
805         /*
806          * Display the header.
807          * NB: Number of CPU (value in [1, NR_CPUS + 1]).
808          *      1 means that there is only one proc and non SMP kernel.
809          *      2 means one proc and SMP kernel. Etc.
810          */
811         print_gal_header(rectime, file_hdr->sa_sysname, file_hdr->sa_release,
812                          file_hdr->sa_nodename, file_hdr->sa_machine,
813                          file_hdr->sa_cpu_nr > 1 ? file_hdr->sa_cpu_nr - 1 : 1,
814                          PLAIN_OUTPUT);
815 }
816
817 /*
818  ***************************************************************************
819  * Network interfaces may now be registered (and unregistered) dynamically.
820  * This is what we try to guess here.
821  *
822  * IN:
823  * @a           Activity structure with statistics.
824  * @curr        Index in array for current sample statistics.
825  * @ref         Index in array for sample statistics used as reference.
826  * @pos         Index on current network interface.
827  *
828  * RETURNS:
829  * Position of current network interface in array of sample statistics used
830  * as reference.
831  * -1 if it is a new interface (it was not present in array of stats used
832  * as reference).
833  * -2 if it is a known interface but which has been unregistered then
834  * registered again on the interval.
835  ***************************************************************************
836  */
837 int check_net_dev_reg(struct activity *a, int curr, int ref, int pos)
838 {
839         struct stats_net_dev *sndc, *sndp;
840         int j0, j = pos;
841
842         if (!a->nr[ref])
843                 /*
844                  * No items found in previous iteration:
845                  * Current interface is necessarily new.
846                  */
847                 return -1;
848
849         if (j >= a->nr[ref]) {
850                 j = a->nr[ref] - 1;
851         }
852         j0 = j;
853
854         sndc = (struct stats_net_dev *) ((char *) a->buf[curr] + pos * a->msize);
855
856         do {
857                 sndp = (struct stats_net_dev *) ((char *) a->buf[ref] + j * a->msize);
858
859                 if (!strcmp(sndc->interface, sndp->interface)) {
860                         /*
861                          * Network interface found.
862                          * If a counter has decreased, then we may assume that the
863                          * corresponding interface was unregistered, then registered again.
864                          */
865                         if ((sndc->rx_packets    < sndp->rx_packets)    ||
866                             (sndc->tx_packets    < sndp->tx_packets)    ||
867                             (sndc->rx_bytes      < sndp->rx_bytes)      ||
868                             (sndc->tx_bytes      < sndp->tx_bytes)      ||
869                             (sndc->rx_compressed < sndp->rx_compressed) ||
870                             (sndc->tx_compressed < sndp->tx_compressed) ||
871                             (sndc->multicast     < sndp->multicast)) {
872
873                                 /*
874                                  * Special processing for rx_bytes (_packets) and
875                                  * tx_bytes (_packets) counters: If the number of
876                                  * bytes (packets) has decreased, whereas the number of
877                                  * packets (bytes) has increased, then assume that the
878                                  * relevant counter has met an overflow condition, and that
879                                  * the interface was not unregistered, which is all the
880                                  * more plausible that the previous value for the counter
881                                  * was > ULLONG_MAX/2.
882                                  * NB: the average value displayed will be wrong in this case...
883                                  *
884                                  * If such an overflow is detected, just set the flag. There is no
885                                  * need to handle this in a special way: the difference is still
886                                  * properly calculated if the result is of the same type (i.e.
887                                  * unsigned long) as the two values.
888                                  */
889                                 int ovfw = FALSE;
890
891                                 if ((sndc->rx_bytes   < sndp->rx_bytes)   &&
892                                     (sndc->rx_packets > sndp->rx_packets) &&
893                                     (sndp->rx_bytes   > (~0ULL >> 1))) {
894                                         ovfw = TRUE;
895                                 }
896                                 if ((sndc->tx_bytes   < sndp->tx_bytes)   &&
897                                     (sndc->tx_packets > sndp->tx_packets) &&
898                                     (sndp->tx_bytes   > (~0ULL >> 1))) {
899                                         ovfw = TRUE;
900                                 }
901                                 if ((sndc->rx_packets < sndp->rx_packets) &&
902                                     (sndc->rx_bytes   > sndp->rx_bytes)   &&
903                                     (sndp->rx_packets > (~0ULL >> 1))) {
904                                         ovfw = TRUE;
905                                 }
906                                 if ((sndc->tx_packets < sndp->tx_packets) &&
907                                     (sndc->tx_bytes   > sndp->tx_bytes)   &&
908                                     (sndp->tx_packets > (~0ULL >> 1))) {
909                                         ovfw = TRUE;
910                                 }
911
912                                 if (!ovfw)
913                                         /*
914                                          * OK: Assume here that the device was
915                                          * actually unregistered.
916                                          */
917                                         return -2;
918                         }
919                         return j;
920                 }
921                 if (++j >= a->nr[ref]) {
922                         j = 0;
923                 }
924         }
925         while (j != j0);
926
927         /* This is a newly registered interface */
928         return -1;
929 }
930
931 /*
932  ***************************************************************************
933  * Network interfaces may now be registered (and unregistered) dynamically.
934  * This is what we try to guess here.
935  *
936  * IN:
937  * @a           Activity structure with statistics.
938  * @curr        Index in array for current sample statistics.
939  * @ref         Index in array for sample statistics used as reference.
940  * @pos         Index on current network interface.
941  *
942  * RETURNS:
943  * Position of current network interface in array of sample statistics used
944  * as reference.
945  * -1 if it is a newly registered interface.
946  * -2 if it is a known interface but which has been unregistered then
947  * registered again on the interval.
948  ***************************************************************************
949  */
950 int check_net_edev_reg(struct activity *a, int curr, int ref, int pos)
951 {
952         struct stats_net_edev *snedc, *snedp;
953         int j0, j = pos;
954
955         if (!a->nr[ref])
956                 /*
957                  * No items found in previous iteration:
958                  * Current interface is necessarily new.
959                  */
960                 return -1;
961
962         if (j >= a->nr[ref]) {
963                 j = a->nr[ref] - 1;
964         }
965         j0 = j;
966
967         snedc = (struct stats_net_edev *) ((char *) a->buf[curr] + pos * a->msize);
968
969         do {
970                 snedp = (struct stats_net_edev *) ((char *) a->buf[ref] + j * a->msize);
971
972                 if (!strcmp(snedc->interface, snedp->interface)) {
973                         /*
974                          * Network interface found.
975                          * If a counter has decreased, then we may assume that the
976                          * corresponding interface was unregistered, then registered again.
977                          */
978                         if ((snedc->tx_errors         < snedp->tx_errors)         ||
979                             (snedc->collisions        < snedp->collisions)        ||
980                             (snedc->rx_dropped        < snedp->rx_dropped)        ||
981                             (snedc->tx_dropped        < snedp->tx_dropped)        ||
982                             (snedc->tx_carrier_errors < snedp->tx_carrier_errors) ||
983                             (snedc->rx_frame_errors   < snedp->rx_frame_errors)   ||
984                             (snedc->rx_fifo_errors    < snedp->rx_fifo_errors)    ||
985                             (snedc->tx_fifo_errors    < snedp->tx_fifo_errors))
986                                 /*
987                                  * OK: assume here that the device was
988                                  * actually unregistered.
989                                  */
990                                 return -2;
991
992                         return j;
993                 }
994                 if (++j >= a->nr[ref]) {
995                         j = 0;
996                 }
997         }
998         while (j != j0);
999
1000         /* This is a newly registered interface */
1001         return -1;
1002 }
1003
1004 /*
1005  ***************************************************************************
1006  * Disks may be registered dynamically (true in /proc/diskstats file).
1007  * This is what we try to guess here.
1008  *
1009  * IN:
1010  * @a           Activity structure with statistics.
1011  * @curr        Index in array for current sample statistics.
1012  * @ref         Index in array for sample statistics used as reference.
1013  * @pos         Index on current disk.
1014  *
1015  * RETURNS:
1016  * Position of current disk in array of sample statistics used as reference
1017  * -1 if it is a newly registered device.
1018  * -2 if it is a known device but which has been unregistered then registered
1019  * again on the interval.
1020  ***************************************************************************
1021  */
1022 int check_disk_reg(struct activity *a, int curr, int ref, int pos)
1023 {
1024         struct stats_disk *sdc, *sdp;
1025         int j0, j = pos;
1026
1027         if (!a->nr[ref])
1028                 /*
1029                  * No items found in previous iteration:
1030                  * Current interface is necessarily new.
1031                  */
1032                 return -1;
1033
1034         if (j >= a->nr[ref]) {
1035                 j = a->nr[ref] - 1;
1036         }
1037         j0 = j;
1038
1039         sdc = (struct stats_disk *) ((char *) a->buf[curr] + pos * a->msize);
1040
1041         do {
1042                 sdp = (struct stats_disk *) ((char *) a->buf[ref] + j * a->msize);
1043
1044                 if ((sdc->major == sdp->major) &&
1045                     (sdc->minor == sdp->minor)) {
1046                         /*
1047                          * Disk found.
1048                          * If all the counters have decreased then the likelyhood
1049                          * is that the disk has been unregistered and a new disk inserted.
1050                          * If only one or two have decreased then the likelyhood
1051                          * is that the counter has simply wrapped.
1052                          * Don't take into account a counter if its previous value was 0
1053                          * (this may be a read-only device, or a kernel that doesn't
1054                          * support discard stats yet...)
1055                          */
1056                         if ((sdc->nr_ios < sdp->nr_ios) &&
1057                             (!sdp->rd_sect || (sdc->rd_sect < sdp->rd_sect)) &&
1058                             (!sdp->wr_sect || (sdc->wr_sect < sdp->wr_sect)) &&
1059                             (!sdp->dc_sect || (sdc->dc_sect < sdp->dc_sect)))
1060                                 /* Same device registered again */
1061                                 return -2;
1062
1063                         return j;
1064                 }
1065                 if (++j >= a->nr[ref]) {
1066                         j = 0;
1067                 }
1068         }
1069         while (j != j0);
1070
1071         /* This is a newly registered device */
1072         return -1;
1073 }
1074
1075 /*
1076  ***************************************************************************
1077  * Allocate bitmaps for activities that have one.
1078  *
1079  * IN:
1080  * @act         Array of activities.
1081  ***************************************************************************
1082  */
1083 void allocate_bitmaps(struct activity *act[])
1084 {
1085         int i;
1086
1087         for (i = 0; i < NR_ACT; i++) {
1088                 /*
1089                  * If current activity has a bitmap which has not already
1090                  * been allocated, then allocate it.
1091                  * Note that a same bitmap may be used by several activities.
1092                  */
1093                 if (act[i]->bitmap && !act[i]->bitmap->b_array) {
1094                         SREALLOC(act[i]->bitmap->b_array, unsigned char,
1095                                  BITMAP_SIZE(act[i]->bitmap->b_size));
1096                 }
1097         }
1098 }
1099
1100 /*
1101  ***************************************************************************
1102  * Free bitmaps for activities that have one.
1103  *
1104  * IN:
1105  * @act         Array of activities.
1106  ***************************************************************************
1107  */
1108 void free_bitmaps(struct activity *act[])
1109 {
1110         int i;
1111
1112         for (i = 0; i < NR_ACT; i++) {
1113                 if (act[i]->bitmap && act[i]->bitmap->b_array) {
1114                         free(act[i]->bitmap->b_array);
1115                         /* Set pointer to NULL to prevent it from being freed again */
1116                         act[i]->bitmap->b_array = NULL;
1117                 }
1118         }
1119 }
1120
1121 /*
1122  ***************************************************************************
1123  * Select all activities, even if they have no associated items.
1124  *
1125  * IN:
1126  * @act         Array of activities.
1127  *
1128  * OUT:
1129  * @act         Array of activities, all of the being selected.
1130  ***************************************************************************
1131  */
1132 void select_all_activities(struct activity *act[])
1133 {
1134         int i;
1135
1136         for (i = 0; i < NR_ACT; i++) {
1137                 act[i]->options |= AO_SELECTED;
1138         }
1139 }
1140
1141 /*
1142  ***************************************************************************
1143  * Select CPU activity if no other activities have been explicitly selected.
1144  * Also select CPU "all" if no other CPU has been selected.
1145  *
1146  * IN:
1147  * @act         Array of activities.
1148  *
1149  * OUT:
1150  * @act         Array of activities with CPU activity selected if needed.
1151  ***************************************************************************
1152  */
1153 void select_default_activity(struct activity *act[])
1154 {
1155         int p;
1156
1157         p = get_activity_position(act, A_CPU, EXIT_IF_NOT_FOUND);
1158
1159         /* Default is CPU activity... */
1160         if (!get_activity_nr(act, AO_SELECTED, COUNT_ACTIVITIES)) {
1161                 /*
1162                  * Yet A_CPU activity may not be available in file
1163                  * since the user can choose not to collect it.
1164                  */
1165                 act[p]->options |= AO_SELECTED;
1166         }
1167
1168         /*
1169          * If no CPU's have been selected then select CPU "all".
1170          * cpu_bitmap bitmap may be used by several activities (A_CPU, A_PWR_CPU...)
1171          */
1172         if (!count_bits(cpu_bitmap.b_array, BITMAP_SIZE(cpu_bitmap.b_size))) {
1173                 cpu_bitmap.b_array[0] |= 0x01;
1174         }
1175 }
1176
1177 /*
1178  ***************************************************************************
1179  * Swap bytes for every numerical field in structure. Used to convert from
1180  * one endianness type (big-endian or little-endian) to the other.
1181  *
1182  * IN:
1183  * @types_nr    Number of fields in structure for each following types:
1184  *              unsigned long long, unsigned long and int.
1185  * @ps          Pointer on structure.
1186  * @is64bit     TRUE if data come from a 64-bit machine.
1187  ***************************************************************************
1188  */
1189 void swap_struct(unsigned int types_nr[], void *ps, int is64bit)
1190 {
1191         int i;
1192         uint64_t *x;
1193         uint32_t *y;
1194
1195         x = (uint64_t *) ps;
1196         /* For each field of type long long (or double) */
1197         for (i = 0; i < types_nr[0]; i++) {
1198                 *x = __builtin_bswap64(*x);
1199                 x = (uint64_t *) ((char *) x + ULL_ALIGNMENT_WIDTH);
1200         }
1201
1202         y = (uint32_t *) x;
1203         /* For each field of type long */
1204         for (i = 0; i < types_nr[1]; i++) {
1205                 if (is64bit) {
1206                         *x = __builtin_bswap64(*x);
1207                         x = (uint64_t *) ((char *) x + UL_ALIGNMENT_WIDTH);
1208                 }
1209                 else {
1210                         *y = __builtin_bswap32(*y);
1211                         y = (uint32_t *) ((char *) y + UL_ALIGNMENT_WIDTH);
1212                 }
1213         }
1214
1215         if (is64bit) {
1216                 y = (uint32_t *) x;
1217         }
1218         /* For each field of type int */
1219         for (i = 0; i < types_nr[2]; i++) {
1220                 *y = __builtin_bswap32(*y);
1221                 y = (uint32_t *) ((char *) y + U_ALIGNMENT_WIDTH);
1222         }
1223 }
1224
1225 /*
1226  ***************************************************************************
1227  * Map the fields of a structure containing statistics read from a file to
1228  * those of the structure known by current sysstat version.
1229  * Each structure (either read from file or from current sysstat version)
1230  * is described by 3 values: The number of [unsigned] long long integers,
1231  * the number of [unsigned] long integers following in the structure, and
1232  * last the number of [unsigned] integers.
1233  * We assume that those numbers will *never* decrease with newer sysstat
1234  * versions.
1235  *
1236  * IN:
1237  * @gtypes_nr   Structure description as expected for current sysstat version.
1238  * @ftypes_nr   Structure description as read from file.
1239  * @ps          Pointer on structure containing statistics.
1240  * @f_size      Size of the structure containing statistics. This is the
1241  *              size of the structure *read from file*.
1242  * @g_size      Size of the structure expected by current sysstat version.
1243  * @b_size      Size of the buffer pointed by @ps.
1244  *
1245  * RETURNS:
1246  * -1 if an error has been encountered, or 0 otherwise.
1247  ***************************************************************************
1248  */
1249 int remap_struct(unsigned int gtypes_nr[], unsigned int ftypes_nr[],
1250                  void *ps, unsigned int f_size, unsigned int g_size, size_t b_size)
1251 {
1252         int d;
1253         size_t n;
1254
1255         /* Sanity check */
1256         if (MAP_SIZE(ftypes_nr) > f_size)
1257                 return -1;
1258
1259         /* Remap [unsigned] long fields */
1260         d = gtypes_nr[0] - ftypes_nr[0];
1261         if (d) {
1262                 if (ftypes_nr[0] * ULL_ALIGNMENT_WIDTH < ftypes_nr[0])
1263                         /* Overflow */
1264                         return -1;
1265
1266                 n = MINIMUM(f_size - ftypes_nr[0] * ULL_ALIGNMENT_WIDTH,
1267                             g_size - gtypes_nr[0] * ULL_ALIGNMENT_WIDTH);
1268                 if ((ftypes_nr[0] * ULL_ALIGNMENT_WIDTH >= b_size) ||
1269                     (gtypes_nr[0] * ULL_ALIGNMENT_WIDTH + n > b_size) ||
1270                     (ftypes_nr[0] * ULL_ALIGNMENT_WIDTH + n > b_size))
1271                         return -1;
1272
1273                 memmove(((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH,
1274                         ((char *) ps) + ftypes_nr[0] * ULL_ALIGNMENT_WIDTH, n);
1275                 if (d > 0) {
1276                         memset(((char *) ps) + ftypes_nr[0] * ULL_ALIGNMENT_WIDTH,
1277                                0, d * ULL_ALIGNMENT_WIDTH);
1278                 }
1279         }
1280         /* Remap [unsigned] int fields */
1281         d = gtypes_nr[1] - ftypes_nr[1];
1282         if (d) {
1283                 if (gtypes_nr[0] * ULL_ALIGNMENT_WIDTH +
1284                     ftypes_nr[1] * UL_ALIGNMENT_WIDTH < ftypes_nr[1])
1285                         /* Overflow */
1286                         return -1;
1287
1288                 n = MINIMUM(f_size - ftypes_nr[0] * ULL_ALIGNMENT_WIDTH
1289                                    - ftypes_nr[1] * UL_ALIGNMENT_WIDTH,
1290                             g_size - gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
1291                                    - gtypes_nr[1] * UL_ALIGNMENT_WIDTH);
1292                 if ((gtypes_nr[0] * ULL_ALIGNMENT_WIDTH +
1293                      ftypes_nr[1] * UL_ALIGNMENT_WIDTH >= b_size) ||
1294                     (gtypes_nr[0] * ULL_ALIGNMENT_WIDTH +
1295                      gtypes_nr[1] * UL_ALIGNMENT_WIDTH + n > b_size) ||
1296                     (gtypes_nr[0] * ULL_ALIGNMENT_WIDTH +
1297                      ftypes_nr[1] * UL_ALIGNMENT_WIDTH + n > b_size))
1298                         return -1;
1299
1300                 memmove(((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
1301                                       + gtypes_nr[1] * UL_ALIGNMENT_WIDTH,
1302                         ((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
1303                                       + ftypes_nr[1] * UL_ALIGNMENT_WIDTH, n);
1304                 if (d > 0) {
1305                         memset(((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
1306                                              + ftypes_nr[1] * UL_ALIGNMENT_WIDTH,
1307                                0, d * UL_ALIGNMENT_WIDTH);
1308                 }
1309         }
1310         /* Remap possible fields (like strings of chars) following int fields */
1311         d = gtypes_nr[2] - ftypes_nr[2];
1312         if (d) {
1313                 if (gtypes_nr[0] * ULL_ALIGNMENT_WIDTH +
1314                     gtypes_nr[1] * UL_ALIGNMENT_WIDTH +
1315                     ftypes_nr[2] * U_ALIGNMENT_WIDTH < ftypes_nr[2])
1316                         /* Overflow */
1317                         return -1;
1318
1319                 n = MINIMUM(f_size - ftypes_nr[0] * ULL_ALIGNMENT_WIDTH
1320                                    - ftypes_nr[1] * UL_ALIGNMENT_WIDTH
1321                                    - ftypes_nr[2] * U_ALIGNMENT_WIDTH,
1322                             g_size - gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
1323                                    - gtypes_nr[1] * UL_ALIGNMENT_WIDTH
1324                                    - gtypes_nr[2] * U_ALIGNMENT_WIDTH);
1325                 if ((gtypes_nr[0] * ULL_ALIGNMENT_WIDTH +
1326                      gtypes_nr[1] * UL_ALIGNMENT_WIDTH +
1327                      ftypes_nr[2] * U_ALIGNMENT_WIDTH >= b_size) ||
1328                     (gtypes_nr[0] * ULL_ALIGNMENT_WIDTH +
1329                      gtypes_nr[1] * UL_ALIGNMENT_WIDTH +
1330                      gtypes_nr[2] * U_ALIGNMENT_WIDTH + n > b_size) ||
1331                     (gtypes_nr[0] * ULL_ALIGNMENT_WIDTH +
1332                      gtypes_nr[1] * UL_ALIGNMENT_WIDTH +
1333                      ftypes_nr[2] * U_ALIGNMENT_WIDTH + n > b_size))
1334                         return -1;
1335
1336                 memmove(((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
1337                                       + gtypes_nr[1] * UL_ALIGNMENT_WIDTH
1338                                       + gtypes_nr[2] * U_ALIGNMENT_WIDTH,
1339                         ((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
1340                                       + gtypes_nr[1] * UL_ALIGNMENT_WIDTH
1341                                       + ftypes_nr[2] * U_ALIGNMENT_WIDTH, n);
1342                 if (d > 0) {
1343                         memset(((char *) ps) + gtypes_nr[0] * ULL_ALIGNMENT_WIDTH
1344                                              + gtypes_nr[1] * UL_ALIGNMENT_WIDTH
1345                                              + ftypes_nr[2] * U_ALIGNMENT_WIDTH,
1346                                0, d * U_ALIGNMENT_WIDTH);
1347                 }
1348         }
1349         return 0;
1350 }
1351
1352 /*
1353  ***************************************************************************
1354  * Read data from a system activity data file.
1355  *
1356  * IN:
1357  * @ifd         Input file descriptor.
1358  * @buffer      Buffer where data are read.
1359  * @size        Number of bytes to read.
1360  * @mode        If set to HARD_SIZE, indicate that an EOF should be considered
1361  *              as an error.
1362  * @oneof       Set to UEOF_CONT if an unexpected end of file should not make
1363  *              sadf stop. Default behavior is to stop on unexpected EOF.
1364  *
1365  * RETURNS:
1366  * 1 if EOF has been reached,
1367  * 2 if an unexpected EOF has been reached (and sadf was told to continue),
1368  * 0 otherwise.
1369  ***************************************************************************
1370  */
1371 int sa_fread(int ifd, void *buffer, size_t size, int mode, int oneof)
1372 {
1373         ssize_t n;
1374
1375         if ((n = read(ifd, buffer, size)) < 0) {
1376                 fprintf(stderr, _("Error while reading system activity file: %s\n"),
1377                         strerror(errno));
1378                 close(ifd);
1379                 exit(2);
1380         }
1381
1382         if (!n && (mode == SOFT_SIZE))
1383                 return 1;       /* EOF */
1384
1385         if (n < size) {
1386                 fprintf(stderr, _("End of system activity file unexpected\n"));
1387                 if (oneof == UEOF_CONT)
1388                         return 2;
1389                 close(ifd);
1390                 exit(2);
1391         }
1392
1393         return 0;
1394 }
1395
1396 /*
1397  ***************************************************************************
1398  * Skip unknown extra structures present in file.
1399  *
1400  * IN:
1401  * @ifd         System activity data file descriptor.
1402  * @endian_mismatch
1403  *              TRUE if file's data don't match current machine's endianness.
1404  * @arch_64     TRUE if file's data come from a 64 bit machine.
1405  *
1406  * RETURNS:
1407  * -1 on error, 0 otherwise.
1408  ***************************************************************************
1409  */
1410 int skip_extra_struct(int ifd, int endian_mismatch, int arch_64)
1411 {
1412         int i;
1413         struct extra_desc xtra_d;
1414
1415         do {
1416                 /* Read extra structure description */
1417                 sa_fread(ifd, &xtra_d, EXTRA_DESC_SIZE, HARD_SIZE, UEOF_STOP);
1418
1419                 /*
1420                  * We don't need to remap as the extra_desc structure won't change,
1421                  * but we may need to normalize endianness anyway.
1422                  */
1423                 if (endian_mismatch) {
1424                         swap_struct(extra_desc_types_nr, &xtra_d, arch_64);
1425                 }
1426
1427                 /* Check values consistency */
1428                 if (MAP_SIZE(xtra_d.extra_types_nr) > xtra_d.extra_size) {
1429 #ifdef DEBUG
1430                         fprintf(stderr, "%s: extra_size=%u types=%d,%d,%d\n",
1431                                 __FUNCTION__, xtra_d.extra_size,
1432                                 xtra_d.extra_types_nr[0], xtra_d.extra_types_nr[1], xtra_d.extra_types_nr[2]);
1433 #endif
1434                         return -1;
1435                 }
1436
1437                 if ((xtra_d.extra_nr > MAX_EXTRA_NR) || (xtra_d.extra_size > MAX_EXTRA_SIZE)) {
1438 #ifdef DEBUG
1439                         fprintf(stderr, "%s: extra_size=%u extra_nr=%u\n",
1440                                 __FUNCTION__, xtra_d.extra_size, xtra_d.extra_size);
1441 #endif
1442                         return -1;
1443                 }
1444
1445                 /* Ignore current unknown extra structures */
1446                 for (i = 0; i < xtra_d.extra_nr; i++) {
1447                         if (lseek(ifd, xtra_d.extra_size, SEEK_CUR) < xtra_d.extra_size)
1448                                 return -1;
1449                 }
1450         }
1451         while (xtra_d.extra_next);
1452
1453         return 0;
1454 }
1455
1456 /*
1457  ***************************************************************************
1458  * Read the record header of current sample and process it.
1459  *
1460  * IN:
1461  * @ifd         Input file descriptor.
1462  * @buffer      Buffer where data will be read.
1463  * @record_hdr  Structure where record header will be saved.
1464  * @file_hdr    file_hdr structure containing data read from file standard
1465  *              header.
1466  * @arch_64     TRUE if file's data come from a 64-bit machine.
1467  * @endian_mismatch
1468  *              TRUE if data read from file don't match current machine's
1469  *              endianness.
1470  * @oneof       Set to EOF_CONT if an unexpected end of file should not make
1471  *              sadf stop. Default behavior is to stop on unexpected EOF.
1472  * @b_size      @buffer size.
1473  * @flags       Flags for common options and system state.
1474  * @ofmt        Pointer on report output format structure.
1475  *
1476  * OUT:
1477  * @record_hdr  Record header for current sample.
1478  *
1479  * RETURNS:
1480  * 1 if EOF has been reached,
1481  * 2 if an error has been encountered (e.g. unexpected EOF),
1482  * 0 otherwise.
1483  ***************************************************************************
1484  */
1485 int read_record_hdr(int ifd, void *buffer, struct record_header *record_hdr,
1486                     struct file_header *file_hdr, int arch_64, int endian_mismatch,
1487                     int oneof, size_t b_size, uint64_t flags, struct report_format *ofmt)
1488 {
1489         int rc;
1490
1491         do {
1492                 if ((rc = sa_fread(ifd, buffer, (size_t) file_hdr->rec_size, SOFT_SIZE, oneof)) != 0)
1493                         /* End of sa data file */
1494                         return rc;
1495
1496                 /* Remap record header structure to that expected by current version */
1497                 if (remap_struct(rec_types_nr, file_hdr->rec_types_nr, buffer,
1498                                  file_hdr->rec_size, RECORD_HEADER_SIZE, b_size) < 0)
1499                         return 2;
1500                 memcpy(record_hdr, buffer, RECORD_HEADER_SIZE);
1501
1502                 /* Normalize endianness */
1503                 if (endian_mismatch) {
1504                         swap_struct(rec_types_nr, record_hdr, arch_64);
1505                 }
1506
1507                 /* Raw output in debug mode */
1508                 if (DISPLAY_DEBUG_MODE(flags) && (ofmt->id == F_RAW_OUTPUT)) {
1509                         char out[128];
1510
1511                         sprintf(out, "# uptime_cs; %llu; ust_time; %llu; extra_next; %u; record_type; %d; HH:MM:SS; %02d:%02d:%02d\n",
1512                                record_hdr->uptime_cs, record_hdr->ust_time,
1513                                record_hdr->extra_next, record_hdr->record_type,
1514                                record_hdr->hour, record_hdr->minute, record_hdr->second);
1515                         cprintf_s(IS_COMMENT, "%s", out);
1516                 }
1517
1518                 /* Sanity checks */
1519                 if ((record_hdr->record_type <= 0) || (record_hdr->record_type > R_EXTRA_MAX) ||
1520                     (record_hdr->hour > 23) || (record_hdr->minute > 59) || (record_hdr->second > 60)) {
1521 #ifdef DEBUG
1522                         fprintf(stderr, "%s: record_type=%d HH:MM:SS=%02d:%02d:%02d\n",
1523                                 __FUNCTION__, record_hdr->record_type,
1524                                 record_hdr->hour, record_hdr->minute, record_hdr->second);
1525 #endif
1526                         return 2;
1527                 }
1528
1529                 /*
1530                  * Skip unknown extra structures if present.
1531                  * This will be done later for R_COMMENT and R_RESTART records, as extra structures
1532                  * are saved after the comment or the number of CPU.
1533                  */
1534                 if ((record_hdr->record_type != R_COMMENT) && (record_hdr->record_type != R_RESTART) &&
1535                     record_hdr->extra_next && (skip_extra_struct(ifd, endian_mismatch, arch_64) < 0))
1536                         return 2;
1537         }
1538         while ((record_hdr->record_type >= R_EXTRA_MIN) && (record_hdr->record_type <= R_EXTRA_MAX)) ;
1539
1540         return 0;
1541 }
1542
1543 /*
1544  ***************************************************************************
1545  * Move structures data.
1546  *
1547  * IN:
1548  * @act         Array of activities.
1549  * @id_seq      Activity sequence in file.
1550  * @record_hdr  Current record header.
1551  * @dest        Index in array where stats have to be copied to.
1552  * @src         Index in array where stats to copy are.
1553  ***************************************************************************
1554  */
1555 void copy_structures(struct activity *act[], unsigned int id_seq[],
1556                      struct record_header record_hdr[], int dest, int src)
1557 {
1558         int i, p;
1559
1560         memcpy(&record_hdr[dest], &record_hdr[src], RECORD_HEADER_SIZE);
1561
1562         for (i = 0; i < NR_ACT; i++) {
1563
1564                 if (!id_seq[i])
1565                         continue;
1566
1567                 p = get_activity_position(act, id_seq[i], EXIT_IF_NOT_FOUND);
1568
1569                 memcpy(act[p]->buf[dest], act[p]->buf[src],
1570                        (size_t) act[p]->msize * (size_t) act[p]->nr_allocated * (size_t) act[p]->nr2);
1571                 act[p]->nr[dest] = act[p]->nr[src];
1572         }
1573 }
1574
1575 /*
1576  ***************************************************************************
1577  * Read an __nr_t value from file.
1578  * Such a value can be the new number of CPU saved after a RESTART record,
1579  * or the number of structures to read saved before the structures containing
1580  * statistics for an activity with a varying number of items in file.
1581  *
1582  * IN:
1583  * @ifd         Input file descriptor.
1584  * @file        Name of file being read.
1585  * @file_magic  file_magic structure filled with file magic header data.
1586  * @endian_mismatch
1587  *              TRUE if file's data don't match current machine's endianness.
1588  * @arch_64     TRUE if file's data come from a 64 bit machine.
1589  * @non_zero    TRUE if value should not be zero.
1590  *
1591  * RETURNS:
1592  * __nr_t value, as read from file.
1593  ***************************************************************************
1594  */
1595 __nr_t read_nr_value(int ifd, char *file, struct file_magic *file_magic,
1596                      int endian_mismatch, int arch_64, int non_zero)
1597 {
1598         __nr_t value;
1599         unsigned int nr_types_nr[]  = {0, 0, 1};
1600
1601         sa_fread(ifd, &value, sizeof(__nr_t), HARD_SIZE, UEOF_STOP);
1602
1603         /* Normalize endianness for file_activity structures */
1604         if (endian_mismatch) {
1605                 swap_struct(nr_types_nr, &value, arch_64);
1606         }
1607
1608         if ((non_zero && !value) || (value < 0)) {
1609 #ifdef DEBUG
1610                 fprintf(stderr, "%s: Value=%d\n",
1611                         __FUNCTION__, value);
1612 #endif
1613                 /* Value number cannot be zero or negative */
1614                 handle_invalid_sa_file(ifd, file_magic, file, 0);
1615         }
1616
1617         return value;
1618 }
1619
1620 /*
1621  ***************************************************************************
1622  * Read varying part of the statistics from a daily data file.
1623  *
1624  * IN:
1625  * @act         Array of activities.
1626  * @curr        Index in array for current sample statistics.
1627  * @ifd         Input file descriptor.
1628  * @act_nr      Number of activities in file.
1629  * @file_actlst Activity list in file.
1630  * @endian_mismatch
1631  *              TRUE if file's data don't match current machine's endianness.
1632  * @arch_64     TRUE if file's data come from a 64 bit machine.
1633  * @dfile       Name of system activity data file.
1634  * @file_magic  file_magic structure containing data read from file magic
1635  *              header.
1636  * @oneof       Set to UEOF_CONT if an unexpected end of file should not make
1637  *              sadf stop. Default behavior is to stop on unexpected EOF.
1638  *
1639  * RETURNS:
1640  * 2 if an error has been encountered (e.g. unexpected EOF),
1641  * 0 otherwise.
1642  ***************************************************************************
1643  */
1644 int read_file_stat_bunch(struct activity *act[], int curr, int ifd, int act_nr,
1645                          struct file_activity *file_actlst, int endian_mismatch,
1646                          int arch_64, char *dfile, struct file_magic *file_magic,
1647                          int oneof)
1648 {
1649         int i, j, p;
1650         struct file_activity *fal = file_actlst;
1651         off_t offset;
1652         __nr_t nr_value;
1653
1654         for (i = 0; i < act_nr; i++, fal++) {
1655
1656                 /* Read __nr_t value preceding statistics structures if it exists */
1657                 if (fal->has_nr) {
1658                         nr_value = read_nr_value(ifd, dfile, file_magic,
1659                                                  endian_mismatch, arch_64, FALSE);
1660                 }
1661                 else {
1662                         nr_value = fal->nr;
1663                 }
1664
1665                 if (nr_value > NR_MAX) {
1666 #ifdef DEBUG
1667                         fprintf(stderr, "%s: Value=%d Max=%d\n", __FUNCTION__, nr_value, NR_MAX);
1668 #endif
1669                         handle_invalid_sa_file(ifd, file_magic, dfile, 0);
1670                 }
1671
1672                 if (((p = get_activity_position(act, fal->id, RESUME_IF_NOT_FOUND)) < 0) ||
1673                     (act[p]->magic != fal->magic)) {
1674                         /*
1675                          * Ignore current activity in file, which is unknown to
1676                          * current sysstat version or has an unknown format.
1677                          */
1678                         if (nr_value) {
1679                                 offset = (off_t) fal->size * (off_t) nr_value * (off_t) fal->nr2;
1680                                 if (lseek(ifd, offset, SEEK_CUR) < offset) {
1681                                         close(ifd);
1682                                         perror("lseek");
1683                                         if (oneof == UEOF_CONT)
1684                                                 return 2;
1685                                         exit(2);
1686                                 }
1687                         }
1688                         continue;
1689                 }
1690
1691                 if (nr_value > act[p]->nr_max) {
1692 #ifdef DEBUG
1693                         fprintf(stderr, "%s: %s: Value=%d Max=%d\n",
1694                                 __FUNCTION__, act[p]->name, nr_value, act[p]->nr_max);
1695 #endif
1696                         handle_invalid_sa_file(ifd, file_magic, dfile, 0);
1697                 }
1698                 act[p]->nr[curr] = nr_value;
1699
1700                 /* Reallocate buffers if needed */
1701                 if (nr_value > act[p]->nr_allocated) {
1702                         reallocate_all_buffers(act[p], nr_value);
1703                 }
1704
1705                 /*
1706                  * For persistent activities, we must make sure that no statistics
1707                  * from a previous iteration remain, especially if the number
1708                  * of structures read is smaller than @nr_ini.
1709                  */
1710                 if (HAS_PERSISTENT_VALUES(act[p]->options)) {
1711                     memset(act[p]->buf[curr], 0,
1712                            (size_t) act[p]->msize * (size_t) act[p]->nr_ini * (size_t) act[p]->nr2);
1713                 }
1714
1715                 /* OK, this is a known activity: Read the stats structures */
1716                 if ((nr_value > 0) &&
1717                     ((nr_value > 1) || (act[p]->nr2 > 1)) &&
1718                     (act[p]->msize > act[p]->fsize)) {
1719
1720                         for (j = 0; j < (nr_value * act[p]->nr2); j++) {
1721                                 if (sa_fread(ifd, (char *) act[p]->buf[curr] + j * act[p]->msize,
1722                                          (size_t) act[p]->fsize, HARD_SIZE, oneof) > 0)
1723                                         /* Unexpected EOF */
1724                                         return 2;
1725                         }
1726                 }
1727                 else if (nr_value > 0) {
1728                         /*
1729                          * Note: If msize was smaller than fsize,
1730                          * then it has been set to fsize in check_file_actlst().
1731                          */
1732                         if (sa_fread(ifd, act[p]->buf[curr],
1733                                  (size_t) act[p]->fsize * (size_t) nr_value * (size_t) act[p]->nr2,
1734                                  HARD_SIZE, oneof) > 0)
1735                                 /* Unexpected EOF */
1736                                 return 2;
1737                 }
1738                 else {
1739                         /* nr_value == 0: Nothing to read */
1740                         continue;
1741                 }
1742
1743                 /* Normalize endianness for current activity's structures */
1744                 if (endian_mismatch) {
1745                         for (j = 0; j < (nr_value * act[p]->nr2); j++) {
1746                                 swap_struct(act[p]->ftypes_nr, (char *) act[p]->buf[curr] + j * act[p]->msize,
1747                                             arch_64);
1748                         }
1749                 }
1750
1751                 /* Remap structure's fields to those known by current sysstat version */
1752                 for (j = 0; j < (nr_value * act[p]->nr2); j++) {
1753                         if (remap_struct(act[p]->gtypes_nr, act[p]->ftypes_nr,
1754                                          (char *) act[p]->buf[curr] + j * act[p]->msize,
1755                                          act[p]->fsize, act[p]->msize, act[p]->msize) < 0)
1756                                 return 2;
1757                 }
1758         }
1759
1760         return 0;
1761 }
1762
1763 /*
1764  ***************************************************************************
1765  * Open a sysstat activity data file and read its magic structure.
1766  *
1767  * IN:
1768  * @dfile       Name of system activity data file.
1769  * @ignore      Set to 1 if a true sysstat activity file but with a bad
1770  *              format should not yield an error message. Useful with
1771  *              sadf -H and sadf -c.
1772  *
1773  * OUT:
1774  * @fd          System activity data file descriptor.
1775  * @file_magic  file_magic structure containing data read from file magic
1776  *              header.
1777  * @endian_mismatch
1778  *              TRUE if file's data don't match current machine's endianness.
1779  * @do_swap     TRUE if endianness should be normalized for sysstat_magic
1780  *              and format_magic numbers.
1781  *
1782  * RETURNS:
1783  * -1 if data file is a sysstat file with an old format (which we cannot
1784  * read), 0 otherwise.
1785  ***************************************************************************
1786  */
1787 int sa_open_read_magic(int *fd, char *dfile, struct file_magic *file_magic,
1788                        int ignore, int *endian_mismatch, int do_swap)
1789 {
1790         int n;
1791         unsigned int fm_types_nr[] = {FILE_MAGIC_ULL_NR, FILE_MAGIC_UL_NR, FILE_MAGIC_U_NR};
1792
1793         /* Open sa data file */
1794         if ((*fd = open(dfile, O_RDONLY)) < 0) {
1795                 int saved_errno = errno;
1796
1797                 fprintf(stderr, _("Cannot open %s: %s\n"), dfile, strerror(errno));
1798
1799                 if ((saved_errno == ENOENT) && default_file_used) {
1800                         fprintf(stderr, _("Please check if data collecting is enabled\n"));
1801                 }
1802                 exit(2);
1803         }
1804
1805         /* Read file magic data */
1806         n = read(*fd, file_magic, FILE_MAGIC_SIZE);
1807
1808         if ((n != FILE_MAGIC_SIZE) ||
1809             ((file_magic->sysstat_magic != SYSSTAT_MAGIC) && (file_magic->sysstat_magic != SYSSTAT_MAGIC_SWAPPED)) ||
1810             ((file_magic->format_magic != FORMAT_MAGIC) && (file_magic->format_magic != FORMAT_MAGIC_SWAPPED) && !ignore)) {
1811 #ifdef DEBUG
1812                 fprintf(stderr, "%s: Bytes read=%d sysstat_magic=%x format_magic=%x\n",
1813                         __FUNCTION__, n, file_magic->sysstat_magic, file_magic->format_magic);
1814 #endif
1815                 /* Display error message and exit */
1816                 handle_invalid_sa_file(*fd, file_magic, dfile, n);
1817         }
1818
1819         *endian_mismatch = (file_magic->sysstat_magic != SYSSTAT_MAGIC);
1820         if (*endian_mismatch) {
1821                 if (do_swap) {
1822                         /* Swap bytes for file_magic fields */
1823                         file_magic->sysstat_magic = SYSSTAT_MAGIC;
1824                         file_magic->format_magic  = __builtin_bswap16(file_magic->format_magic);
1825                 }
1826                 /*
1827                  * Start swapping at field "header_size" position.
1828                  * May not exist for older versions but in this case, it won't be used.
1829                  */
1830                 swap_struct(fm_types_nr, &file_magic->header_size, 0);
1831         }
1832
1833         if ((file_magic->sysstat_version > 10) ||
1834             ((file_magic->sysstat_version == 10) && (file_magic->sysstat_patchlevel >= 3))) {
1835                 /* header_size field exists only for sysstat versions 10.3.1 and later */
1836                 if ((file_magic->header_size <= MIN_FILE_HEADER_SIZE) ||
1837                     (file_magic->header_size > MAX_FILE_HEADER_SIZE)) {
1838 #ifdef DEBUG
1839                         fprintf(stderr, "%s: header_size=%u\n",
1840                                 __FUNCTION__, file_magic->header_size);
1841 #endif
1842                         /* Display error message and exit */
1843                         handle_invalid_sa_file(*fd, file_magic, dfile, n);
1844                 }
1845         }
1846         if ((file_magic->sysstat_version > 11) ||
1847             ((file_magic->sysstat_version == 11) && (file_magic->sysstat_patchlevel >= 7))) {
1848                 /* hdr_types_nr field exists only for sysstat versions 11.7.1 and later */
1849                 if (MAP_SIZE(file_magic->hdr_types_nr) > file_magic->header_size) {
1850 #ifdef DEBUG
1851                         fprintf(stderr, "%s: map_size=%u header_size=%u\n",
1852                                 __FUNCTION__, MAP_SIZE(file_magic->hdr_types_nr), file_magic->header_size);
1853 #endif
1854                         handle_invalid_sa_file(*fd, file_magic, dfile, n);
1855                 }
1856         }
1857
1858         if ((file_magic->format_magic != FORMAT_MAGIC) &&
1859             (file_magic->format_magic != FORMAT_MAGIC_SWAPPED))
1860                 /*
1861                  * This is an old (or new) sa datafile format to
1862                  * be read by sadf (since @ignore was set to TRUE).
1863                  */
1864                 return -1;
1865
1866         return 0;
1867 }
1868
1869 /*
1870  ***************************************************************************
1871  * Open a data file, and perform various checks before reading.
1872  * NB: This is called only when reading a datafile (sar and sadf), never
1873  * when writing or appending data to a datafile.
1874  *
1875  * IN:
1876  * @dfile       Name of system activity data file.
1877  * @act         Array of activities.
1878  * @flags       Flags for common options and system state.
1879  *
1880  * OUT:
1881  * @ifd         System activity data file descriptor.
1882  * @file_magic  file_magic structure containing data read from file magic
1883  *              header.
1884  * @file_hdr    file_hdr structure containing data read from file standard
1885  *              header.
1886  * @file_actlst Acvtivity list in file.
1887  * @id_seq      Activity sequence.
1888  * @endian_mismatch
1889  *              TRUE if file's data don't match current machine's endianness.
1890  * @arch_64     TRUE if file's data come from a 64 bit machine.
1891  ***************************************************************************
1892  */
1893 void check_file_actlst(int *ifd, char *dfile, struct activity *act[], uint64_t flags,
1894                        struct file_magic *file_magic, struct file_header *file_hdr,
1895                        struct file_activity **file_actlst, unsigned int id_seq[],
1896                        int *endian_mismatch, int *arch_64)
1897 {
1898         int i, j, k, p, skip;
1899         struct file_activity *fal;
1900         void *buffer = NULL;
1901         size_t bh_size = FILE_HEADER_SIZE;
1902         size_t ba_size = FILE_ACTIVITY_SIZE;
1903
1904         /* Open sa data file and read its magic structure */
1905         if (sa_open_read_magic(ifd, dfile, file_magic,
1906                                DISPLAY_HDR_ONLY(flags), endian_mismatch, TRUE) < 0)
1907                 /*
1908                  * Not current sysstat's format.
1909                  * Return now so that sadf -H can display at least
1910                  * file's version and magic number.
1911                  */
1912                 return;
1913
1914         /*
1915          * We know now that we have a *compatible* sysstat datafile format
1916          * (correct FORMAT_MAGIC value), and in this case, we should have
1917          * checked header_size value. Anyway, with a corrupted datafile,
1918          * this may not be the case. So check again.
1919          */
1920         if ((file_magic->header_size <= MIN_FILE_HEADER_SIZE) ||
1921             (file_magic->header_size > MAX_FILE_HEADER_SIZE)) {
1922 #ifdef DEBUG
1923                 fprintf(stderr, "%s: header_size=%u\n",
1924                         __FUNCTION__, file_magic->header_size);
1925 #endif
1926                 goto format_error;
1927         }
1928
1929         /* Allocate buffer for file_header structure */
1930         if (file_magic->header_size > FILE_HEADER_SIZE) {
1931                 bh_size = file_magic->header_size;
1932         }
1933         SREALLOC(buffer, char, bh_size);
1934
1935         /* Read sa data file standard header and allocate activity list */
1936         sa_fread(*ifd, buffer, (size_t) file_magic->header_size, HARD_SIZE, UEOF_STOP);
1937         /*
1938          * Data file header size (file_magic->header_size) may be greater or
1939          * smaller than FILE_HEADER_SIZE. Remap the fields of the file header
1940          * then copy its contents to the expected structure.
1941          */
1942         if (remap_struct(hdr_types_nr, file_magic->hdr_types_nr, buffer,
1943                          file_magic->header_size, FILE_HEADER_SIZE, bh_size) < 0)
1944                 goto format_error;
1945
1946         memcpy(file_hdr, buffer, FILE_HEADER_SIZE);
1947         free(buffer);
1948         buffer = NULL;
1949
1950         /* Tell that data come from a 64 bit machine */
1951         *arch_64 = (file_hdr->sa_sizeof_long == SIZEOF_LONG_64BIT);
1952
1953         /* Normalize endianness for file_hdr structure */
1954         if (*endian_mismatch) {
1955                 swap_struct(hdr_types_nr, file_hdr, *arch_64);
1956         }
1957
1958         /*
1959          * Sanity checks.
1960          * NB: Compare against MAX_NR_ACT and not NR_ACT because
1961          * we are maybe reading a datafile from a future sysstat version
1962          * with more activities than known today.
1963          */
1964         if ((file_hdr->sa_act_nr > MAX_NR_ACT) ||
1965             (file_hdr->act_size > MAX_FILE_ACTIVITY_SIZE) ||
1966             (file_hdr->rec_size > MAX_RECORD_HEADER_SIZE) ||
1967             (MAP_SIZE(file_hdr->act_types_nr) > file_hdr->act_size) ||
1968             (MAP_SIZE(file_hdr->rec_types_nr) > file_hdr->rec_size)) {
1969 #ifdef DEBUG
1970                 fprintf(stderr, "%s: sa_act_nr=%d act_size=%u rec_size=%u map_size(act)=%u map_size(rec)=%u\n",
1971                         __FUNCTION__, file_hdr->sa_act_nr, file_hdr->act_size, file_hdr->rec_size,
1972                         MAP_SIZE(file_hdr->act_types_nr), MAP_SIZE(file_hdr->rec_types_nr));
1973 #endif
1974                 /* Maybe a "false positive" sysstat datafile? */
1975                 goto format_error;
1976         }
1977
1978         /* Allocate buffer for file_activity structures */
1979         if (file_hdr->act_size > FILE_ACTIVITY_SIZE) {
1980                 ba_size = file_hdr->act_size;
1981         }
1982         SREALLOC(buffer, char, ba_size);
1983         SREALLOC(*file_actlst, struct file_activity, FILE_ACTIVITY_SIZE * file_hdr->sa_act_nr);
1984         fal = *file_actlst;
1985
1986         /* Read activity list */
1987         j = 0;
1988         for (i = 0; i < file_hdr->sa_act_nr; i++, fal++) {
1989
1990                 /* Read current file_activity structure from file */
1991                 sa_fread(*ifd, buffer, (size_t) file_hdr->act_size, HARD_SIZE, UEOF_STOP);
1992
1993                 /*
1994                  * Data file_activity size (file_hdr->act_size) may be greater or
1995                  * smaller than FILE_ACTIVITY_SIZE. Remap the fields of the file's structure
1996                  * then copy its contents to the expected structure.
1997                  */
1998                 if (remap_struct(act_types_nr, file_hdr->act_types_nr, buffer,
1999                              file_hdr->act_size, FILE_ACTIVITY_SIZE, ba_size) < 0)
2000                         goto format_error;
2001                 memcpy(fal, buffer, FILE_ACTIVITY_SIZE);
2002
2003                 /* Normalize endianness for file_activity structures */
2004                 if (*endian_mismatch) {
2005                         swap_struct(act_types_nr, fal, *arch_64);
2006                 }
2007
2008                 /*
2009                  * Every activity, known or unknown, should have
2010                  * at least one item and sub-item, and a size value in
2011                  * a defined range.
2012                  * Also check that the number of items and sub-items
2013                  * doesn't exceed a max value. This is necessary
2014                  * because we will use @nr and @nr2 to
2015                  * allocate memory to read the file contents. So we
2016                  * must make sure the file is not corrupted.
2017                  * NB: Another check will be made below for known
2018                  * activities which have each a specific max value.
2019                  */
2020                 if ((fal->nr < 1) || (fal->nr2 < 1) ||
2021                     (fal->nr > NR_MAX) || (fal->nr2 > NR2_MAX) ||
2022                     (fal->size <= 0) || (fal->size > MAX_ITEM_STRUCT_SIZE)) {
2023 #ifdef DEBUG
2024                         fprintf(stderr, "%s: id=%d nr=%d nr2=%d size=%d\n",
2025                                 __FUNCTION__, fal->id, fal->nr, fal->nr2, fal->size);
2026 #endif
2027                         goto format_error;
2028                 }
2029
2030                 if ((p = get_activity_position(act, fal->id, RESUME_IF_NOT_FOUND)) < 0)
2031                         /* Unknown activity */
2032                         continue;
2033
2034                 if ((fal->magic != act[p]->magic) && !DISPLAY_HDR_ONLY(flags)) {
2035                         skip = TRUE;
2036                 }
2037                 else {
2038                         skip = FALSE;
2039                 }
2040
2041                 /* Check max value for known activities */
2042                 if (fal->nr > act[p]->nr_max) {
2043 #ifdef DEBUG
2044                         fprintf(stderr, "%s: id=%d nr=%d nr_max=%d\n",
2045                                 __FUNCTION__, fal->id, fal->nr, act[p]->nr_max);
2046 #endif
2047                         goto format_error;
2048                 }
2049
2050                 /*
2051                  * Number of fields of each type ("long long", or "long"
2052                  * or "int") composing the structure with statistics may
2053                  * only increase with new sysstat versions, unless we change
2054                  * the activity's magic number. Here, we may
2055                  * be reading a file created by current sysstat version,
2056                  * or by an older or a newer version.
2057                  */
2058                 if (!(((fal->types_nr[0] >= act[p]->gtypes_nr[0]) &&
2059                      (fal->types_nr[1] >= act[p]->gtypes_nr[1]) &&
2060                      (fal->types_nr[2] >= act[p]->gtypes_nr[2]))
2061                      ||
2062                      ((fal->types_nr[0] <= act[p]->gtypes_nr[0]) &&
2063                      (fal->types_nr[1] <= act[p]->gtypes_nr[1]) &&
2064                      (fal->types_nr[2] <= act[p]->gtypes_nr[2]))) &&
2065                      (fal->magic == act[p]->magic) && !DISPLAY_HDR_ONLY(flags)) {
2066 #ifdef DEBUG
2067                         fprintf(stderr, "%s: id=%d file=%d,%d,%d activity=%d,%d,%d\n",
2068                                 __FUNCTION__, fal->id, fal->types_nr[0], fal->types_nr[1], fal->types_nr[2],
2069                                 act[p]->gtypes_nr[0], act[p]->gtypes_nr[1], act[p]->gtypes_nr[2]);
2070 #endif
2071                         goto format_error;
2072                 }
2073
2074                 if (MAP_SIZE(fal->types_nr) > fal->size) {
2075 #ifdef DEBUG
2076                 fprintf(stderr, "%s: id=%d size=%u map_size=%u\n",
2077                         __FUNCTION__, fal->id, fal->size, MAP_SIZE(fal->types_nr));
2078 #endif
2079                         goto format_error;
2080                 }
2081
2082                 for (k = 0; k < 3; k++) {
2083                         act[p]->ftypes_nr[k] = fal->types_nr[k];
2084                 }
2085
2086                 if (fal->size > act[p]->msize) {
2087                         act[p]->msize = fal->size;
2088                 }
2089
2090                 act[p]->nr_ini = fal->nr;
2091                 act[p]->nr2    = fal->nr2;
2092                 act[p]->fsize  = fal->size;
2093
2094                 /*
2095                  * This is a known activity with a known format
2096                  * (magical number). Only such activities will be displayed.
2097                  * (Well, this may also be an unknown format if we have entered sadf -H.)
2098                  */
2099                 if (!skip) {
2100                         id_seq[j++] = fal->id;
2101                 }
2102         }
2103
2104         while (j < NR_ACT) {
2105                 id_seq[j++] = 0;
2106         }
2107
2108         free(buffer);
2109         buffer = NULL;
2110
2111         /* Check that at least one activity selected by the user is available in file */
2112         for (i = 0; i < NR_ACT; i++) {
2113
2114                 if (!IS_SELECTED(act[i]->options))
2115                         continue;
2116
2117                 /* Here is a selected activity: Does it exist in file? */
2118                 fal = *file_actlst;
2119                 for (j = 0; j < file_hdr->sa_act_nr; j++, fal++) {
2120                         if (act[i]->id == fal->id)
2121                                 break;
2122                 }
2123                 if (j == file_hdr->sa_act_nr) {
2124                         /* No: Unselect it */
2125                         act[i]->options &= ~AO_SELECTED;
2126                 }
2127         }
2128
2129         /*
2130          * None of selected activities exist in file: Abort.
2131          * NB: Error is ignored if we only want to display
2132          * datafile header (sadf -H).
2133          */
2134         if (!get_activity_nr(act, AO_SELECTED, COUNT_ACTIVITIES) && !DISPLAY_HDR_ONLY(flags)) {
2135                 fprintf(stderr, _("Requested activities not available in file %s\n"),
2136                         dfile);
2137                 close(*ifd);
2138                 exit(1);
2139         }
2140
2141         /*
2142          * Check if there are some extra structures.
2143          * We will just skip them as they are unknown for now.
2144          */
2145         if (file_hdr->extra_next && (skip_extra_struct(*ifd, *endian_mismatch, *arch_64) < 0))
2146                 goto format_error;
2147
2148         return;
2149
2150 format_error:
2151         if (buffer) {
2152                 free(buffer);
2153         }
2154         handle_invalid_sa_file(*ifd, file_magic, dfile, 0);
2155 }
2156
2157 /*
2158  ***************************************************************************
2159  * Look for item in list.
2160  *
2161  * IN:
2162  * @list        Pointer on the start of the linked list.
2163  * @item_name   Item name to look for.
2164  *
2165  * RETURNS:
2166  * 1 if item found in list, 0 otherwise.
2167  ***************************************************************************
2168  */
2169 int search_list_item(struct sa_item *list, char *item_name)
2170 {
2171         while (list != NULL) {
2172                 if (!strcmp(list->item_name, item_name))
2173                         return 1;       /* Item found in list */
2174                 list = list->next;
2175         }
2176
2177         /* Item not found */
2178         return 0;
2179 }
2180
2181 /*
2182  ***************************************************************************
2183  * Add item to the list.
2184  *
2185  * IN:
2186  * @list        Address of pointer on the start of the linked list.
2187  * @item_name   Name of the item.
2188  * @max_len     Max length of an item.
2189  *
2190  * RETURNS:
2191  * 1 if item has been added to the list (since it was not previously there),
2192  * and 0 otherwise (item already in list or item name too long).
2193  ***************************************************************************
2194  */
2195 int add_list_item(struct sa_item **list, char *item_name, int max_len)
2196 {
2197         struct sa_item *e;
2198         int len;
2199
2200         if ((len = strnlen(item_name, max_len)) == max_len)
2201                 /* Item too long */
2202                 return 0;
2203
2204         while (*list != NULL) {
2205                 e = *list;
2206                 if (!strcmp(e->item_name, item_name))
2207                         return 0;       /* Item found in list */
2208                 list = &(e->next);
2209         }
2210
2211         /* Item not found: Add it to the list */
2212         SREALLOC(*list, struct sa_item, sizeof(struct sa_item));
2213         e = *list;
2214         if ((e->item_name = (char *) malloc(len + 1)) == NULL) {
2215                 perror("malloc");
2216                 exit(4);
2217         }
2218         strcpy(e->item_name, item_name);
2219
2220         return 1;
2221 }
2222
2223 /*
2224  ***************************************************************************
2225  * Parse sar activities options (also used by sadf).
2226  *
2227  * IN:
2228  * @argv        Arguments list.
2229  * @opt         Index in list of arguments.
2230  * @caller      Indicate whether it's sar or sadf that called this function.
2231  *
2232  * OUT:
2233  * @act         Array of selected activities.
2234  * @flags       Common flags and system state.
2235  *
2236  * RETURNS:
2237  * 0 on success.
2238  ***************************************************************************
2239  */
2240 int parse_sar_opt(char *argv[], int *opt, struct activity *act[],
2241                   uint64_t *flags, int caller)
2242 {
2243         int i, p;
2244
2245         for (i = 1; *(argv[*opt] + i); i++) {
2246                 /*
2247                  * Note: argv[*opt] contains something like "-BruW"
2248                  *     *(argv[*opt] + i) will contain 'B', 'r', etc.
2249                  */
2250
2251                 switch (*(argv[*opt] + i)) {
2252
2253                 case 'A':
2254                         select_all_activities(act);
2255                         *flags |= S_F_OPTION_A;
2256
2257                         /*
2258                          * Force '-r ALL -u ALL -F'.
2259                          * Setting -F is compulsory because corresponding activity
2260                          * has AO_MULTIPLE_OUTPUTS flag set.
2261                          * -P ALL will be set only if corresponding option has
2262                          * not been exlicitly entered on the command line.
2263                          */
2264                         p = get_activity_position(act, A_MEMORY, EXIT_IF_NOT_FOUND);
2265                         act[p]->opt_flags |= AO_F_MEMORY + AO_F_SWAP + AO_F_MEM_ALL;
2266
2267                         p = get_activity_position(act, A_CPU, EXIT_IF_NOT_FOUND);
2268                         act[p]->opt_flags = AO_F_CPU_ALL;
2269
2270                         p = get_activity_position(act, A_FS, EXIT_IF_NOT_FOUND);
2271                         act[p]->opt_flags = AO_F_FILESYSTEM;
2272                         break;
2273
2274                 case 'B':
2275                         SELECT_ACTIVITY(A_PAGE);
2276                         break;
2277
2278                 case 'b':
2279                         SELECT_ACTIVITY(A_IO);
2280                         break;
2281
2282                 case 'C':
2283                         *flags |= S_F_COMMENT;
2284                         break;
2285
2286                 case 'd':
2287                         SELECT_ACTIVITY(A_DISK);
2288                         break;
2289
2290                 case 'F':
2291                         p = get_activity_position(act, A_FS, EXIT_IF_NOT_FOUND);
2292                         act[p]->options |= AO_SELECTED;
2293                         if (!*(argv[*opt] + i + 1) && argv[*opt + 1] && !strcmp(argv[*opt + 1], K_MOUNT)) {
2294                                 (*opt)++;
2295                                 act[p]->opt_flags |= AO_F_MOUNT;
2296                                 return 0;
2297                         }
2298                         else {
2299                                 act[p]->opt_flags |= AO_F_FILESYSTEM;
2300                         }
2301                         break;
2302
2303                 case 'H':
2304                         SELECT_ACTIVITY(A_HUGE);
2305                         break;
2306
2307                 case 'h':
2308                         /* Option -h is equivalent to --pretty --human */
2309                         *flags |= S_F_PRETTY + S_F_UNIT;
2310                         break;
2311
2312                 case 'I':
2313                         p = get_activity_position(act, A_IRQ, EXIT_IF_NOT_FOUND);
2314                         act[p]->options |= AO_SELECTED;
2315
2316                         if (!*(argv[*opt] + i + 1) && argv[*opt + 1] &&
2317                             (!strcmp(argv[*opt + 1], K_ALL) || !strcmp(argv[*opt + 1], K_SUM))) {
2318                                 (*opt)++;
2319                                 /* Select int "sum". Keyword ALL is ignored */
2320                                 if (!strcmp(argv[*opt], K_SUM)) {
2321                                         act[p]->item_list_sz += add_list_item(&(act[p]->item_list), K_LOWERSUM, MAX_SA_IRQ_LEN);
2322                                         act[p]->options |= AO_LIST_ON_CMDLINE;
2323                                 }
2324                                 return 0;
2325                         }
2326                         break;
2327
2328                 case 'j':
2329                         if (!argv[*opt + 1]) {
2330                                 return 1;
2331                         }
2332                         (*opt)++;
2333                         if (!strcmp(argv[*opt], K_SID)) {
2334                                 *flags |= S_F_DEV_SID + S_F_PRETTY;
2335                                 return 0;
2336                         }
2337
2338                         if (strnlen(argv[*opt], sizeof(persistent_name_type)) >= sizeof(persistent_name_type) - 1)
2339                                 return 1;
2340
2341                         strncpy(persistent_name_type, argv[*opt], sizeof(persistent_name_type) - 1);
2342                         persistent_name_type[sizeof(persistent_name_type) - 1] = '\0';
2343                         strtolower(persistent_name_type);
2344                         if (!get_persistent_type_dir(persistent_name_type)) {
2345                                 fprintf(stderr, _("Invalid type of persistent device name\n"));
2346                                 return 2;
2347                         }
2348                         /* Pretty print report (option -j implies option -p) */
2349                         *flags |= S_F_PERSIST_NAME + S_F_PRETTY;
2350                         return 0;
2351                         break;
2352
2353                 case 'p':
2354                         *flags |= S_F_PRETTY;
2355                         break;
2356
2357                 case 'q':
2358                         /* Option -q grouped with other ones */
2359                         SELECT_ACTIVITY(A_QUEUE);
2360                         break;
2361
2362                 case 'r':
2363                         p = get_activity_position(act, A_MEMORY, EXIT_IF_NOT_FOUND);
2364                         act[p]->options   |= AO_SELECTED;
2365                         act[p]->opt_flags |= AO_F_MEMORY;
2366                         if (!*(argv[*opt] + i + 1) && argv[*opt + 1] && !strcmp(argv[*opt + 1], K_ALL)) {
2367                                 (*opt)++;
2368                                 act[p]->opt_flags |= AO_F_MEM_ALL;
2369                                 return 0;
2370                         }
2371                         break;
2372
2373                 case 'S':
2374                         p = get_activity_position(act, A_MEMORY, EXIT_IF_NOT_FOUND);
2375                         act[p]->options   |= AO_SELECTED;
2376                         act[p]->opt_flags |= AO_F_SWAP;
2377                         break;
2378
2379                 case 't':
2380                         /*
2381                          * Check sar option -t here (as it can be combined
2382                          * with other ones, eg. "sar -rtu ..."
2383                          * But sadf option -t is checked in sadf.c as it won't
2384                          * be entered as a sar option after "--".
2385                          */
2386                         if (caller != C_SAR) {
2387                                 return 1;
2388                         }
2389                         *flags |= S_F_TRUE_TIME;
2390                         break;
2391
2392                 case 'u':
2393                         p = get_activity_position(act, A_CPU, EXIT_IF_NOT_FOUND);
2394                         act[p]->options |= AO_SELECTED;
2395                         if (!*(argv[*opt] + i + 1) && argv[*opt + 1] && !strcmp(argv[*opt + 1], K_ALL)) {
2396                                 (*opt)++;
2397                                 act[p]->opt_flags = AO_F_CPU_ALL;
2398                                 return 0;
2399                         }
2400                         else {
2401                                 act[p]->opt_flags = AO_F_CPU_DEF;
2402                         }
2403                         break;
2404
2405                 case 'v':
2406                         SELECT_ACTIVITY(A_KTABLES);
2407                         break;
2408
2409                 case 'w':
2410                         SELECT_ACTIVITY(A_PCSW);
2411                         break;
2412
2413                 case 'W':
2414                         SELECT_ACTIVITY(A_SWAP);
2415                         break;
2416
2417                 case 'y':
2418                         SELECT_ACTIVITY(A_SERIAL);
2419                         break;
2420
2421                 case 'z':
2422                         *flags |= S_F_ZERO_OMIT;
2423                         break;
2424
2425                 case 'V':
2426                         print_version();
2427                         break;
2428
2429                 default:
2430                         return 1;
2431                 }
2432         }
2433         return 0;
2434 }
2435
2436 /*
2437  ***************************************************************************
2438  * Parse sar "-m" option.
2439  *
2440  * IN:
2441  * @argv        Arguments list.
2442  * @opt         Index in list of arguments.
2443  *
2444  * OUT:
2445  * @act         Array of selected activities.
2446  *
2447  * RETURNS:
2448  * 0 on success, 1 otherwise.
2449  ***************************************************************************
2450  */
2451 int parse_sar_m_opt(char *argv[], int *opt, struct activity *act[])
2452 {
2453         char *t;
2454
2455         for (t = strtok(argv[*opt], ","); t; t = strtok(NULL, ",")) {
2456                 if (!strcmp(t, K_CPU)) {
2457                         SELECT_ACTIVITY(A_PWR_CPU);
2458                 }
2459                 else if (!strcmp(t, K_FAN)) {
2460                         SELECT_ACTIVITY(A_PWR_FAN);
2461                 }
2462                 else if (!strcmp(t, K_IN)) {
2463                         SELECT_ACTIVITY(A_PWR_IN);
2464                 }
2465                 else if (!strcmp(t, K_TEMP)) {
2466                         SELECT_ACTIVITY(A_PWR_TEMP);
2467                 }
2468                 else if (!strcmp(t, K_FREQ)) {
2469                         SELECT_ACTIVITY(A_PWR_FREQ);
2470                 }
2471                 else if (!strcmp(t, K_USB)) {
2472                         SELECT_ACTIVITY(A_PWR_USB);
2473                 }
2474                 else if (!strcmp(t, K_ALL)) {
2475                         SELECT_ACTIVITY(A_PWR_CPU);
2476                         SELECT_ACTIVITY(A_PWR_FAN);
2477                         SELECT_ACTIVITY(A_PWR_IN);
2478                         SELECT_ACTIVITY(A_PWR_TEMP);
2479                         SELECT_ACTIVITY(A_PWR_FREQ);
2480                         SELECT_ACTIVITY(A_PWR_USB);
2481                 }
2482                 else
2483                         return 1;
2484         }
2485
2486         (*opt)++;
2487         return 0;
2488 }
2489
2490 /*
2491  ***************************************************************************
2492  * Parse sar "-n" option.
2493  *
2494  * IN:
2495  * @argv        Arguments list.
2496  * @opt         Index in list of arguments.
2497  *
2498  * OUT:
2499  * @act         Array of selected activities.
2500  *
2501  * RETURNS:
2502  * 0 on success, 1 otherwise.
2503  ***************************************************************************
2504  */
2505 int parse_sar_n_opt(char *argv[], int *opt, struct activity *act[])
2506 {
2507         char *t;
2508
2509         for (t = strtok(argv[*opt], ","); t; t = strtok(NULL, ",")) {
2510                 if (!strcmp(t, K_DEV)) {
2511                         SELECT_ACTIVITY(A_NET_DEV);
2512                 }
2513                 else if (!strcmp(t, K_EDEV)) {
2514                         SELECT_ACTIVITY(A_NET_EDEV);
2515                 }
2516                 else if (!strcmp(t, K_SOCK)) {
2517                         SELECT_ACTIVITY(A_NET_SOCK);
2518                 }
2519                 else if (!strcmp(t, K_NFS)) {
2520                         SELECT_ACTIVITY(A_NET_NFS);
2521                 }
2522                 else if (!strcmp(t, K_NFSD)) {
2523                         SELECT_ACTIVITY(A_NET_NFSD);
2524                 }
2525                 else if (!strcmp(t, K_IP)) {
2526                         SELECT_ACTIVITY(A_NET_IP);
2527                 }
2528                 else if (!strcmp(t, K_EIP)) {
2529                         SELECT_ACTIVITY(A_NET_EIP);
2530                 }
2531                 else if (!strcmp(t, K_ICMP)) {
2532                         SELECT_ACTIVITY(A_NET_ICMP);
2533                 }
2534                 else if (!strcmp(t, K_EICMP)) {
2535                         SELECT_ACTIVITY(A_NET_EICMP);
2536                 }
2537                 else if (!strcmp(t, K_TCP)) {
2538                         SELECT_ACTIVITY(A_NET_TCP);
2539                 }
2540                 else if (!strcmp(t, K_ETCP)) {
2541                         SELECT_ACTIVITY(A_NET_ETCP);
2542                 }
2543                 else if (!strcmp(t, K_UDP)) {
2544                         SELECT_ACTIVITY(A_NET_UDP);
2545                 }
2546                 else if (!strcmp(t, K_SOCK6)) {
2547                         SELECT_ACTIVITY(A_NET_SOCK6);
2548                 }
2549                 else if (!strcmp(t, K_IP6)) {
2550                         SELECT_ACTIVITY(A_NET_IP6);
2551                 }
2552                 else if (!strcmp(t, K_EIP6)) {
2553                         SELECT_ACTIVITY(A_NET_EIP6);
2554                 }
2555                 else if (!strcmp(t, K_ICMP6)) {
2556                         SELECT_ACTIVITY(A_NET_ICMP6);
2557                 }
2558                 else if (!strcmp(t, K_EICMP6)) {
2559                         SELECT_ACTIVITY(A_NET_EICMP6);
2560                 }
2561                 else if (!strcmp(t, K_UDP6)) {
2562                         SELECT_ACTIVITY(A_NET_UDP6);
2563                 }
2564                 else if (!strcmp(t, K_FC)) {
2565                         SELECT_ACTIVITY(A_NET_FC);
2566                 }
2567                 else if (!strcmp(t, K_SOFT)) {
2568                         SELECT_ACTIVITY(A_NET_SOFT);
2569                 }
2570                 else if (!strcmp(t, K_ALL)) {
2571                         SELECT_ACTIVITY(A_NET_DEV);
2572                         SELECT_ACTIVITY(A_NET_EDEV);
2573                         SELECT_ACTIVITY(A_NET_SOCK);
2574                         SELECT_ACTIVITY(A_NET_NFS);
2575                         SELECT_ACTIVITY(A_NET_NFSD);
2576                         SELECT_ACTIVITY(A_NET_IP);
2577                         SELECT_ACTIVITY(A_NET_EIP);
2578                         SELECT_ACTIVITY(A_NET_ICMP);
2579                         SELECT_ACTIVITY(A_NET_EICMP);
2580                         SELECT_ACTIVITY(A_NET_TCP);
2581                         SELECT_ACTIVITY(A_NET_ETCP);
2582                         SELECT_ACTIVITY(A_NET_UDP);
2583                         SELECT_ACTIVITY(A_NET_SOCK6);
2584                         SELECT_ACTIVITY(A_NET_IP6);
2585                         SELECT_ACTIVITY(A_NET_EIP6);
2586                         SELECT_ACTIVITY(A_NET_ICMP6);
2587                         SELECT_ACTIVITY(A_NET_EICMP6);
2588                         SELECT_ACTIVITY(A_NET_UDP6);
2589                         SELECT_ACTIVITY(A_NET_FC);
2590                         SELECT_ACTIVITY(A_NET_SOFT);
2591                 }
2592                 else
2593                         return 1;
2594         }
2595
2596         (*opt)++;
2597         return 0;
2598 }
2599
2600 /*
2601  ***************************************************************************
2602  * Parse sar "-q" option.
2603  *
2604  * IN:
2605  * @argv        Arguments list.
2606  * @opt         Index in list of arguments.
2607  *
2608  * OUT:
2609  * @act         Array of selected activities.
2610  *
2611  * RETURNS:
2612  * 0 on success, 1 otherwise.
2613  ***************************************************************************
2614  */
2615 int parse_sar_q_opt(char *argv[], int *opt, struct activity *act[])
2616 {
2617         char *t;
2618
2619         for (t = strtok(argv[*opt], ","); t; t = strtok(NULL, ",")) {
2620                 if (!strcmp(t, K_LOAD)) {
2621                         SELECT_ACTIVITY(A_QUEUE);
2622                 }
2623                 else if (!strcmp(t, K_PSI_CPU)) {
2624                         SELECT_ACTIVITY(A_PSI_CPU);
2625                 }
2626                 else if (!strcmp(t, K_PSI_IO)) {
2627                         SELECT_ACTIVITY(A_PSI_IO);
2628                 }
2629                 else if (!strcmp(t, K_PSI_MEM)) {
2630                         SELECT_ACTIVITY(A_PSI_MEM);
2631                 }
2632                 else if (!strcmp(t, K_PSI)) {
2633                         SELECT_ACTIVITY(A_PSI_CPU);
2634                         SELECT_ACTIVITY(A_PSI_IO);
2635                         SELECT_ACTIVITY(A_PSI_MEM);
2636                 }
2637                 else if (!strcmp(t, K_ALL)) {
2638                         SELECT_ACTIVITY(A_QUEUE);
2639                         SELECT_ACTIVITY(A_PSI_CPU);
2640                         SELECT_ACTIVITY(A_PSI_IO);
2641                         SELECT_ACTIVITY(A_PSI_MEM);
2642                 }
2643                 else
2644                         return 1;
2645         }
2646
2647         (*opt)++;
2648         return 0;
2649 }
2650
2651 /*
2652  ***************************************************************************
2653  * Parse sar and sadf "-P" option.
2654  *
2655  * IN:
2656  * @argv        Arguments list.
2657  * @opt         Index in list of arguments.
2658  * @act         Array of activities.
2659  *
2660  * OUT:
2661  * @flags       Common flags and system state.
2662  * @act         Array of activities, with CPUs selected.
2663  *
2664  * RETURNS:
2665  * 0 on success, 1 otherwise.
2666  ***************************************************************************
2667  */
2668 int parse_sa_P_opt(char *argv[], int *opt, uint64_t *flags, struct activity *act[])
2669 {
2670         int p;
2671
2672         p = get_activity_position(act, A_CPU, EXIT_IF_NOT_FOUND);
2673
2674         if (argv[++(*opt)]) {
2675                 if (parse_values(argv[*opt], act[p]->bitmap->b_array,
2676                              act[p]->bitmap->b_size, K_LOWERALL))
2677                         return 1;
2678                 (*opt)++;
2679                 *flags |= S_F_OPTION_P;
2680                 return 0;
2681         }
2682
2683         return 1;
2684 }
2685
2686 /*
2687  ***************************************************************************
2688  * If option -A has been used, force -P ALL only if corresponding
2689  * option has not been explicitly entered on the command line.
2690  *
2691  * IN:
2692  * @flags       Common flags and system state.
2693  *
2694  * OUT:
2695  * @act         Array of selected activities.
2696  ***************************************************************************
2697  */
2698 void set_bitmaps(struct activity *act[], uint64_t *flags)
2699 {
2700         int p;
2701
2702         if (!USE_OPTION_P(*flags)) {
2703                 /* Force -P ALL */
2704                 p = get_activity_position(act, A_CPU, EXIT_IF_NOT_FOUND);
2705                 memset(act[p]->bitmap->b_array, ~0,
2706                        BITMAP_SIZE(act[p]->bitmap->b_size));
2707         }
2708 }
2709
2710 /*
2711  ***************************************************************************
2712  * Parse devices entered on the command line and save them in activity's
2713  * list.
2714  *
2715  * IN:
2716  * @argv        Argument with list of devices.
2717  * @a           Activity for which devices are entered on the command line.
2718  * @max_len     Max length of a device name.
2719  * @opt         Index in list of arguments.
2720  * @pos         Position is string where is located the first device.
2721  * @max_val     If > 0 then ranges of values are allowed (e.g. 3-5,9-, etc.)
2722  *              Values are in range [0..@max_val].
2723  *
2724  * OUT:
2725  * @opt         Index on next argument.
2726  ***************************************************************************
2727  */
2728 void parse_sa_devices(char *argv, struct activity *a, int max_len, int *opt, int pos,
2729                       int max_val)
2730 {
2731         int i, val_low, val;
2732         char *t;
2733         char svalue[9];
2734
2735         for (t = strtok(argv + pos, ","); t; t = strtok(NULL, ",")) {
2736
2737                 /* Test ranges of values, if allowed */
2738                 if ((max_val > 0) && (strlen(t) <= 16) && (strspn(t, XDIGITS) == strlen(t))) {
2739                         if (parse_range_values(t, max_val, &val_low, &val) == 0) {
2740                                 /* This is a real range of values: Save each if its values */
2741                                 for (i = val_low; i <= val; i++) {
2742                                         snprintf(svalue, sizeof(svalue), "%d", i);
2743                                         svalue[sizeof(svalue) - 1] = '\0';
2744                                         a->item_list_sz += add_list_item(&(a->item_list), svalue, max_len);
2745                                 }
2746                                 continue;
2747                         }
2748                 }
2749                 a->item_list_sz += add_list_item(&(a->item_list), t, max_len);
2750         }
2751         if (a->item_list_sz) {
2752                 a->options |= AO_LIST_ON_CMDLINE;
2753         }
2754         (*opt)++;
2755 }
2756
2757 /*
2758  ***************************************************************************
2759  * Compute network interface utilization.
2760  *
2761  * IN:
2762  * @st_net_dev  Structure with network interface stats.
2763  * @rx          Number of bytes received per second.
2764  * @tx          Number of bytes transmitted per second.
2765  *
2766  * RETURNS:
2767  * NIC utilization (0-100%).
2768  ***************************************************************************
2769  */
2770 double compute_ifutil(struct stats_net_dev *st_net_dev, double rx, double tx)
2771 {
2772         unsigned long long speed;
2773
2774         if (st_net_dev->speed) {
2775
2776                 speed = (unsigned long long) st_net_dev->speed * 1000000;
2777
2778                 if (st_net_dev->duplex == C_DUPLEX_FULL) {
2779                         /* Full duplex */
2780                         if (rx > tx) {
2781                                 return (rx * 800 / speed);
2782                         }
2783                         else {
2784                                 return (tx * 800 / speed);
2785                         }
2786                 }
2787                 else {
2788                         /* Half duplex */
2789                         return ((rx + tx) * 800 / speed);
2790                 }
2791         }
2792
2793         return 0;
2794 }
2795
2796 /*
2797  ***************************************************************************
2798  * Read and replace unprintable characters in comment with ".".
2799  *
2800  * IN:
2801  * @ifd         Input file descriptor.
2802  * @comment     Comment.
2803  ***************************************************************************
2804  */
2805 void replace_nonprintable_char(int ifd, char *comment)
2806 {
2807         int i;
2808
2809         /* Read comment */
2810         sa_fread(ifd, comment, MAX_COMMENT_LEN, HARD_SIZE, UEOF_STOP);
2811         comment[MAX_COMMENT_LEN - 1] = '\0';
2812
2813         /* Replace non printable chars */
2814         for (i = 0; i < strlen(comment); i++) {
2815                 if (!isprint(comment[i]))
2816                         comment[i] = '.';
2817         }
2818 }
2819
2820 /*
2821  ***************************************************************************
2822  * Fill the rectime and loctime structures with current record's date and
2823  * time, based on current record's "number of seconds since the epoch" saved
2824  * in file.
2825  * For loctime (if given): The timestamp is expressed in local time.
2826  * For rectime: The timestamp is expressed in UTC, in local time, or in the
2827  * time of the file's creator depending on options entered by the user on the
2828  * command line.
2829  *
2830  * IN:
2831  * @l_flags     Flags indicating the type of time expected by the user.
2832  *              S_F_LOCAL_TIME means time should be expressed in local time.
2833  *              S_F_TRUE_TIME means time should be expressed in time of
2834  *              file's creator.
2835  *              Default is time expressed in UTC (except for sar, where it
2836  *              is local time).
2837  * @record_hdr  Record header containing the number of seconds since the
2838  *              epoch, and the HH:MM:SS of the file's creator.
2839  *
2840  * OUT:
2841  * @rectime     Structure where timestamp for current record has been saved
2842  *              (in local time, in UTC or in time of file's creator
2843  *              depending on options used).
2844  *
2845  * RETURNS:
2846  * 1 if an error was detected, or 0 otherwise.
2847  ***************************************************************************
2848 */
2849 int sa_get_record_timestamp_struct(uint64_t l_flags, struct record_header *record_hdr,
2850                                    struct tm *rectime)
2851 {
2852         struct tm *ltm;
2853         time_t t = record_hdr->ust_time;
2854         int rc = 0;
2855
2856         /*
2857          * Fill generic rectime structure in local time.
2858          * Done so that we have some default values.
2859          */
2860         ltm = localtime_r(&t, rectime);
2861
2862         if (!PRINT_LOCAL_TIME(l_flags) && !PRINT_TRUE_TIME(l_flags)) {
2863                 /*
2864                  * Get time in UTC
2865                  * (the user doesn't want local time nor time of file's creator).
2866                  */
2867                 ltm = gmtime_r(&t, rectime);
2868         }
2869
2870         if (!ltm) {
2871                 rc = 1;
2872         }
2873
2874         if (PRINT_TRUE_TIME(l_flags)) {
2875                 /* Time of file's creator */
2876                 rectime->tm_hour = record_hdr->hour;
2877                 rectime->tm_min  = record_hdr->minute;
2878                 rectime->tm_sec  = record_hdr->second;
2879         }
2880
2881         return rc;
2882 }
2883
2884 /*
2885  ***************************************************************************
2886  * Set current record's timestamp strings (date and time) using the time
2887  * data saved in @rectime structure. The string may be the number of seconds
2888  * since the epoch if flag S_F_SEC_EPOCH has been set.
2889  *
2890  * IN:
2891  * @l_flags     Flags indicating the type of time expected by the user.
2892  *              S_F_SEC_EPOCH means the time should be expressed in seconds
2893  *              since the epoch (01/01/1970).
2894  * @record_hdr  Record header containing the number of seconds since the
2895  *              epoch.
2896  * @cur_date    String where timestamp's date will be saved. May be NULL.
2897  * @cur_time    String where timestamp's time will be saved.
2898  * @len         Maximum length of timestamp strings.
2899  * @rectime     Structure with current timestamp (expressed in local time or
2900  *              in UTC depending on whether options -T or -t have been used
2901  *              or not) that should be broken down in date and time strings.
2902  *
2903  * OUT:
2904  * @cur_date    Timestamp's date string (if expected).
2905  * @cur_time    Timestamp's time string. May contain the number of seconds
2906  *              since the epoch (01-01-1970) if corresponding option has
2907  *              been used.
2908  ***************************************************************************
2909 */
2910 void set_record_timestamp_string(uint64_t l_flags, struct record_header *record_hdr,
2911                                  char *cur_date, char *cur_time, int len, struct tm *rectime)
2912 {
2913         /* Set cur_time date value */
2914         if (PRINT_SEC_EPOCH(l_flags) && cur_date) {
2915                 sprintf(cur_time, "%llu", record_hdr->ust_time);
2916                 strcpy(cur_date, "");
2917         }
2918         else {
2919                 /*
2920                  * If options -T or -t have been used then cur_time is
2921                  * expressed in local time. Else it is expressed in UTC.
2922                  */
2923                 if (cur_date) {
2924                         strftime(cur_date, len, "%Y-%m-%d", rectime);
2925                 }
2926                 if (USE_PREFD_TIME_OUTPUT(l_flags)) {
2927                         strftime(cur_time, len, "%X", rectime);
2928                 }
2929                 else {
2930                         strftime(cur_time, len, "%H:%M:%S", rectime);
2931                 }
2932         }
2933 }
2934
2935 /*
2936  ***************************************************************************
2937  * Print contents of a special (RESTART or COMMENT) record.
2938  * Note: This function is called only when reading a file.
2939  *
2940  * IN:
2941  * @record_hdr  Current record header.
2942  * @l_flags     Flags for common options.
2943  * @tm_start    Structure filled when option -s has been used.
2944  * @tm_end      Structure filled when option -e has been used.
2945  * @rtype       Record type (R_RESTART or R_COMMENT).
2946  * @ifd         Input file descriptor.
2947  * @rectime     Structure where timestamp (expressed in local time or in UTC
2948  *              depending on whether options -T/-t have been used or not) can
2949  *              be saved for current record.
2950  * @file        Name of file being read.
2951  * @tab         Number of tabulations to print.
2952  * @my_tz       Current timezone.
2953  * @file_magic  file_magic structure filled with file magic header data.
2954  * @file_hdr    System activity file standard header.
2955  * @act         Array of activities.
2956  * @ofmt        Pointer on report output format structure.
2957  * @endian_mismatch
2958  *              TRUE if file's data don't match current machine's endianness.
2959  * @arch_64     TRUE if file's data come from a 64 bit machine.
2960  *
2961  * OUT:
2962  * @rectime     Structure where timestamp (expressed in local time or in UTC)
2963  *              has been saved.
2964  *
2965  * RETURNS:
2966  * 1 if the record has been successfully displayed, and 0 otherwise.
2967  ***************************************************************************
2968  */
2969 int print_special_record(struct record_header *record_hdr, uint64_t l_flags,
2970                          struct tstamp *tm_start, struct tstamp *tm_end, int rtype, int ifd,
2971                          struct tm *rectime, char *file, int tab, char *my_tz,
2972                          struct file_magic *file_magic, struct file_header *file_hdr,
2973                          struct activity *act[], struct report_format *ofmt,
2974                          int endian_mismatch, int arch_64)
2975 {
2976         char cur_date[TIMESTAMP_LEN], cur_time[TIMESTAMP_LEN];
2977         int dp = 1;
2978         int p;
2979
2980         /* Fill timestamp structure (rectime) for current record */
2981         if (sa_get_record_timestamp_struct(l_flags, record_hdr, rectime))
2982                 return 0;
2983
2984         /* The record must be in the interval specified by -s/-e options */
2985         if ((tm_start->use && (datecmp(rectime, tm_start, FALSE) < 0)) ||
2986             (tm_end->use && (datecmp(rectime, tm_end, FALSE) > 0))) {
2987                 /* Will not display the special record */
2988                 dp = 0;
2989         }
2990         else {
2991                 /* Set date and time strings to be displayed for current record */
2992                 set_record_timestamp_string(l_flags, record_hdr,
2993                                             cur_date, cur_time, TIMESTAMP_LEN, rectime);
2994         }
2995
2996         if (rtype == R_RESTART) {
2997                 /* Read new cpu number following RESTART record */
2998                 file_hdr->sa_cpu_nr = read_nr_value(ifd, file, file_magic,
2999                                                     endian_mismatch, arch_64, TRUE);
3000
3001                 /*
3002                  * We don't know if CPU related activities will be displayed or not.
3003                  * But if it is the case, @nr_ini will be used in the loop
3004                  * to process all CPUs. So update their value here and
3005                  * reallocate buffers if needed.
3006                  * NB: We may have nr_allocated=0 here if the activity has
3007                  * not been collected in file (or if it has an unknown format).
3008                  */
3009                 for (p = 0; p < NR_ACT; p++) {
3010                         if (HAS_PERSISTENT_VALUES(act[p]->options) && (act[p]->nr_ini > 0)) {
3011                                 act[p]->nr_ini = file_hdr->sa_cpu_nr;
3012                                 if (act[p]->nr_ini > act[p]->nr_allocated) {
3013                                         reallocate_all_buffers(act[p], act[p]->nr_ini);
3014                                 }
3015                         }
3016                 }
3017
3018                 /* Ignore unknown extra structures if present */
3019                 if (record_hdr->extra_next && (skip_extra_struct(ifd, endian_mismatch, arch_64) < 0))
3020                         return 0;
3021
3022                 if (!dp)
3023                         return 0;
3024
3025                 if (*ofmt->f_restart) {
3026                         (*ofmt->f_restart)(&tab, F_MAIN, cur_date, cur_time, my_tz, file_hdr, record_hdr);
3027                 }
3028         }
3029         else if (rtype == R_COMMENT) {
3030                 char file_comment[MAX_COMMENT_LEN];
3031
3032                 /* Read and replace non printable chars in comment */
3033                 replace_nonprintable_char(ifd, file_comment);
3034
3035                 /* Ignore unknown extra structures if present */
3036                 if (record_hdr->extra_next && (skip_extra_struct(ifd, endian_mismatch, arch_64) < 0))
3037                         return 0;
3038
3039                 if (!dp || !DISPLAY_COMMENT(l_flags))
3040                         return 0;
3041
3042                 if (*ofmt->f_comment) {
3043                         (*ofmt->f_comment)(&tab, F_MAIN, cur_date, cur_time, my_tz,
3044                                            file_comment, file_hdr, record_hdr);
3045                 }
3046         }
3047
3048         return 1;
3049 }
3050
3051 /*
3052  ***************************************************************************
3053  * Compute global CPU statistics as the sum of individual CPU ones, and
3054  * calculate interval for global CPU.
3055  * Also identify offline CPU.
3056  *
3057  * IN:
3058  * @a           Activity structure with statistics.
3059  * @prev        Index in array where stats used as reference are.
3060  * @curr        Index in array for current sample statistics.
3061  * @flags       Flags for common options and system state.
3062  * @offline_cpu_bitmap
3063  *              CPU bitmap for offline CPU.
3064  *
3065  * OUT:
3066  * @a           Activity structure with updated statistics (those for global
3067  *              CPU, and also those for offline CPU).
3068  * @offline_cpu_bitmap
3069  *              CPU bitmap with offline CPU.
3070  *
3071  * RETURNS:
3072  * Interval for global CPU.
3073  ***************************************************************************
3074  */
3075 unsigned long long get_global_cpu_statistics(struct activity *a, int prev, int curr,
3076                                              uint64_t flags, unsigned char offline_cpu_bitmap[])
3077 {
3078         int i;
3079         unsigned long long tot_jiffies_c, tot_jiffies_p;
3080         unsigned long long deltot_jiffies = 0;
3081         struct stats_cpu *scc, *scp;
3082         struct stats_cpu *scc_all = (struct stats_cpu *) ((char *) a->buf[curr]);
3083         struct stats_cpu *scp_all = (struct stats_cpu *) ((char *) a->buf[prev]);
3084
3085         /*
3086          * Initial processing.
3087          * Compute CPU "all" as sum of all individual CPU. Done only on SMP machines (a->nr_ini > 1).
3088          * For UP machines we keep the values read from global CPU line in /proc/stat.
3089          * Also look for offline CPU: They won't be displayed, and some of their values may
3090          * have to be modified.
3091          */
3092         if (a->nr_ini > 1) {
3093                 memset(scc_all, 0, sizeof(struct stats_cpu));
3094                 memset(scp_all, 0, sizeof(struct stats_cpu));
3095         }
3096
3097         for (i = 1; (i < a->nr_ini) && (i < a->bitmap->b_size + 1); i++) {
3098
3099                 /*
3100                  * The size of a->buf[...] CPU structure may be different from the default
3101                  * sizeof(struct stats_cpu) value if data have been read from a file!
3102                  * That's why we don't use a syntax like:
3103                  * scc = (struct stats_cpu *) a->buf[...] + i;
3104                  */
3105                 scc = (struct stats_cpu *) ((char *) a->buf[curr] + i * a->msize);
3106                 scp = (struct stats_cpu *) ((char *) a->buf[prev] + i * a->msize);
3107
3108                 /*
3109                  * Compute the total number of jiffies spent by current processor.
3110                  * NB: Don't add cpu_guest/cpu_guest_nice because cpu_user/cpu_nice
3111                  * already include them.
3112                  */
3113                 tot_jiffies_c = scc->cpu_user + scc->cpu_nice +
3114                                 scc->cpu_sys + scc->cpu_idle +
3115                                 scc->cpu_iowait + scc->cpu_hardirq +
3116                                 scc->cpu_steal + scc->cpu_softirq;
3117                 tot_jiffies_p = scp->cpu_user + scp->cpu_nice +
3118                                 scp->cpu_sys + scp->cpu_idle +
3119                                 scp->cpu_iowait + scp->cpu_hardirq +
3120                                 scp->cpu_steal + scp->cpu_softirq;
3121
3122                 /*
3123                  * If the CPU is offline then it is omited from /proc/stat:
3124                  * All the fields couldn't have been read and the sum of them is zero.
3125                  */
3126                 if (tot_jiffies_c == 0) {
3127                         /*
3128                          * CPU is currently offline.
3129                          * Set current struct fields (which have been set to zero)
3130                          * to values from previous iteration. Hence their values won't
3131                          * jump from zero when the CPU comes back online.
3132                          * Note that this workaround no longer fully applies with recent kernels,
3133                          * as I have noticed that when a CPU comes back online, some fields
3134                          * restart from their previous value (e.g. user, nice, system)
3135                          * whereas others restart from zero (idle, iowait)! To deal with this,
3136                          * the get_per_cpu_interval() function will set these previous values
3137                          * to zero if necessary.
3138                          */
3139                         *scc = *scp;
3140
3141                         /*
3142                          * Mark CPU as offline to not display it
3143                          * (and thus it will not be confused with a tickless CPU).
3144                          */
3145                         offline_cpu_bitmap[i >> 3] |= 1 << (i & 0x07);
3146                 }
3147
3148                 if ((tot_jiffies_p == 0) && !WANT_SINCE_BOOT(flags)) {
3149                         /*
3150                          * CPU has just come back online.
3151                          * Unfortunately, no reference values are available
3152                          * from a previous iteration, probably because it was
3153                          * already offline when the first sample has been taken.
3154                          * So don't display that CPU to prevent "jump-from-zero"
3155                          * output syndrome, and don't take it into account for CPU "all".
3156                          */
3157                         offline_cpu_bitmap[i >> 3] |= 1 << (i & 0x07);
3158                         continue;
3159                 }
3160
3161                 /*
3162                  * Get interval for current CPU and add it to global CPU.
3163                  * Note: Previous idle and iowait values (saved in scp) may be modified here.
3164                  */
3165                 deltot_jiffies += get_per_cpu_interval(scc, scp);
3166
3167                 scc_all->cpu_user += scc->cpu_user;
3168                 scp_all->cpu_user += scp->cpu_user;
3169
3170                 scc_all->cpu_nice += scc->cpu_nice;
3171                 scp_all->cpu_nice += scp->cpu_nice;
3172
3173                 scc_all->cpu_sys += scc->cpu_sys;
3174                 scp_all->cpu_sys += scp->cpu_sys;
3175
3176                 scc_all->cpu_idle += scc->cpu_idle;
3177                 scp_all->cpu_idle += scp->cpu_idle;
3178
3179                 scc_all->cpu_iowait += scc->cpu_iowait;
3180                 scp_all->cpu_iowait += scp->cpu_iowait;
3181
3182                 scc_all->cpu_hardirq += scc->cpu_hardirq;
3183                 scp_all->cpu_hardirq += scp->cpu_hardirq;
3184
3185                 scc_all->cpu_steal += scc->cpu_steal;
3186                 scp_all->cpu_steal += scp->cpu_steal;
3187
3188                 scc_all->cpu_softirq += scc->cpu_softirq;
3189                 scp_all->cpu_softirq += scp->cpu_softirq;
3190
3191                 scc_all->cpu_guest += scc->cpu_guest;
3192                 scp_all->cpu_guest += scp->cpu_guest;
3193
3194                 scc_all->cpu_guest_nice += scc->cpu_guest_nice;
3195                 scp_all->cpu_guest_nice += scp->cpu_guest_nice;
3196         }
3197
3198         return deltot_jiffies;
3199 }
3200
3201 /*
3202  ***************************************************************************
3203  * Compute softnet statistics for CPU "all" as the sum of individual CPU
3204  * ones.
3205  * Also identify offline CPU.
3206  *
3207  * IN:
3208  * @a           Activity structure with statistics.
3209  * @prev        Index in array where stats used as reference are.
3210  * @curr        Index in array for current sample statistics.
3211  * @flags       Flags for common options and system state.
3212  * @offline_cpu_bitmap
3213  *              CPU bitmap for offline CPU.
3214  *
3215  * OUT:
3216  * @a           Activity structure with updated statistics (those for global
3217  *              CPU, and also those for offline CPU).
3218  * @offline_cpu_bitmap
3219  *              CPU bitmap with offline CPU.
3220  ***************************************************************************
3221  */
3222 void get_global_soft_statistics(struct activity *a, int prev, int curr,
3223                                 uint64_t flags, unsigned char offline_cpu_bitmap[])
3224 {
3225         int i;
3226         struct stats_softnet *ssnc, *ssnp;
3227         struct stats_softnet *ssnc_all = (struct stats_softnet *) ((char *) a->buf[curr]);
3228         struct stats_softnet *ssnp_all = (struct stats_softnet *) ((char *) a->buf[prev]);
3229
3230         /*
3231          * Init structures that will contain values for CPU "all".
3232          * CPU "all" doesn't exist in /proc/net/softnet_stat file, so
3233          * we compute its values as the sum of the values of each CPU.
3234          */
3235         memset(ssnc_all, 0, sizeof(struct stats_softnet));
3236         memset(ssnp_all, 0, sizeof(struct stats_softnet));
3237
3238         for (i = 1; (i < a->nr_ini) && (i < a->bitmap->b_size + 1); i++) {
3239
3240                 /*
3241                  * The size of a->buf[...] CPU structure may be different from the default
3242                  * sizeof(struct stats_softnet) value if data have been read from a file!
3243                  * That's why we don't use a syntax like:
3244                  * ssnc = (struct stats_softnet *) a->buf[...] + i;
3245                  */
3246                 ssnc = (struct stats_softnet *) ((char *) a->buf[curr] + i * a->msize);
3247                 ssnp = (struct stats_softnet *) ((char *) a->buf[prev] + i * a->msize);
3248
3249                 if ((ssnp->processed + ssnp->dropped + ssnp->time_squeeze +
3250                     ssnp->received_rps + ssnp->flow_limit + ssnp->backlog_len == 0) &&
3251                     !WANT_SINCE_BOOT(flags)) {
3252                         /*
3253                          * No previous sample for current CPU: Don't display it unless
3254                          * we want stats since last boot time.
3255                          * (CPU may be online but we don't display it because all
3256                          * its counters would appear to jump from zero...)
3257                          */
3258                         offline_cpu_bitmap[i >> 3] |= 1 << (i & 0x07);
3259                         continue;
3260                 }
3261
3262                 if (ssnc->processed + ssnc->dropped + ssnc->time_squeeze +
3263                     ssnc->received_rps + ssnc->flow_limit + ssnc->backlog_len == 0) {
3264                         /* Assume current CPU is offline */
3265                         *ssnc = *ssnp;
3266                         offline_cpu_bitmap[i >> 3] |= 1 << (i & 0x07);
3267                 }
3268
3269                 ssnc_all->processed += ssnc->processed;
3270                 ssnc_all->dropped += ssnc->dropped;
3271                 ssnc_all->time_squeeze += ssnc->time_squeeze;
3272                 ssnc_all->received_rps += ssnc->received_rps;
3273                 ssnc_all->flow_limit += ssnc->flow_limit;
3274                 ssnc_all->backlog_len += ssnc->backlog_len;
3275
3276                 ssnp_all->processed += ssnp->processed;
3277                 ssnp_all->dropped += ssnp->dropped;
3278                 ssnp_all->time_squeeze += ssnp->time_squeeze;
3279                 ssnp_all->received_rps += ssnp->received_rps;
3280                 ssnp_all->flow_limit += ssnp->flow_limit;
3281                 ssnp_all->backlog_len += ssnp->backlog_len;
3282         }
3283 }
3284
3285 /*
3286  ***************************************************************************
3287  * Identify offline CPU (those for which all interrupts are 0) and keep
3288  * interrupts statistics (their values are persistent). Include also CPU
3289  * which have not been selected (this is necessary so that the header of the
3290  * interrupts statistics report can be displayed).
3291  *
3292  * IN:
3293  * @a           Activity structure with statistics.
3294  * @prev        Index in array where stats used as reference are.
3295  * @curr        Index in array for current sample statistics.
3296  * @flags       Flags for common options and system state.
3297  * @masked_cpu_bitmap
3298  *              CPU bitmap for offline and unselected CPU.
3299  *
3300  * OUT:
3301  * @a           Activity structure with updated statistics (those for global
3302  *              CPU, and also those for offline CPU).
3303  * @masked_cpu_bitmap
3304  *              CPU bitmap with offline and unselected CPU.
3305  ***************************************************************************
3306  */
3307 void get_global_int_statistics(struct activity *a, int prev, int curr,
3308                                uint64_t flags, unsigned char masked_cpu_bitmap[])
3309 {
3310         int i;
3311         struct stats_irq *stc_cpu_sum, *stp_cpu_sum;
3312
3313         for (i = 0; (i < a->nr_ini) && (i < a->bitmap->b_size + 1); i++) {
3314
3315                 /*
3316                  * The size of a->buf[...] CPU structure may be different from the default
3317                  * sizeof(struct stats_irq) value if data have been read from a file!
3318                  * That's why we don't use a syntax like:
3319                  * stc_cpu_sum = (struct stats_irq *) a->buf[...] + i;
3320                  */
3321                 stc_cpu_sum = (struct stats_irq *) ((char *) a->buf[curr] + i * a->msize * a->nr2);
3322                 stp_cpu_sum = (struct stats_irq *) ((char *) a->buf[prev] + i * a->msize * a->nr2);
3323
3324                 /*
3325                  * Check if current CPU is back online but with no previous sample for it,
3326                  * or if it has not been selected.
3327                  */
3328                 if (((stp_cpu_sum->irq_nr == 0) && !WANT_SINCE_BOOT(flags)) ||
3329                     (!(a->bitmap->b_array[i >> 3] & (1 << (i & 0x07))))) {
3330                         /* CPU should not be displayed */
3331                         masked_cpu_bitmap[i >> 3] |= 1 << (i & 0x07);
3332                         continue;
3333                 }
3334
3335                 if (stc_cpu_sum->irq_nr == 0) {
3336                         /* Assume current CPU is offline */
3337                         masked_cpu_bitmap[i >> 3] |= 1 << (i & 0x07);
3338                         memcpy(stc_cpu_sum, stp_cpu_sum, (size_t) a->msize * a->nr2);
3339                 }
3340
3341         }
3342 }
3343
3344 /*
3345  ***************************************************************************
3346  * Get filesystem name to display. This may be either the persistent name
3347  * if requested by the user, the standard filesystem name (e.g. /dev/sda1,
3348  * /dev/sdb3, etc.) or the mount point. This is used when displaying
3349  * filesystem statistics: sar -F or sadf -- -F).
3350  *
3351  * IN:
3352  * @a           Activity structure.
3353  * @flags       Flags for common options and system state.
3354  * @st_fs       Statistics for current filesystem.
3355  *
3356  * RETURNS:
3357  * Filesystem name to display.
3358  ***************************************************************************
3359  */
3360 char *get_fs_name_to_display(struct activity *a, uint64_t flags, struct stats_filesystem *st_fs)
3361 {
3362         char *pname = NULL, *persist_dev_name;
3363         char fname[MAX_FS_LEN];
3364
3365         if (DISPLAY_PERSIST_NAME_S(flags) && !DISPLAY_MOUNT(a->opt_flags)) {
3366                 strncpy(fname, st_fs->fs_name, sizeof(fname));
3367                 fname[sizeof(fname) - 1] = '\0';
3368                 if ((persist_dev_name = get_persistent_name_from_pretty(basename(fname))) != NULL) {
3369                         pname = persist_dev_name;
3370                 }
3371         }
3372         if (!pname) {
3373                 pname = DISPLAY_MOUNT(a->opt_flags) ? st_fs->mountp : st_fs->fs_name;
3374         }
3375         return pname;
3376 }
3377 #endif /* SOURCE_SADC undefined */