]> granicus.if.org Git - sysstat/blob - tapestat.c
tapestat: more fixes for realloc
[sysstat] / tapestat.c
1 /*
2  * tapestat: report tape statistics
3  * (C) 2015 Hewlett-Packard Development Company, L.P.
4  *
5  * Initial revision by Shane M. SEYMOUR (shane.seymour <at> hpe.com)
6  * Modified for sysstat by Sebastien GODARD (sysstat <at> orange.fr)
7  *
8  ***************************************************************************
9  * This program is free software; you can redistribute it and/or modify it *
10  * under the terms of the GNU General Public License as published  by  the *
11  * Free Software Foundation; either version 2 of the License, or (at  your *
12  * option) any later version.                                              *
13  *                                                                         *
14  * This program is distributed in the hope that it  will  be  useful,  but *
15  * WITHOUT ANY WARRANTY; without the implied warranty  of  MERCHANTABILITY *
16  * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License *
17  * for more details.                                                       *
18  *                                                                         *
19  * You should have received a copy of the GNU General Public License along *
20  * with this program; if not, write to the Free Software Foundation, Inc., *
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA              *
22  ***************************************************************************
23  */
24
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <time.h>
30 #include <dirent.h>
31 #define __DO_NOT_DEFINE_COMPILE
32 #include <regex.h>
33 #include <inttypes.h>
34 #include <stdint.h>
35 #include <signal.h>
36 #include <sys/stat.h>
37 #include <sys/time.h>
38 #include <sys/utsname.h>
39 #include <sys/param.h>
40 #undef HZ /* sys/param.h defines HZ but needed for MAXPATHLEN */
41
42 #include "version.h"
43 #include "tapestat.h"
44 #include "common.h"
45 #include "count.h"
46
47 #ifdef USE_NLS
48 #include <locale.h>
49 #include <libintl.h>
50 #define _(string) gettext(string)
51 #else
52 #define _(string) (string)
53 #endif
54
55 #define SCCSID "@(#)sysstat-" VERSION ": " __FILE__ " compiled " __DATE__ " " __TIME__
56 char *sccsid(void) { return (SCCSID); }
57
58 int cpu_nr = 0;         /* Nb of processors on the machine */
59 int flags = 0;          /* Flag for common options and system state */
60
61 long interval = 0;
62 char timestamp[64];
63
64 struct sigaction alrm_act;
65
66 /*
67  * For tape stats - it would be extremely rare for there to be a very large
68  * number of tape drives attached to a system. I wouldn't expect to see more
69  * than 20-30 in a very large configuration and discontinguous ones should
70  * be even more rare. Because of this we keep the old and new data in a
71  * simple data structure with the tape index being the number after the tape
72  * drive, st0 at index 0, etc.
73  */
74 int max_tape_drives = 0;
75 struct tape_stats *tape_new_stats = { NULL };
76 struct tape_stats *tape_old_stats = { NULL };
77 regex_t tape_reg;
78
79 /*
80  ***************************************************************************
81  * Print usage and exit.
82  *
83  * IN:
84  * @progname    Name of sysstat command.
85  ***************************************************************************
86  */
87 void usage(char *progname)
88 {
89         fprintf(stderr, _("Usage: %s [ options ] [ <interval> [ <count> ] ]\n"),
90                 progname);
91         fprintf(stderr, _("Options are:\n"
92                           "[ -k | -m ] [ -t ] [ -V ] [ -y ] [ -z ]\n"));
93         exit(1);
94 }
95
96 /*
97  ***************************************************************************
98  * SIGALRM signal handler. No need to reset the handler here.
99  *
100  * IN:
101  * @sig Signal number.
102  ***************************************************************************
103  */
104 void alarm_handler(int sig)
105 {
106         alarm(interval);
107 }
108
109 /*
110  ***************************************************************************
111  * Initialization.
112  ***************************************************************************
113  */
114 void tape_initialise(void)
115 {
116         /* How many processors on this machine? */
117         cpu_nr = get_cpu_nr(~0, FALSE);
118
119         /* Compile regular expression for tape names */
120         if (regcomp(&tape_reg, "^st[0-9]+$", REG_EXTENDED) != 0) {
121                 exit(1);
122         }
123 }
124
125 /*
126  ***************************************************************************
127  * Free structures.
128  ***************************************************************************
129  */
130 void tape_uninitialise(void)
131 {
132         regfree(&tape_reg);
133         if (tape_old_stats != NULL) {
134                 free(tape_old_stats);
135         }
136         if (tape_new_stats != NULL) {
137                 free(tape_new_stats);
138         }
139 }
140
141 /*
142  ***************************************************************************
143  * Get maximum number of tapes in the system.
144  *
145  * RETURNS:
146  * Number of tapes found.
147  ***************************************************************************
148  */
149 int get_max_tape_drives(void)
150 {
151         DIR *dir;
152         struct dirent *entry;
153         int new_max_tape_drives, tmp, num_stats_dir = 0;
154         regmatch_t match;
155         char stats_dir[MAXPATHLEN + 1];
156         struct stat stat_buf;
157
158         new_max_tape_drives = max_tape_drives;
159
160         /* Open sysfs tree */
161         dir = opendir(SYSFS_CLASS_TAPE_DIR);
162         if (dir == NULL)
163                 return 0;
164
165         while ((entry = readdir(dir)) != NULL) {
166                 if (regexec(&tape_reg, &entry->d_name[0], 1, &match, 0) == 0) {
167                         /* d_name[2] to skip the st at the front */
168                         tmp = atoi(&entry->d_name[2]) + 1;
169                         if (tmp > new_max_tape_drives) {
170                                 new_max_tape_drives = tmp;
171                         }
172                 }
173                 snprintf(stats_dir, MAXPATHLEN, "%s/%s/%s",
174                         SYSFS_CLASS_TAPE_DIR, &entry->d_name[0], "stats");
175                 if (stat(stats_dir, &stat_buf) == 0) {
176                         if (S_ISDIR(stat_buf.st_mode)) {
177                                 num_stats_dir++;
178                         }
179                 }
180         }
181         closedir(dir);
182
183         /* If there are no stats directories make the new number of tape drives 0 */
184         if (num_stats_dir == 0) {
185                 new_max_tape_drives = 0;
186         }
187
188         return new_max_tape_drives;
189 }
190
191 /*
192  ***************************************************************************
193  * Check if new tapes have been added and reallocate structures accordingly.
194  ***************************************************************************
195  */
196 void tape_check_tapes_and_realloc(void)
197 {
198         int new_max_tape_drives, i;
199
200         /* Count again number of tapes */
201         new_max_tape_drives = get_max_tape_drives();
202
203         if (new_max_tape_drives > max_tape_drives) {
204                 /* New tapes found: Realloc structures */
205                 struct tape_stats *tape_old_stats_t = (struct tape_stats *)
206                         realloc(tape_old_stats, sizeof(struct tape_stats) * new_max_tape_drives);
207                 struct tape_stats *tape_new_stats_t = (struct tape_stats *)
208                         realloc(tape_new_stats, sizeof(struct tape_stats) * new_max_tape_drives);
209                 if ((tape_old_stats_t == NULL) || (tape_new_stats_t == NULL)) {
210                         if (tape_old_stats_t != NULL) {
211                                 free(tape_old_stats_t);
212                                 tape_old_stats_t = NULL;
213                         }
214                         if (tape_new_stats_t != NULL) {
215                                 free(tape_new_stats_t);
216                                 tape_new_stats_t = NULL;
217                         }
218                         free(tape_old_stats);
219                         tape_old_stats = NULL;
220                         free(tape_new_stats);
221                         tape_new_stats = NULL;
222
223                         perror("realloc");
224                         exit(4);
225                 }
226
227                 tape_old_stats = tape_old_stats_t;
228                 tape_new_stats = tape_new_stats_t;
229
230                 for (i = max_tape_drives; i < new_max_tape_drives; i++) {
231                         tape_old_stats[i].valid = TAPE_STATS_INVALID;
232                         tape_new_stats[i].valid = TAPE_STATS_INVALID;
233                 }
234                 max_tape_drives = new_max_tape_drives;
235         }
236 }
237
238 /*
239  ***************************************************************************
240  * Collect initial statistics for all existing tapes in the system.
241  * This function should be called only once.
242  ***************************************************************************
243  */
244 void tape_gather_initial_stats(void)
245 {
246         int new_max_tape_drives, i;
247         FILE *fp;
248         char filename[MAXPATHLEN + 1];
249
250         /* Get number of tapes in the system */
251         new_max_tape_drives = get_max_tape_drives();
252
253         if (new_max_tape_drives == 0) {
254                 /* No tapes found */
255                 fprintf(stderr, _("No tape drives with statistics found\n"));
256                 exit(1);
257         }
258         else {
259                 /* Allocate structures */
260                 if (tape_old_stats == NULL) {
261                         tape_old_stats = (struct tape_stats *)
262                                 malloc(sizeof(struct tape_stats) * new_max_tape_drives);
263                         tape_new_stats = (struct tape_stats *)
264                                 malloc(sizeof(struct tape_stats) * new_max_tape_drives);
265                         for (i = 0; i < new_max_tape_drives; i++) {
266                                 tape_old_stats[i].valid = TAPE_STATS_INVALID;
267                                 tape_new_stats[i].valid = TAPE_STATS_INVALID;
268                         }
269                         max_tape_drives = new_max_tape_drives;
270                 } else
271                         /* This should only be called once */
272                         return;
273         }
274
275         /* Read stats for each tape */
276         for (i = 0; i < max_tape_drives; i++) {
277                 /*
278                  * Everything starts out valid but failing to open
279                  * a file gets the tape drive marked invalid.
280                  */
281                 tape_new_stats[i].valid = TAPE_STATS_VALID;
282                 tape_old_stats[i].valid = TAPE_STATS_VALID;
283
284                 gettimeofday(&tape_old_stats[i].tv, NULL);
285
286                 tape_new_stats[i].tv.tv_sec = tape_old_stats[i].tv.tv_sec;
287                 tape_new_stats[i].tv.tv_usec = tape_old_stats[i].tv.tv_usec;
288
289                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "read_ns", read_time)
290                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "write_ns", write_time)
291                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "io_ns", other_time)
292                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "read_byte_cnt", read_bytes)
293                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "write_byte_cnt", write_bytes)
294                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "read_cnt", read_count)
295                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "write_cnt", write_count)
296                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "other_cnt", other_count)
297                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "resid_cnt", resid_count)
298
299                 tape_old_stats[i].read_time = 0;
300                 tape_old_stats[i].write_time = 0;
301                 tape_old_stats[i].other_time = 0;
302                 tape_old_stats[i].read_bytes = 0;
303                 tape_old_stats[i].write_bytes = 0;
304                 tape_old_stats[i].read_count = 0;
305                 tape_old_stats[i].write_count = 0;
306                 tape_old_stats[i].other_count = 0;
307                 tape_old_stats[i].resid_count = 0;
308         }
309 }
310
311 /*
312  ***************************************************************************
313  * Collect a new sample of statistics for all existing tapes in the system.
314  ***************************************************************************
315  */
316 void tape_get_updated_stats(void)
317 {
318         int i;
319         FILE *fp;
320         char filename[MAXPATHLEN + 1] = { 0 };
321
322         /* Check tapes and realloc structures if  needed */
323         tape_check_tapes_and_realloc();
324
325         for (i = 0; i < max_tape_drives; i++) {
326                 /*
327                  * Everything starts out valid but failing
328                  * to open a file gets the tape drive marked invalid.
329                  */
330                 tape_new_stats[i].valid = TAPE_STATS_VALID;
331                 gettimeofday(&tape_new_stats[i].tv, NULL);
332
333                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "read_ns", read_time)
334                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "write_ns", write_time)
335                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "io_ns", other_time)
336                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "read_byte_cnt", read_bytes)
337                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "write_byte_cnt", write_bytes)
338                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "read_cnt", read_count)
339                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "write_cnt", write_count)
340                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "other_cnt", other_count)
341                 TAPE_STAT_FILE_VAL(TAPE_STAT_PATH "resid_cnt", resid_count)
342
343                 if ((tape_new_stats[i].read_time < tape_old_stats[i].read_time) ||
344                     (tape_new_stats[i].write_time < tape_old_stats[i].write_time) ||
345                     (tape_new_stats[i].other_time < tape_old_stats[i].other_time)) {
346                         tape_new_stats[i].valid = TAPE_STATS_INVALID;
347                 }
348         }
349 }
350
351 /*
352  ***************************************************************************
353  * Display tapes statistics headings.
354  ***************************************************************************
355  */
356 void tape_write_headings(void)
357 {
358         printf("Tape:     r/s     w/s   ");
359         if (DISPLAY_MEGABYTES(flags)) {
360                 printf("MB_read/s   MB_wrtn/s");
361         } else {
362                 printf("kB_read/s   kB_wrtn/s");
363         }
364         printf(" %%Rd %%Wr %%Oa    Rs/s    Ot/s\n");
365 }
366
367 /*
368  ***************************************************************************
369  * Calculate statistics for current tape.
370  *
371  * IN:
372  * @i           Index in array for current tape.
373  *
374  * OUT:
375  * @stats       Statistics for current tape.
376  ***************************************************************************
377  */
378 void tape_calc_one_stats(struct calc_stats *stats, int i)
379 {
380         uint64_t duration;
381         double temp;
382         FILE *fp;
383
384         /* Duration in ms done in ms to prevent rounding issues with using seconds */
385         duration = (tape_new_stats[i].tv.tv_sec -
386                 tape_old_stats[i].tv.tv_sec) * 1000;
387         duration -= tape_old_stats[i].tv.tv_usec / 1000;
388         duration += tape_new_stats[i].tv.tv_usec / 1000;
389
390         /* If duration is zero we need to calculate the ms since boot time */
391         if (duration == 0) {
392                 fp = fopen("/proc/uptime", "r");
393
394                 /*
395                  * Get uptime from /proc/uptime and if we can't then just set duration to
396                  * be 0 - it will mean that we don't calculate stats.
397                  */
398                 if (fp == NULL) {
399                         duration = 0;
400                 } else {
401                         if (fscanf(fp, "%lf", &temp) != 1) {
402                                 temp = 0;
403                         }
404                         duration = (uint64_t) (temp * 1000);
405                         fclose(fp);
406                 }
407         }
408
409         /* The second value passed into the macro is the thing being calculated */
410         CALC_STAT_CNT(read_count, reads_per_second)
411         CALC_STAT_CNT(write_count, writes_per_second)
412         CALC_STAT_CNT(other_count, other_per_second)
413         CALC_STAT_KB(read_bytes, kbytes_read_per_second)
414         CALC_STAT_KB(write_bytes, kbytes_written_per_second)
415         CALC_STAT_PCT(read_time, read_pct_wait)
416         CALC_STAT_PCT(write_time, write_pct_wait)
417         CALC_STAT_PCT(other_time, all_pct_wait)
418         CALC_STAT_CNT(resid_count, resids_per_second)
419 }
420
421 /*
422  ***************************************************************************
423  * Display statistics for current tape.
424  *
425  * IN:
426  * @tape        Statistics for current tape.
427  * @i           Index in array for current tape.
428  ***************************************************************************
429  */
430 void tape_write_stats(struct calc_stats *tape, int i)
431 {
432         char buffer[32];
433         uint64_t divisor = 1;
434
435         if (DISPLAY_MEGABYTES(flags))
436                 divisor = 1024;
437
438         sprintf(buffer, "st%i        ", i);
439         buffer[5] = 0;
440         cprintf_in(IS_STR, "%s", buffer, 0);
441         cprintf_u64(2, 7,
442                     tape->reads_per_second,
443                     tape->writes_per_second);
444         cprintf_u64(2, 11,
445                     tape->kbytes_read_per_second / divisor,
446                     tape->kbytes_written_per_second / divisor);
447         cprintf_pc(3, 3, 0,
448                    (double) tape->read_pct_wait,
449                    (double) tape->write_pct_wait,
450                    (double) tape->all_pct_wait);
451         cprintf_u64(2, 7,
452                     tape->resids_per_second,
453                     tape->other_per_second);
454         printf("\n");
455 }
456
457 /*
458  ***************************************************************************
459  * Print everything now (stats and uptime).
460  *
461  * IN:
462  * @rectime     Current date and time.
463  ***************************************************************************
464  */
465 void write_stats(struct tm *rectime)
466 {
467         int i;
468         struct calc_stats tape;
469         struct tape_stats *tmp;
470
471         /* Test stdout */
472         TEST_STDOUT(STDOUT_FILENO);
473
474         /* Print time stamp */
475         if (DISPLAY_TIMESTAMP(flags)) {
476                 if (DISPLAY_ISO(flags)) {
477                         strftime(timestamp, sizeof(timestamp), "%FT%T%z", rectime);
478                 }
479                 else {
480                         strftime(timestamp, sizeof(timestamp), "%x %X", rectime);
481                 }
482                 printf("%s\n", timestamp);
483         }
484
485         /* Print the headings */
486         tape_write_headings();
487
488         /*
489          * If either new or old is invalid or the I/Os per second is 0 and
490          * zero omit is true then we print nothing.
491          */
492         if (max_tape_drives > 0) {
493
494                 for (i = 0; i < max_tape_drives; i++) {
495                         if ((tape_new_stats[i].valid == TAPE_STATS_VALID) &&
496                                 (tape_old_stats[i].valid == TAPE_STATS_VALID)) {
497                                 tape_calc_one_stats(&tape, i);
498                                 if (!(DISPLAY_ZERO_OMIT(flags)
499                                         && (tape.other_per_second == 0)
500                                         && (tape.reads_per_second == 0)
501                                         && (tape.writes_per_second == 0)
502                                         && (tape.kbytes_read_per_second == 0)
503                                         && (tape.kbytes_written_per_second == 0)
504                                         && (tape.read_pct_wait == 0)
505                                         && (tape.write_pct_wait == 0)
506                                         && (tape.all_pct_wait == 0)
507                                         && (tape.resids_per_second == 0))) {
508                                         tape_write_stats(&tape, i);
509                                 }
510                         }
511                 }
512                 /*
513                  * Swap new and old so next time we compare against the new old stats.
514                  * If a new tape drive appears it won't appear in the output until after
515                  * the second time we gather information about it.
516                  */
517                 tmp = tape_old_stats;
518                 tape_old_stats = tape_new_stats;
519                 tape_new_stats = tmp;
520         }
521         printf("\n");
522 }
523
524 /*
525  ***************************************************************************
526  * Main loop: Read tape stats from the relevant sources and display them.
527  *
528  * IN:
529  * @count       Number of lines of stats to print.
530  * @rectime     Current date and time.
531  ***************************************************************************
532  */
533 void rw_tape_stat_loop(long int count, struct tm *rectime)
534 {
535         struct tape_stats *tmp;
536         int skip = 0;
537
538         /* Should we skip first report? */
539         if (DISPLAY_OMIT_SINCE_BOOT(flags) && interval > 0) {
540                 skip = 1;
541         }
542
543         /* Don't buffer data if redirected to a pipe */
544         setbuf(stdout, NULL);
545
546         do {
547
548                 if (tape_new_stats == NULL) {
549                         tape_gather_initial_stats();
550                 } else {
551                         tape_get_updated_stats();
552                 }
553
554                 /* Get time */
555                 get_localtime(rectime, 0);
556
557                 /* Check whether we should skip first report */
558                 if (!skip) {
559                         /* Print results */
560                         write_stats(rectime);
561
562                         if (count > 0) {
563                                 count--;
564                         }
565                 }
566                 else {
567                         skip = 0;
568                         tmp = tape_old_stats;
569                         tape_old_stats = tape_new_stats;
570                         tape_new_stats = tmp;
571                 }
572
573                 if (count) {
574                         pause();
575                 }
576         }
577         while (count);
578 }
579
580 /*
581  ***************************************************************************
582  * Main entry to the tapestat program.
583  ***************************************************************************
584  */
585 int main(int argc, char **argv)
586 {
587         int it = 0;
588         int opt = 1;
589         int i;
590         long count = 1;
591         struct utsname header;
592         struct tm rectime;
593
594 #ifdef USE_NLS
595         /* Init National Language Support */
596         init_nls();
597 #endif
598
599         /* Init color strings */
600         init_colors();
601
602         /* Get HZ */
603         get_HZ();
604
605         /* Process args... */
606         while (opt < argc) {
607                         if (!strncmp(argv[opt], "-", 1)) {
608                         for (i = 1; *(argv[opt] + i); i++) {
609
610                                 switch (*(argv[opt] + i)) {
611
612                                 case 'k':
613                                         if (DISPLAY_MEGABYTES(flags)) {
614                                                 usage(argv[0]);
615                                         }
616                                         /* Display stats in kB/s */
617                                         flags |= T_D_KILOBYTES;
618                                         break;
619
620                                 case 'm':
621                                         if (DISPLAY_KILOBYTES(flags)) {
622                                                 usage(argv[0]);
623                                         }
624                                         /* Display stats in MB/s */
625                                         flags |= T_D_MEGABYTES;
626                                         break;
627
628                                 case 't':
629                                         /* Display timestamp */
630                                         flags |= T_D_TIMESTAMP;
631                                         break;
632
633                                 case 'y':
634                                         /* Don't display stats since system restart */
635                                         flags |= T_D_OMIT_SINCE_BOOT;
636                                         break;
637
638                                 case 'z':
639                                         /* Omit output for devices with no activity */
640                                         flags |= T_D_ZERO_OMIT;
641                                         break;
642
643                                 case 'V':
644                                         /* Print version number and exit */
645                                         print_version();
646                                         break;
647
648                                 default:
649                                         usage(argv[0]);
650                                 }
651                         }
652                         opt++;
653                 }
654
655                 else if (!it) {
656                         interval = atol(argv[opt++]);
657                         if (interval < 0) {
658                                 usage(argv[0]);
659                         }
660                         count = -1;
661                         it = 1;
662                 }
663
664                 else if (it > 0) {
665                         count = atol(argv[opt++]);
666                         if ((count < 1) || !interval) {
667                                 usage(argv[0]);
668                         }
669                         it = -1;
670                 }
671                 else {
672                         usage(argv[0]);
673                 }
674         }
675
676         if (!interval) {
677                 count = 1;
678         }
679
680         tape_initialise();
681
682         get_localtime(&rectime, 0);
683
684         /* Get system name, release number and hostname */
685         uname(&header);
686         if (print_gal_header(&rectime, header.sysname, header.release,
687                              header.nodename, header.machine, cpu_nr)) {
688                 flags |= T_D_ISO;
689         }
690         printf("\n");
691
692         /* Set a handler for SIGALRM */
693         memset(&alrm_act, 0, sizeof(alrm_act));
694         alrm_act.sa_handler = alarm_handler;
695         sigaction(SIGALRM, &alrm_act, NULL);
696         alarm(interval);
697
698         /* Main loop */
699         rw_tape_stat_loop(count, &rectime);
700
701         /* Free structures */
702         tape_uninitialise();
703
704         return 0;
705 }