forked from sysstat/sysstat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.c
1766 lines (1560 loc) · 42.8 KB
/
common.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* sar, sadc, sadf, mpstat and iostat common routines.
* (C) 1999-2024 by Sebastien GODARD (sysstat <at> orange.fr)
*
***************************************************************************
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation; either version 2 of the License, or (at your *
* option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without the implied warranty of MERCHANTABILITY *
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License *
* for more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA *
***************************************************************************
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <inttypes.h>
#include <time.h>
#include <errno.h>
#include <unistd.h> /* For STDOUT_FILENO, among others */
#include <sys/ioctl.h>
#include <sys/types.h>
#include <dirent.h>
#include <ctype.h>
#include <limits.h>
#include <libgen.h>
#include "version.h"
#include "common.h"
#include "ioconf.h"
#ifdef USE_NLS
#include <locale.h>
#include <libintl.h>
#define _(string) gettext(string)
#else
#define _(string) (string)
#endif
/* Number of decimal places */
extern int dplaces_nr;
/* Units (sectors, Bytes, kilobytes, etc.) */
char units[] = {'s', 'B', 'k', 'M', 'G', 'T', 'P', '?'};
/* Number of ticks per second */
unsigned long hz;
/* Number of bit shifts to convert pages to kB */
unsigned int kb_shift;
/* Colors strings */
char sc_percent_warn[MAX_SGR_LEN] = C_BOLD_MAGENTA;
char sc_percent_xtreme[MAX_SGR_LEN] = C_BOLD_RED;
char sc_zero_int_stat[MAX_SGR_LEN] = C_LIGHT_BLUE;
char sc_int_stat[MAX_SGR_LEN] = C_BOLD_BLUE;
char sc_item_name[MAX_SGR_LEN] = C_LIGHT_GREEN;
char sc_sa_restart[MAX_SGR_LEN] = C_LIGHT_RED;
char sc_sa_comment[MAX_SGR_LEN] = C_LIGHT_YELLOW;
char sc_trend_pos[MAX_SGR_LEN] = C_BOLD_GREEN;
char sc_trend_neg[MAX_SGR_LEN] = C_BOLD_RED;
char sc_normal[MAX_SGR_LEN] = C_NORMAL;
/*
* Type of persistent device names in lowercase letters
* (e.g. "uuid", "label", "path"...) Used in sar and iostat.
*/
char persistent_name_type[MAX_FILE_LEN];
/*
***************************************************************************
* Print sysstat version number, environment variables and exit.
*
* IN:
* @env Array with environment variable names.
* @n Number of environment variables.
***************************************************************************
*/
void print_version(char *env[], int n)
{
char *e;
int i;
/* Display contents of environment variables */
for (i = 0; i < n; i++) {
if ((e = __getenv(env[i])) != NULL) {
printf("%s=%s\n", env[i], e);
}
}
/* Print sysstat version number */
printf(_("sysstat version %s\n"), VERSION);
printf("(C) Sebastien Godard (sysstat <at> orange.fr)\n");
exit(0);
}
/*
***************************************************************************
* Get date and time, expressed in UTC or in local time.
*
* IN:
* @d_off Day offset (number of days to go back in the past).
* @utc TRUE if date and time shall be expressed in UTC.
*
* OUT:
* @rectime Current local date and time.
*
* RETURNS:
* Value of time in seconds since the Epoch (always in UTC)
***************************************************************************
*/
time_t get_xtime(struct tm *rectime, int d_off, int utc)
{
time_t timer;
timer = __time(NULL);
timer -= SEC_PER_DAY * d_off;
if (utc) {
/* Get date and time in UTC */
gmtime_r(&timer, rectime);
}
else {
/* Get date and time in local time */
localtime_r(&timer, rectime);
}
return timer;
}
/*
***************************************************************************
* Get date and time and take into account <ENV_TIME_DEFTM> variable.
*
* IN:
* @d_off Day offset (number of days to go back in the past).
*
* OUT:
* @rectime Current date and time.
*
* RETURNS:
* Value of time in seconds since the Epoch.
***************************************************************************
*/
time_t get_time(struct tm *rectime, int d_off)
{
static int utc = 0;
if (!utc) {
char *e;
/* Read environment variable value once */
if ((e = __getenv(ENV_TIME_DEFTM)) != NULL) {
utc = !strcmp(e, K_UTC);
}
utc++;
}
return get_xtime(rectime, d_off, utc == 2);
}
#ifdef USE_NLS
/*
***************************************************************************
* Init National Language Support.
***************************************************************************
*/
void init_nls(void)
{
setlocale(LC_MESSAGES, "");
setlocale(LC_CTYPE, "");
setlocale(LC_TIME, "");
setlocale(LC_NUMERIC, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
}
#endif
/*
***************************************************************************
* Test whether given name is a device or a partition, using sysfs.
*
* IN:
* @sysdev sysfs location.
* @name Device or partition name.
* @allow_virtual TRUE if virtual devices are also accepted.
* The device is assumed to be virtual if no
* /sys/block/<device>/device link exists.
*
* RETURNS:
* TRUE if @name is a device, and FALSE if it's a partition.
***************************************************************************
*/
int is_device(char *sysdev, char *name, int allow_virtual)
{
char syspath[PATH_MAX];
char *slash;
/* Some devices may have a slash in their name (eg. cciss/c0d0...) */
while ((slash = strchr(name, '/'))) {
*slash = '!';
}
snprintf(syspath, sizeof(syspath), "%s/%s/%s%s", sysdev, __BLOCK, name,
allow_virtual ? "" : "/device");
return !(access(syspath, F_OK));
}
/*
***************************************************************************
* Get page shift in kB.
***************************************************************************
*/
void get_kb_shift(void)
{
int shift = 0;
long size;
/* One can also use getpagesize() to get the size of a page */
if ((size = sysconf(_SC_PAGESIZE)) == -1) {
perror("sysconf");
}
size >>= 10; /* Assume that a page has a minimum size of 1 kB */
while (size > 1) {
shift++;
size >>= 1;
}
kb_shift = (unsigned int) shift;
}
/*
***************************************************************************
* Get number of clock ticks per second.
***************************************************************************
*/
void get_HZ(void)
{
long ticks;
if ((ticks = sysconf(_SC_CLK_TCK)) == -1) {
perror("sysconf");
}
hz = (unsigned long) ticks;
}
/*
***************************************************************************
* Unhandled situation: Panic and exit. Should never happen.
*
* IN:
* @function Function name where situation occured.
* @error_code Error code.
***************************************************************************
*/
void sysstat_panic(const char *function, int error_code)
{
fprintf(stderr, "sysstat: %s[%d]: Internal error...\n",
function, error_code);
exit(1);
}
/*
***************************************************************************
* Extract WWWN identifiers from filename, as read from /dev/disk/by-id.
*
* Sample valid names read from /dev/disk/by-id:
* wwn-0x5000cca369f193ac
* wwn-0x5000cca369f193ac-part12
* wwn-0x600605b00a2bdf00242b28c10dcb1999
* wwn-0x600605b00a2bdf00242b28c10dcb1999-part2
*
* WWN ids like these ones are ignored:
* wwn-0x5438850077615869953x
* wwn-0x5438850077615869953x-part1
*
* IN:
* @name Filename read from /dev/disk/by-id.
*
* OUT:
* @wwn WWN identifier (8 or 16 hex characters).
* @part-nr Partition number if applicable.
*
* RETURNS:
* 0 on success, -1 otherwise.
***************************************************************************
*/
int extract_wwnid(char *name, unsigned long long *wwn, unsigned int *part_nr)
{
char id[17];
char *s;
int wwnlen;
*wwn = *(wwn + 1) = 0ULL;
*part_nr = 0;
/* Check name */
if (((wwnlen = strlen(name)) < 22) || (strncmp(name, "wwn-0x", 6)))
return -1;
/* Is there a partition number? */
if ((s = strstr(name, "-part")) != NULL) {
/* Yes: Get partition number */
if (sscanf(s + 5, "%u", part_nr) == 0)
return -1;
wwnlen = s - name - 6;
}
else {
wwnlen -= 6; /* Don't count "wwn-0x" */
}
/* Check WWN length */
if ((wwnlen != 16) && (wwnlen != 32))
return -1;
/* Extract first 16 hex chars of WWN */
strncpy(id, name + 6, 16);
id[16] = '\0';
if (sscanf(id, "%llx", wwn) == 0)
return -1;
if (strlen(name) < 38)
/* This is a short (16 hex chars) WWN id */
return 0;
/* Extract second part of WWN */
if (sscanf(name + 22, "%llx", wwn + 1) == 0)
return -1;
return 0;
}
/*
***************************************************************************
* Get WWWN identifiers from a pretty filename using links present in
* /dev/disk/by-id directory.
*
* IN:
* @pretty Pretty name (e.g. sda, sdb3...).
*
* OUT:
* @wwn WWN identifier (8 or 16 hex characters).
* @part-nr Partition number if applicable.
*
* RETURNS:
* 0 on success, -1 otherwise.
***************************************************************************
*/
int get_wwnid_from_pretty(char *pretty, unsigned long long *wwn, unsigned int *part_nr)
{
DIR *dir;
struct dirent *drd;
ssize_t r;
char link[PATH_MAX], target[PATH_MAX], wwn_name[FILENAME_MAX];
char *name;
int rc = -1;
/* Open /dev/disk/by-id directory */
if ((dir = opendir(DEV_DISK_BY_ID)) == NULL)
return -1;
/* Get current id */
while ((drd = readdir(dir)) != NULL) {
if (strncmp(drd->d_name, "wwn-0x", 6))
continue;
/* Get absolute path for current persistent name */
snprintf(link, PATH_MAX, "%s/%s", DEV_DISK_BY_ID, drd->d_name);
/* Persistent name is usually a symlink: Read it... */
r = readlink(link, target, PATH_MAX);
if ((r <= 0) || (r >= PATH_MAX))
continue;
target[r] = '\0';
/* ... and get device pretty name it points at */
name = basename(target);
if (!name || (name[0] == '\0'))
continue;
if (!strncmp(name, pretty, FILENAME_MAX)) {
/* We have found pretty name for current persistent one */
strncpy(wwn_name, drd->d_name, MINIMUM(sizeof(wwn_name), sizeof(drd->d_name)));
wwn_name[sizeof(wwn_name) - 1] = '\0';
/* Try to extract WWN */
if (!extract_wwnid(wwn_name, wwn, part_nr)) {
/* WWN successfully extracted */
rc = 0;
break;
}
}
}
/* Close directory */
closedir(dir);
return rc;
}
/*
***************************************************************************
* Check if a directory exists.
*
* IN:
* @dirname Name of the directory.
*
* RETURNS:
* TRUE if @dirname is actually an existing directory.
***************************************************************************
*/
int check_dir(char *dirname)
{
struct stat sb;
if (!stat(dirname, &sb) && S_ISDIR(sb.st_mode))
return 1;
return 0;
}
/*
* **************************************************************************
* Check if the multiplication of the 3 values may be greater than UINT_MAX.
*
* IN:
* @val1 First value.
* @val2 Second value.
* @val3 Third value.
***************************************************************************
*/
void check_overflow(unsigned int val1, unsigned int val2,
unsigned int val3)
{
if ((val1 != 0) && (val2 != 0) && (val3 != 0) &&
(((unsigned long long) UINT_MAX / (unsigned long long) val1 <
(unsigned long long) val2) ||
((unsigned long long) UINT_MAX / ((unsigned long long) val1 * (unsigned long long) val2) <
(unsigned long long) val3))) {
#ifdef DEBUG
fprintf(stderr, "%s: Overflow detected (%u,%u,%u). Aborting...\n",
__FUNCTION__, val1, val2, val3);
#endif
exit(4);
}
}
#ifndef SOURCE_SADC
/*
***************************************************************************
* Read /proc/devices file and get device-mapper major number.
* If device-mapper entry is not found in file, assume it's not active.
*
* RETURNS:
* Device-mapper major number.
***************************************************************************
*/
unsigned int get_devmap_major(void)
{
FILE *fp;
char line[128];
/*
* Linux uses 12 bits for the major number,
* so this shouldn't match any real device.
*/
unsigned int dm_major = ~0U;
if ((fp = fopen(DEVICES, "r")) == NULL)
return dm_major;
while (fgets(line, sizeof(line), fp) != NULL) {
if (strstr(line, "device-mapper")) {
/* Read device-mapper major number */
sscanf(line, "%u", &dm_major);
}
}
fclose(fp);
return dm_major;
}
/*
***************************************************************************
* Returns whether S_TIME_FORMAT is set to ISO.
*
* RETURNS:
* TRUE if S_TIME_FORMAT is set to ISO, or FALSE otherwise.
***************************************************************************
*/
int is_iso_time_fmt(void)
{
static int is_iso = -1;
if (is_iso < 0) {
char *e;
is_iso = (((e = __getenv(ENV_TIME_FMT)) != NULL) && !strcmp(e, K_ISO));
}
return is_iso;
}
/*
***************************************************************************
* Print tabulations
*
* IN:
* @nr_tab Number of tabs to print.
***************************************************************************
*/
void prtab(int nr_tab)
{
int i;
for (i = 0; i < nr_tab; i++) {
printf("\t");
}
}
/*
***************************************************************************
* printf() function modified for XML-like output. Don't print a CR at the
* end of the line.
*
* IN:
* @nr_tab Number of tabs to print.
* @fmtf printf() format.
***************************************************************************
*/
void xprintf0(int nr_tab, const char *fmtf, ...)
{
static char buf[1024];
va_list args;
va_start(args, fmtf);
vsnprintf(buf, sizeof(buf), fmtf, args);
va_end(args);
prtab(nr_tab);
printf("%s", buf);
}
/*
***************************************************************************
* printf() function modified for XML-like output. Print a CR at the end of
* the line.
*
* IN:
* @nr_tab Number of tabs to print.
* @fmtf printf() format.
***************************************************************************
*/
void xprintf(int nr_tab, const char *fmtf, ...)
{
static char buf[1024];
va_list args;
va_start(args, fmtf);
vsnprintf(buf, sizeof(buf), fmtf, args);
va_end(args);
prtab(nr_tab);
printf("%s\n", buf);
}
/*
***************************************************************************
* Get report date as a string of characters.
*
* IN:
* @tm_time Date to display (don't use time fields).
* @cur_date String where date will be saved.
* @sz Max size of cur_date string.
*
* OUT:
* @cur_date Date (string format).
*
* RETURNS:
* TRUE if S_TIME_FORMAT is set to ISO, or FALSE otherwise.
***************************************************************************
*/
int set_report_date(struct tm *tm_time, char cur_date[], int sz)
{
if (tm_time == NULL) {
strncpy(cur_date, "?/?/?", sz);
cur_date[sz - 1] = '\0';
}
else if (is_iso_time_fmt()) {
strftime(cur_date, sz, "%Y-%m-%d", tm_time);
return 1;
}
else {
strftime(cur_date, sz, "%x", tm_time);
}
return 0;
}
/*
***************************************************************************
* Print banner.
*
* IN:
* @tm_time Date to display (don't use time fields).
* @sysname System name to display.
* @release System release number to display.
* @nodename Hostname to display.
* @machine Machine architecture to display.
* @cpu_nr Number of CPU.
* @format Set to FALSE for (default) plain output, and to TRUE for
* JSON format output.
*
* RETURNS:
* TRUE if S_TIME_FORMAT is set to ISO, or FALSE otherwise.
***************************************************************************
*/
int print_gal_header(struct tm *tm_time, char *sysname, char *release,
char *nodename, char *machine, int cpu_nr, int format)
{
char cur_date[TIMESTAMP_LEN];
int rc = 0;
rc = set_report_date(tm_time, cur_date, sizeof(cur_date));
if (format == PLAIN_OUTPUT) {
/* Plain output */
printf("%s %s (%s) \t%s \t_%s_\t(%d CPU)\n", sysname, release, nodename,
cur_date, machine, cpu_nr);
}
else {
/* JSON output */
xprintf(0, "{\"sysstat\": {");
xprintf(1, "\"hosts\": [");
xprintf(2, "{");
xprintf(3, "\"nodename\": \"%s\",", nodename);
xprintf(3, "\"sysname\": \"%s\",", sysname);
xprintf(3, "\"release\": \"%s\",", release);
xprintf(3, "\"machine\": \"%s\",", machine);
xprintf(3, "\"number-of-cpus\": %d,", cpu_nr);
xprintf(3, "\"date\": \"%s\",", cur_date);
xprintf(3, "\"statistics\": [");
}
return rc;
}
/*
***************************************************************************
* Get number of rows for current window.
* If stdout is not a terminal then use the value given by environment
* variable S_REPEAT_HEADER if existent.
*
* RETURNS:
* Number of rows.
***************************************************************************
*/
int get_win_height(void)
{
struct winsize win;
char *e;
/*
* This default value will be used whenever STDOUT
* is redirected to a pipe or a file and S_REPEAT_HEADER variable is not set
*/
int rows = 3600 * 24;
/* Get number of lines of current terminal */
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) != -1) {
if (win.ws_row > 2) {
rows = win.ws_row - 2;
}
}
/* STDOUT is not a terminal. Look for S_REPEAT_HEADER variable's value instead */
else if ((e = __getenv(ENV_REPEAT_HEADER)) != NULL) {
if (strspn(e, DIGITS) == strlen(e)) {
int v = atol(e);
if (v > 0) {
rows = v;
}
}
}
return rows;
}
/*
***************************************************************************
* Canonicalize and remove /dev from path name. If the device has a slash
* character in its name, replace it with a bang character ('!'), e.g.:
* cciss/c0d0 -> cciss!c0d0
* cciss/c0d0p1 -> cciss!c0d0p1
*
* IN:
* @name Device name (may begin with "/dev/" or can be a symlink).
*
* RETURNS:
* Device basename.
***************************************************************************
*/
char *device_name(char *name)
{
static char out[MAX_FILE_LEN];
char *resolved_name = NULL, *slash;
int i = 0;
/* realpath() creates new string, so we need to free it later */
resolved_name = __realpath(name, NULL);
/* If path doesn't exist, just return input */
if (!resolved_name) {
return name;
}
#ifdef DEBUG
fprintf(stderr, "Real pathname: %s (%s)\n", resolved_name, name);
#endif
if (!strncmp(resolved_name, "/dev/", 5)) {
i = 5;
}
strncpy(out, resolved_name + i, sizeof(out));
out[sizeof(out) - 1] = '\0';
/* Some devices may have a slash in their name (eg. cciss/c0d0...) */
while ((slash = strchr(out, '/'))) {
*slash = '!';
}
free(resolved_name);
return out;
}
/*
***************************************************************************
* Workaround for CPU counters read from /proc/stat: Dyn-tick kernels
* have a race issue that can make those counters go backward.
***************************************************************************
*/
double ll_sp_value(unsigned long long value1, unsigned long long value2,
unsigned long long itv)
{
if (value2 < value1)
return (double) 0;
else
return SP_VALUE(value1, value2, itv);
}
/*
***************************************************************************
* Compute time interval.
*
* IN:
* @prev_uptime Previous uptime value (in jiffies or 1/100th of a second).
* @curr_uptime Current uptime value (in jiffies or 1/100th of a second).
*
* RETURNS:
* Interval of time in jiffies or 1/100th of a second.
***************************************************************************
*/
unsigned long long get_interval(unsigned long long prev_uptime,
unsigned long long curr_uptime)
{
unsigned long long itv;
/* prev_time=0 when displaying stats since system startup */
itv = curr_uptime - prev_uptime;
if (!itv) { /* Paranoia checking */
itv = 1;
}
return itv;
}
/*
***************************************************************************
* Count number of bits set in an array.
*
* IN:
* @ptr Pointer to array.
* @size Size of array in bytes.
*
* RETURNS:
* Number of bits set in the array.
***************************************************************************
*/
int count_bits(void *ptr, int size)
{
int nr = 0, i, k;
char *p;
p = ptr;
for (i = 0; i < size; i++, p++) {
k = 0x80;
while (k) {
if (*p & k)
nr++;
k >>= 1;
}
}
return nr;
}
/*
***************************************************************************
* Convert in-place input string to lowercase.
*
* IN:
* @str String to be converted.
*
* OUT:
* @str String in lowercase.
*
* RETURNS:
* String in lowercase.
***************************************************************************
*/
char *strtolower(char *str)
{
char *cp = str;
while (*cp) {
*cp = tolower(*cp);
cp++;
}
return(str);
}
/*
***************************************************************************
* Get persistent type name directory from type.
*
* IN:
* @type Persistent type name (UUID, LABEL, etc.)
*
* RETURNS:
* Path to the persistent type name directory, or NULL if access is denied
* or strings have been truncated.
***************************************************************************
*/
char *get_persistent_type_dir(char *type)
{
static char dir[PATH_MAX];
int n;
n = snprintf(dir, sizeof(dir), "%s-%s", DEV_DISK_BY, type);
if ((n >= sizeof(dir)) || access(dir, R_OK)) {
return (NULL);
}
return (dir);
}
/*
***************************************************************************
* Get persistent name absolute path.
*
* IN:
* @name Persistent name.
*
* RETURNS:
* Path to the persistent name, or NULL if file doesn't exist or strings
* have been truncated.
***************************************************************************
*/
char *get_persistent_name_path(char *name)
{
static char path[PATH_MAX];
int n;
n = snprintf(path, sizeof(path), "%s/%s",
get_persistent_type_dir(persistent_name_type), name);
if ((n >= sizeof(path)) || access(path, F_OK)) {
return (NULL);
}
return (path);
}
/*
***************************************************************************
* Get files from persistent type name directory.
*
* RETURNS:
* List of files in the persistent type name directory in alphabetical order.
***************************************************************************
*/
char **get_persistent_names(void)
{
int n, i, k = 0;
char *dir;
char **files = NULL;
struct dirent **namelist;
/* Get directory name for selected persistent type */
dir = get_persistent_type_dir(persistent_name_type);
if (!dir)
return (NULL);
n = scandir(dir, &namelist, NULL, alphasort);
if (n < 0)
return (NULL);
/* If directory is empty, it contains 2 entries: "." and ".." */
if (n <= 2)
/* Free list and return NULL */
goto free_list;
/* Ignore the "." and "..", but keep place for one last NULL. */
files = (char **) calloc(n - 1, sizeof(char *));
if (!files)
goto free_list;
/*
* i is for traversing namelist, k is for files.
* i != k because we are ignoring "." and ".." entries.
*/
for (i = 0; i < n; i++) {
/* Ignore "." and ".." */
if (!strcmp(".", namelist[i]->d_name) ||
!strcmp("..", namelist[i]->d_name))
continue;
files[k] = (char *) calloc(strlen(namelist[i]->d_name) + 1, sizeof(char));
if (!files[k])
continue;
strcpy(files[k++], namelist[i]->d_name);
}
files[k] = NULL;
free_list:
for (i = 0; i < n; i++) {
free(namelist[i]);
}
free(namelist);
return (files);
}
/*
***************************************************************************
* Get persistent name from pretty name.
*
* IN:
* @pretty Pretty name (e.g. sda, sda1, ..).
*
* RETURNS:
* Persistent name.
***************************************************************************
*/
char *get_persistent_name_from_pretty(char *pretty)
{
int i = -1;
ssize_t r;
char *link, *name;
char **persist_names;
char target[PATH_MAX];
static char persist_name[FILENAME_MAX];
persist_name[0] = '\0';
/* Get list of files from persistent type name directory */
persist_names = get_persistent_names();
if (!persist_names)
return (NULL);
while (persist_names[++i]) {
/* Get absolute path for current persistent name */
link = get_persistent_name_path(persist_names[i]);
if (!link)
continue;
/* Persistent name is usually a symlink: Read it... */
r = readlink(link, target, PATH_MAX);
if ((r <= 0) || (r >= PATH_MAX))
continue;