summaryrefslogtreecommitdiffstats
path: root/ksysguard/ksysguardd/Linux/stat.c
blob: 0e03e4d531394fa68a82dc360cf84fad4aecb9cb (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
/*
    KSysGuard, the KDE System Guard

    Copyright (c) 1999, 2000 Chris Schlaeger <cs@kde.org>

    This program is free software; you can redistribute it and/or
    modify it under the terms of version 2 of the GNU General Public
    License as published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even 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-1301, USA.

*/

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "Command.h"
#include "ksysguardd.h"

#include "stat.h"

typedef struct
{
  /* A CPU can be loaded with user processes, reniced processes and
   * system processes. Unused processing time is called idle load.
   * These variable store the percentage of each load type. */
  int userLoad;
  int niceLoad;
  int sysLoad;
  int idleLoad;

  /* To calculate the loads we need to remember the tick values for each
   * load type. */
  unsigned long userTicks;
  unsigned long niceTicks;
  unsigned long sysTicks;
  unsigned long idleTicks;
} CPULoadInfo;

typedef struct
{
  unsigned long delta;
  unsigned long old;
} DiskLoadSample;

typedef struct
{
  /* 5 types of samples are taken:
       total, rio, wio, rBlk, wBlk */
  DiskLoadSample s[ 5 ];
} DiskLoadInfo;

typedef struct DiskIOInfo
{
  int major;
  int minor;
  int alive;
  DiskLoadSample total;
  DiskLoadSample rio;
  DiskLoadSample wio;
  DiskLoadSample rblk;
  DiskLoadSample wblk;
  struct DiskIOInfo* next;
} DiskIOInfo;

#define STATBUFSIZE (32 * 1024)

static char StatBuf[ STATBUFSIZE ];
static char VmStatBuf[ STATBUFSIZE ];
static char IOStatBuf[ STATBUFSIZE ];	/* Buffer for /proc/diskstats */
static int Dirty = 0;

/* We have observed deviations of up to 5% in the accuracy of the timer
 * interrupts. So we try to measure the interrupt interval and use this
 * value to calculate timing dependant values. */
static float timeInterval = 0;
static struct timeval lastSampling;
static struct timeval currSampling;
static struct SensorModul* StatSM;

static CPULoadInfo CPULoad;
static CPULoadInfo* SMPLoad = 0;
static unsigned CPUCount = 0;
static DiskLoadInfo* DiskLoad = 0;
static unsigned DiskCount = 0;
static DiskIOInfo* DiskIO = 0;
static unsigned long PageIn = 0;
static unsigned long OldPageIn = 0;
static unsigned long PageOut = 0;
static unsigned long OldPageOut = 0;
static unsigned long Ctxt = 0;
static unsigned long OldCtxt = 0;
static unsigned int NumOfInts = 0;
static unsigned long* OldIntr = 0;
static unsigned long* Intr = 0;

static int initStatDisk( char* tag, char* buf, const char* label, const char* shortLabel,
                         int idx, cmdExecutor ex, cmdExecutor iq );
static void updateCPULoad( const char* line, CPULoadInfo* load );
static int processDisk( char* tag, char* buf, const char* label, int idx );
static void processStat( void );
static int processDiskIO( const char* buf );
static int process26DiskIO( const char* buf );
static void cleanupDiskList( void );

static int initStatDisk( char* tag, char* buf, const char* label,
                         const char* shortLabel, int idx, cmdExecutor ex, cmdExecutor iq )
{
  char sensorName[ 128 ];

  gettimeofday( &lastSampling, 0 );

  if ( strcmp( label, tag ) == 0 ) {
    unsigned int i;
    buf = buf + strlen( label ) + 1;

    for ( i = 0; i < DiskCount; ++i ) {
      sscanf( buf, "%lu", &DiskLoad[ i ].s[ idx ].old );
      while ( *buf && isblank( *buf++ ) );
      while ( *buf && isdigit( *buf++ ) );
      sprintf( sensorName, "disk/disk%d/%s", i, shortLabel );
      registerMonitor( sensorName, "integer", ex, iq, StatSM );
    }

    return 1;
  }

  return 0;
}

static void updateCPULoad( const char* line, CPULoadInfo* load )
{
  unsigned long currUserTicks, currSysTicks, currNiceTicks, currIdleTicks;
  unsigned long totalTicks;

  sscanf( line, "%*s %lu %lu %lu %lu", &currUserTicks, &currNiceTicks,
          &currSysTicks, &currIdleTicks );

  totalTicks = ( currUserTicks - load->userTicks ) +
               ( currSysTicks - load->sysTicks ) +
               ( currNiceTicks - load->niceTicks ) +
               ( currIdleTicks - load->idleTicks );

  if ( totalTicks > 10 ) {
    load->userLoad = ( 100 * ( currUserTicks - load->userTicks ) ) / totalTicks;
    load->sysLoad = ( 100 * ( currSysTicks - load->sysTicks ) ) / totalTicks;
    load->niceLoad = ( 100 * ( currNiceTicks - load->niceTicks ) ) / totalTicks;
    load->idleLoad = ( 100 - ( load->userLoad + load->sysLoad + load->niceLoad ) );
  } else
    load->userLoad = load->sysLoad = load->niceLoad = load->idleLoad = 0;

  load->userTicks = currUserTicks;
  load->sysTicks = currSysTicks;
  load->niceTicks = currNiceTicks;
  load->idleTicks = currIdleTicks;
}

static int processDisk( char* tag, char* buf, const char* label, int idx )
{
  if ( strcmp( label, tag ) == 0 ) {
    unsigned long val;
    unsigned int i;
    buf = buf + strlen( label ) + 1;

    for ( i = 0; i < DiskCount; ++i ) {
      sscanf( buf, "%lu", &val );
      while ( *buf && isblank( *buf++ ) );
      while ( *buf && isdigit( *buf++ ) );
      DiskLoad[ i ].s[ idx ].delta = val - DiskLoad[ i ].s[ idx ].old;
      DiskLoad[ i ].s[ idx ].old = val;
    }

    return 1;
  }

  return 0;
}

static int processDiskIO( const char* buf )
{
  /* Process disk_io lines as provided by 2.4.x kernels.
   * disk_io: (2,0):(3,3,6,0,0) (3,0):(1413012,511622,12155382,901390,26486215) */
  int major, minor;
  unsigned long total, rblk, rio, wblk, wio;
  DiskIOInfo* ptr = DiskIO;
  DiskIOInfo* last = 0;
  char sensorName[ 128 ];
  const char* p;

  p = buf + strlen( "disk_io: " );
  while ( p && *p ) {
    if ( sscanf( p, "(%d,%d):(%lu,%lu,%lu,%lu,%lu)", &major, &minor,
                 &total, &rio, &rblk, &wio, &wblk ) != 7 )
      return -1;

    last = 0;
    ptr = DiskIO;
    while ( ptr ) {
      if ( ptr->major == major && ptr->minor == minor ) {
        /* The IO device has already been registered. */
        ptr->total.delta = total - ptr->total.old;
        ptr->total.old = total;
        ptr->rio.delta = rio - ptr->rio.old;
        ptr->rio.old = rio;
        ptr->wio.delta = wio - ptr->wio.old;
        ptr->wio.old = wio;
        ptr->rblk.delta = rblk - ptr->rblk.old;
        ptr->rblk.old = rblk;
        ptr->wblk.delta = wblk - ptr->wblk.old;
        ptr->wblk.old = wblk;
        ptr->alive = 1;
        break;
      }
      last = ptr;
      ptr = ptr->next;
    }

    if ( !ptr ) {
      /* The IO device has not been registered yet. We need to add it. */
      ptr = (DiskIOInfo*)malloc( sizeof( DiskIOInfo ) );
      ptr->major = major;
      ptr->minor = minor;
      ptr->total.delta = 0;
      ptr->total.old = total;
      ptr->rio.delta = 0;
      ptr->rio.old = rio;
      ptr->wio.delta = 0;
      ptr->wio.old = wio;
      ptr->rblk.delta = 0;
      ptr->rblk.old = rblk;
      ptr->wblk.delta = 0;
      ptr->wblk.old = wblk;
      ptr->alive = 1;
      ptr->next = 0;
      if ( last ) {
        /* Append new entry at end of list. */
        last->next = ptr;
      } else {
        /* List is empty, so we insert the fist element into the list. */
        DiskIO = ptr;
      }

      sprintf( sensorName, "disk/%d:%d/total", major, minor );
      registerMonitor( sensorName, "integer", printDiskIO, printDiskIOInfo, StatSM );
      sprintf( sensorName, "disk/%d:%d/rio", major, minor );
      registerMonitor( sensorName, "integer", printDiskIO, printDiskIOInfo, StatSM );
      sprintf( sensorName, "disk/%d:%d/wio", major, minor );
      registerMonitor( sensorName, "integer", printDiskIO, printDiskIOInfo, StatSM );
      sprintf( sensorName, "disk/%d:%d/rblk", major, minor );
      registerMonitor( sensorName, "integer", printDiskIO, printDiskIOInfo, StatSM );
      sprintf( sensorName, "disk/%d:%d/wblk", major, minor );
      registerMonitor( sensorName, "integer", printDiskIO, printDiskIOInfo, StatSM );
    }
    /* Move p after the sencond ')'. We can safely assume that
     * those two ')' exist. */
    p = strchr( p, ')' ) + 1;
    p = strchr( p, ')' ) + 1;
    if ( p && *p )
      p = strchr( p, '(' );
  }

  return 0;
}

static int process26DiskIO( const char* buf )
{
   /* Process values from /proc/diskstats (Linux >= 2.6.x) */

   /* For each disk /proc/diskstats includes lines as follows:
    *   3    0 hda 1314558 74053 26451438 14776742 1971172 4607401 52658448 202855090 0 9597019 217637839
    *   3    1 hda1 178 360 0 0
    *   3    2 hda2 354 360 0 0
    *   3    3 hda3 354 360 0 0
    *   3    4 hda4 0 0 0 0
    *   3    5 hda5 529506 9616000 4745856 37966848
    *
    * - See Documentation/iostats.txt for details on the changes
    */
   int                      major, minor;
   char                     devname[16];
   unsigned long            total,
                            rio, rmrg, rblk, rtim,
                            wio, wmrg, wblk, wtim,
                            ioprog, iotim, iotimw;
   DiskIOInfo               *ptr = DiskIO;
   DiskIOInfo               *last = 0;
   char                     sensorName[128];

   switch (sscanf(buf, "%d %d %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
              &major, &minor, devname,
              &rio, &rmrg, &rblk, &rtim,
              &wio, &wmrg, &wblk, &wtim,
              &ioprog, &iotim, &iotimw))
   {
      case 7:
         /* Partition stats entry */
         /* Adjust read fields rio rmrg rblk rtim -> rio rblk wio wblk */
         wblk = rtim;
         wio = rblk;
         rblk = rmrg;

         total = rio + wio;

         break;
      case 14:
         /* Disk stats entry */
         total = rio + wio;

         break;
      default:
         /* Something unexepected */
         return -1;
   }

   last = 0;
   ptr = DiskIO;
   while (ptr)
   {
      if (ptr->major == major && ptr->minor == minor)
      {
         /* The IO device has already been registered. */
         ptr->total.delta = total - ptr->total.old;
         ptr->total.old = total;
         ptr->rio.delta = rio - ptr->rio.old;
         ptr->rio.old = rio;
         ptr->wio.delta = wio - ptr->wio.old;
         ptr->wio.old = wio;
         ptr->rblk.delta = rblk - ptr->rblk.old;
         ptr->rblk.old = rblk;
         ptr->wblk.delta = wblk - ptr->wblk.old;
         ptr->wblk.old = wblk;
         ptr->alive = 1;
         break;
      }

      last = ptr;
      ptr = ptr->next;
   }

   if (!ptr)
   {
      /* The IO device has not been registered yet. We need to add it. */
      ptr = (DiskIOInfo*)malloc( sizeof( DiskIOInfo ) );
      ptr->major = major;
      ptr->minor = minor;
      ptr->total.delta = 0;
      ptr->total.old = total;
      ptr->rio.delta = 0;
      ptr->rio.old = rio;
      ptr->wio.delta = 0;
      ptr->wio.old = wio;
      ptr->rblk.delta = 0;
      ptr->rblk.old = rblk;
      ptr->wblk.delta = 0;
      ptr->wblk.old = wblk;
      ptr->alive = 1;
      ptr->next = 0;
      if (last)
      {
         /* Append new entry at end of list. */
         last->next = ptr;
      }
      else
      {
         /* List is empty, so we insert the fist element into the list. */
         DiskIO = ptr;
      }

      sprintf(sensorName, "disk/%d:%d/total", major, minor);
      registerMonitor(sensorName, "integer", printDiskIO, printDiskIOInfo,
         StatSM);
      sprintf(sensorName, "disk/%d:%d/rio", major, minor);
      registerMonitor(sensorName, "integer", printDiskIO, printDiskIOInfo,
         StatSM);
      sprintf(sensorName, "disk/%d:%d/wio", major, minor);
      registerMonitor(sensorName, "integer", printDiskIO, printDiskIOInfo,
         StatSM);
      sprintf(sensorName, "disk/%d:%d/rblk", major, minor);
      registerMonitor(sensorName, "integer", printDiskIO, printDiskIOInfo,
         StatSM);
      sprintf(sensorName, "disk/%d:%d/wblk", major, minor);
      registerMonitor(sensorName, "integer", printDiskIO, printDiskIOInfo,
         StatSM);
   }

   return 0;
}

static void cleanupDiskList( void )
{
  DiskIOInfo* ptr = DiskIO;
  DiskIOInfo* last = 0;

  while ( ptr ) {
    if ( ptr->alive == 0 ) {
      DiskIOInfo* newPtr;
      char sensorName[ 128 ];

      /* Disk device has disappeared. We have to remove it from
       * the list and unregister the monitors. */
      sprintf( sensorName, "disk/%d:%d/total", ptr->major, ptr->minor );
      removeMonitor( sensorName );
      sprintf( sensorName, "disk/%d:%d/rio", ptr->major, ptr->minor );
      removeMonitor( sensorName );
      sprintf( sensorName, "disk/%d:%d/wio", ptr->major, ptr->minor );
      removeMonitor( sensorName );
      sprintf( sensorName, "disk/%d:%d/rblk", ptr->major, ptr->minor );
      removeMonitor( sensorName );
      sprintf( sensorName, "disk/%d:%d/wblk", ptr->major, ptr->minor );
      removeMonitor( sensorName );
      if ( last ) {
        last->next = ptr->next;
        newPtr = ptr->next;
      } else {
        DiskIO = ptr->next;
        newPtr = DiskIO;
        last = 0;
      }

      free ( ptr );
      ptr = newPtr;
    } else {
      ptr->alive = 0;
      last = ptr;
      ptr = ptr->next;
    }
  }
}

static void processStat( void )
{
  char format[ 32 ];
  char tagFormat[ 16 ];
  char buf[ 1024 ];
  char tag[ 32 ];
  char* statBufP = StatBuf;
  char* vmstatBufP = VmStatBuf;
  char* iostatBufP = IOStatBuf;

  sprintf( format, "%%%d[^\n]\n", (int)sizeof( buf ) - 1 );
  sprintf( tagFormat, "%%%ds", (int)sizeof( tag ) - 1 );

  while ( sscanf( statBufP, format, buf ) == 1 ) {
    buf[ sizeof( buf ) - 1 ] = '\0';
    statBufP += strlen( buf ) + 1;  /* move statBufP to next line */
    sscanf( buf, tagFormat, tag );

    if ( strcmp( "cpu", tag ) == 0 ) {
      /* Total CPU load */
      updateCPULoad( buf, &CPULoad );
    } else if ( strncmp( "cpu", tag, 3 ) == 0 ) {
      /* Load for each SMP CPU */
      int id;
      sscanf( tag + 3, "%d", &id );
      updateCPULoad( buf, &SMPLoad[ id ]  );
    } else if ( processDisk( tag, buf, "disk", 0 ) ) {
    } else if ( processDisk( tag, buf, "disk_rio", 1 ) ) {
    } else if ( processDisk( tag, buf, "disk_wio", 2 ) ) {
    } else if ( processDisk( tag, buf, "disk_rblk", 3 ) ) {
    } else if ( processDisk( tag, buf, "disk_wblk", 4 ) ) {
    } else if ( strcmp( "disk_io:", tag ) == 0 ) {
      processDiskIO( buf );
    } else if ( strcmp( "page", tag ) == 0 ) {
      unsigned long v1, v2;
      sscanf( buf + 5, "%lu %lu", &v1, &v2 );
      PageIn = v1 - OldPageIn;
      OldPageIn = v1;
      PageOut = v2 - OldPageOut;
      OldPageOut = v2;
    } else if ( strcmp( "intr", tag ) == 0 ) {
      unsigned int i = 0;
      char* p = buf + 5;

      for ( i = 0; i < NumOfInts; i++ ) {
        unsigned long val;

        sscanf( p, "%lu", &val );
        Intr[ i ] = val - OldIntr[ i ];
        OldIntr[ i ] = val;
        while ( *p && *p != ' ' )
          p++;
        while ( *p && *p == ' ' )
          p++;
      }
    } else if ( strcmp( "ctxt", tag ) == 0 ) {
      unsigned long val;

      sscanf( buf + 5, "%lu", &val );
      Ctxt = val - OldCtxt;
      OldCtxt = val;
    }
  }

  /* Read Linux 2.5.x /proc/vmstat */
  while ( sscanf( vmstatBufP, format, buf ) == 1 ) {
    buf[ sizeof( buf ) - 1 ] = '\0';
    vmstatBufP += strlen( buf ) + 1;  /* move vmstatBufP to next line */
    sscanf( buf, tagFormat, tag );

    if ( strcmp( "pgpgin", tag ) == 0 ) {
      unsigned long v1;
      sscanf( buf + 7, "%lu", &v1 );
      PageIn = v1 - OldPageIn;
      OldPageIn = v1;
    } else if ( strcmp( "pgpgout", tag ) == 0 ) {
      unsigned long v1;
      sscanf( buf + 7, "%lu", &v1 );
      PageOut = v1 - OldPageOut;
      OldPageOut = v1;
    }
  }

  /* Process values from /proc/diskstats (Linux >= 2.6.x) */
  while (sscanf(iostatBufP, format, buf) == 1)
  {
    buf[sizeof(buf) - 1] = '\0';
    iostatBufP += strlen(buf) + 1;  /* move IOstatBufP to next line */

    process26DiskIO(buf);
  }

  /* save exact time inverval between this and the last read of /proc/stat */
  timeInterval = currSampling.tv_sec - lastSampling.tv_sec +
                 ( currSampling.tv_usec - lastSampling.tv_usec ) / 1000000.0;
  lastSampling = currSampling;

  cleanupDiskList();

  Dirty = 0;
}

/*
================================ public part =================================
*/

void initStat( struct SensorModul* sm )
{
  /* The CPU load is calculated from the values in /proc/stat. The cpu
   * entry contains 4 counters. These counters count the number of ticks
   * the system has spend on user processes, system processes, nice
   * processes and idle time.
   *
   * SMP systems will have cpu1 to cpuN lines right after the cpu info. The
   * format is identical to cpu and reports the information for each cpu.
   * Linux kernels <= 2.0 do not provide this information!
   *
   * The /proc/stat file looks like this:
   *
   * cpu  1586 4 808 36274
   * disk 7797 0 0 0
   * disk_rio 6889 0 0 0
   * disk_wio 908 0 0 0
   * disk_rblk 13775 0 0 0
   * disk_wblk 1816 0 0 0
   * page 27575 1330
   * swap 1 0
   * intr 50444 38672 2557 0 0 0 0 2 0 2 0 0 3 1429 1 7778 0
   * ctxt 54155
   * btime 917379184
   * processes 347 
   *
   * Linux kernel >= 2.4.0 have one or more disk_io: lines instead of
   * the disk_* lines.
   *
   * Linux kernel >= 2.6.x(?) have disk I/O stats in /proc/diskstats
   * and no disk relevant lines are found in /proc/stat
   */

  char format[ 32 ];
  char tagFormat[ 16 ];
  char buf[ 1024 ];
  char tag[ 32 ];
  char* statBufP = StatBuf;
  char* vmstatBufP = VmStatBuf;
  char* iostatBufP = IOStatBuf;

  StatSM = sm;

  updateStat();

  sprintf( format, "%%%d[^\n]\n", (int)sizeof( buf ) - 1 );
  sprintf( tagFormat, "%%%ds", (int)sizeof( tag ) - 1 );

  while ( sscanf( statBufP, format, buf ) == 1 ) {
    buf[ sizeof( buf ) - 1 ] = '\0';
    statBufP += strlen( buf ) + 1;  /* move statBufP to next line */
    sscanf( buf, tagFormat, tag );

    if ( strcmp( "cpu", tag ) == 0 ) {
      /* Total CPU load */
      registerMonitor( "cpu/user", "integer", printCPUUser, printCPUUserInfo, StatSM );
      registerMonitor( "cpu/nice", "integer", printCPUNice, printCPUNiceInfo, StatSM );
      registerMonitor( "cpu/sys", "integer", printCPUSys, printCPUSysInfo, StatSM );
      registerMonitor( "cpu/idle", "integer", printCPUIdle, printCPUIdleInfo, StatSM );
    } else if ( strncmp( "cpu", tag, 3 ) == 0 ) {
      char cmdName[ 24 ];
      /* Load for each SMP CPU */
      int id;

      sscanf( tag + 3, "%d", &id );
      CPUCount++;
      sprintf( cmdName, "cpu%d/user", id );
      registerMonitor( cmdName, "integer", printCPUxUser, printCPUxUserInfo, StatSM );
      sprintf( cmdName, "cpu%d/nice", id );
      registerMonitor( cmdName, "integer", printCPUxNice, printCPUxNiceInfo, StatSM );
      sprintf( cmdName, "cpu%d/sys", id );
      registerMonitor( cmdName, "integer", printCPUxSys, printCPUxSysInfo, StatSM );
      sprintf( cmdName, "cpu%d/idle", id );
      registerMonitor( cmdName, "integer", printCPUxIdle, printCPUxIdleInfo, StatSM );
    } else if ( strcmp( "disk", tag ) == 0 ) {
      unsigned long val;
      char* b = buf + 5;

      /* Count the number of registered disks */
      for ( DiskCount = 0; *b && sscanf( b, "%lu", &val ) == 1; DiskCount++ ) {
        while ( *b && isblank( *b++ ) );
        while ( *b && isdigit( *b++ ) );
      }

      if ( DiskCount > 0 )
        DiskLoad = (DiskLoadInfo*)malloc( sizeof( DiskLoadInfo ) * DiskCount );
        initStatDisk( tag, buf, "disk", "disk", 0, printDiskTotal, printDiskTotalInfo );
    } else if ( initStatDisk( tag, buf, "disk_rio", "rio", 1, printDiskRIO,
                              printDiskRIOInfo ) );
    else if ( initStatDisk( tag, buf, "disk_wio", "wio", 2, printDiskWIO,
                            printDiskWIOInfo ) );
    else if ( initStatDisk( tag, buf, "disk_rblk", "rblk", 3, printDiskRBlk,
                            printDiskRBlkInfo ) );
    else if ( initStatDisk( tag, buf, "disk_wblk", "wblk", 4, printDiskWBlk,
                            printDiskWBlkInfo ) );
    else if ( strcmp( "disk_io:", tag ) == 0 )
      processDiskIO( buf );
    else if ( strcmp( "page", tag ) == 0 ) {
      sscanf( buf + 5, "%lu %lu", &OldPageIn, &OldPageOut );
      registerMonitor( "cpu/pageIn", "integer", printPageIn,
                       printPageInInfo, StatSM );
      registerMonitor( "cpu/pageOut", "integer", printPageOut,
                       printPageOutInfo, StatSM );
    } else if ( strcmp( "intr", tag ) == 0 ) {
      unsigned int i;
      char cmdName[ 32 ];
      char* p = buf + 5;

      /* Count the number of listed values in the intr line. */
      NumOfInts = 0;
      while ( *p )
        if ( *p++ == ' ' )
          NumOfInts++;

      /* It looks like anything above 24 is always 0. So let's just
       * ignore this for the time being. */
      if ( NumOfInts > 25 )
        NumOfInts = 25;
      OldIntr = (unsigned long*)malloc( NumOfInts * sizeof( unsigned long ) );
      Intr = (unsigned long*)malloc( NumOfInts * sizeof( unsigned long ) );
      i = 0;
      p = buf + 5;
      for ( i = 0; p && i < NumOfInts; i++ ) {
        sscanf( p, "%lu", &OldIntr[ i ] );
        while ( *p && *p != ' ' )
          p++;
        while ( *p && *p == ' ' )
          p++;
        sprintf( cmdName, "cpu/interrupts/int%02d", i );
        registerMonitor( cmdName, "integer", printInterruptx,
                         printInterruptxInfo, StatSM );
      }
    } else if ( strcmp( "ctxt", tag ) == 0 ) {
      sscanf( buf + 5, "%lu", &OldCtxt );
      registerMonitor( "cpu/context", "integer", printCtxt,
                       printCtxtInfo, StatSM );
    }
  }

  while ( sscanf( vmstatBufP, format, buf ) == 1 ) {
    buf[ sizeof( buf ) - 1 ] = '\0';
    vmstatBufP += strlen( buf ) + 1;  /* move vmstatBufP to next line */
    sscanf( buf, tagFormat, tag );

    if ( strcmp( "pgpgin", tag ) == 0 ) {
      sscanf( buf + 7, "%lu", &OldPageIn );
      registerMonitor( "cpu/pageIn", "integer", printPageIn,
                       printPageInInfo, StatSM );
    } else if ( strcmp( "pgpgout", tag ) == 0 ) {
      sscanf( buf + 7, "%lu", &OldPageOut );
      registerMonitor( "cpu/pageOut", "integer", printPageOut,
                       printPageOutInfo, StatSM );
    }
  }

   /* Process values from /proc/diskstats (Linux >= 2.6.x) */
   while (sscanf(iostatBufP, format, buf) == 1)
   {
      buf[sizeof(buf) - 1] = '\0';
      iostatBufP += strlen(buf) + 1;  /* move IOstatBufP to next line */

      process26DiskIO(buf);
   }

  if ( CPUCount > 0 )
    SMPLoad = (CPULoadInfo*)malloc( sizeof( CPULoadInfo ) * CPUCount );

  /* Call processStat to eliminate initial peek values. */
  processStat();
}

void exitStat( void )
{
  free( DiskLoad );
  DiskLoad = 0;

  free( SMPLoad );
  SMPLoad = 0;

  free( OldIntr );
  OldIntr = 0;

  free( Intr );
  Intr = 0;
}

int updateStat( void )
{
  size_t n;
  int fd;

  if ( ( fd = open( "/proc/stat", O_RDONLY ) ) < 0 ) {
    print_error( "Cannot open file \'/proc/stat\'!\n"
                 "The kernel needs to be compiled with support\n"
                 "for /proc filesystem enabled!\n" );
    return -1;
  }

  if ( ( n = read( fd, StatBuf, STATBUFSIZE - 1 ) ) == STATBUFSIZE - 1 ) {
    log_error( "Internal buffer too small to read \'/proc/stat\'" );

    close( fd );
    return -1;
  }

  gettimeofday( &currSampling, 0 );
  close( fd );
  StatBuf[ n ] = '\0';
  Dirty = 1;

  VmStatBuf[ 0 ] = '\0';
  if ( ( fd = open( "/proc/vmstat", O_RDONLY ) ) < 0 )
    return 0; /* failure is okay, only exists for Linux >= 2.5.x */

  if ( ( n = read( fd, VmStatBuf, STATBUFSIZE - 1 ) ) == STATBUFSIZE - 1 ) {
    log_error( "Internal buffer too small to read \'/proc/vmstat\'" );

    close( fd );
    return -1;
  }

  close( fd );
  VmStatBuf[ n ] = '\0';

  /* Linux >= 2.6.x has disk I/O stats in /proc/diskstats */
  IOStatBuf[ 0 ] = '\0';
  if ( ( fd = open( "/proc/diskstats", O_RDONLY ) ) < 0 )
    return 0; /* failure is okay, only exists for Linux >= 2.6.x */

  if ( ( n = read( fd, IOStatBuf, STATBUFSIZE - 1 ) ) == STATBUFSIZE - 1 ) {
    log_error( "Internal buffer too small to read \'/proc/diskstats\'" );

    close( fd );
    return -1;
  }

  close( fd );
  IOStatBuf[ n ] = '\0';

  return 0;
}

void printCPUUser( const char* cmd )
{
  (void)cmd;

  if ( Dirty )
    processStat();

  fprintf( CurrentClient, "%d\n", CPULoad.userLoad );
}

void printCPUUserInfo( const char* cmd )
{
  (void)cmd;
  fprintf( CurrentClient, "CPU User Load\t0\t100\t%%\n" );
}

void printCPUNice( const char* cmd )
{
  (void)cmd;

  if ( Dirty )
    processStat();

  fprintf( CurrentClient, "%d\n", CPULoad.niceLoad );
}

void printCPUNiceInfo( const char* cmd )
{
  (void)cmd;
  fprintf( CurrentClient, "CPU Nice Load\t0\t100\t%%\n" );
}

void printCPUSys( const char* cmd )
{
  (void)cmd;

  if ( Dirty )
    processStat();

  fprintf( CurrentClient, "%d\n", CPULoad.sysLoad );
}

void printCPUSysInfo( const char* cmd )
{
  (void)cmd;
  fprintf( CurrentClient, "CPU System Load\t0\t100\t%%\n" );
}

void printCPUIdle( const char* cmd )
{
  (void)cmd;

  if ( Dirty )
    processStat();

  fprintf( CurrentClient, "%d\n", CPULoad.idleLoad );
}

void printCPUIdleInfo( const char* cmd )
{
  (void)cmd;
  fprintf( CurrentClient, "CPU Idle Load\t0\t100\t%%\n" );
}

void printCPUxUser( const char* cmd )
{
  int id;

  if ( Dirty )
    processStat();

  sscanf( cmd + 3, "%d", &id );
  fprintf( CurrentClient, "%d\n", SMPLoad[ id ].userLoad );
}

void printCPUxUserInfo( const char* cmd )
{
  int id;

  sscanf( cmd + 3, "%d", &id );
  fprintf( CurrentClient, "CPU%d User Load\t0\t100\t%%\n", id );
}

void printCPUxNice( const char* cmd )
{
  int id;

  if ( Dirty )
    processStat();

  sscanf( cmd + 3, "%d", &id );
  fprintf( CurrentClient, "%d\n", SMPLoad[ id ].niceLoad );
}

void printCPUxNiceInfo( const char* cmd )
{
  int id;

  sscanf( cmd + 3, "%d", &id );
  fprintf( CurrentClient, "CPU%d Nice Load\t0\t100\t%%\n", id );
}

void printCPUxSys( const char* cmd )
{
  int id;

  if ( Dirty )
    processStat();

  sscanf( cmd + 3, "%d", &id );
  fprintf( CurrentClient, "%d\n", SMPLoad[ id ].sysLoad );
}

void printCPUxSysInfo( const char* cmd )
{
  int id;

  sscanf( cmd + 3, "%d", &id );
  fprintf( CurrentClient, "CPU%d System Load\t0\t100\t%%\n", id );
}

void printCPUxIdle( const char* cmd )
{
  int id;

  if ( Dirty )
    processStat();

  sscanf( cmd + 3, "%d", &id );
  fprintf( CurrentClient, "%d\n", SMPLoad[ id ].idleLoad );
}

void printCPUxIdleInfo( const char* cmd )
{
  int id;

  sscanf( cmd + 3, "%d", &id );
  fprintf( CurrentClient, "CPU%d Idle Load\t0\t100\t%%\n", id );
}

void printDiskTotal( const char* cmd )
{
  int id;

  if ( Dirty )
    processStat();

  sscanf( cmd + 9, "%d", &id );
  fprintf( CurrentClient, "%lu\n", (unsigned long)( DiskLoad[ id ].s[ 0 ].delta
                                                    / timeInterval ) );
}

void printDiskTotalInfo( const char* cmd )
{
  int id;

  sscanf( cmd + 9, "%d", &id );
  fprintf( CurrentClient, "Disk%d Total Load\t0\t0\tkBytes/s\n", id );
}

void printDiskRIO( const char* cmd )
{
  int id;

  if ( Dirty )
    processStat();

  sscanf( cmd + 9, "%d", &id );
  fprintf( CurrentClient, "%lu\n", (unsigned long)( DiskLoad[ id ].s[ 1 ].delta
                                                    / timeInterval ) );
}

void printDiskRIOInfo( const char* cmd )
{
  int id;

  sscanf( cmd + 9, "%d", &id );
  fprintf( CurrentClient, "Disk%d Read\t0\t0\tkBytes/s\n", id );
}

void printDiskWIO( const char* cmd )
{
  int id;

  if ( Dirty )
    processStat();

  sscanf( cmd + 9, "%d", &id );
  fprintf( CurrentClient, "%lu\n", (unsigned long)( DiskLoad[ id ].s[ 2 ].delta
                                                    / timeInterval ) );
}

void printDiskWIOInfo( const char* cmd )
{
  int id;

  sscanf( cmd + 9, "%d", &id );
  fprintf( CurrentClient, "Disk%d Write\t0\t0\tkBytes/s\n", id );
}

void printDiskRBlk( const char* cmd )
{
  int id;

  if ( Dirty )
    processStat();

  sscanf( cmd + 9, "%d", &id );
  /* a block is 512 bytes or 1/2 kBytes */
  fprintf( CurrentClient, "%lu\n", (unsigned long)( DiskLoad[ id ].s[ 3 ].delta
                                                    / timeInterval * 2 ) );
}

void printDiskRBlkInfo( const char* cmd )
{
  int id;

  sscanf( cmd + 9, "%d", &id );
  fprintf( CurrentClient, "Disk%d Read Data\t0\t0\tkBytes/s\n", id );
}

void printDiskWBlk( const char* cmd )
{
  int id;

  if ( Dirty )
    processStat();

  sscanf( cmd + 9, "%d", &id );
  /* a block is 512 bytes or 1/2 kBytes */
  fprintf( CurrentClient, "%lu\n", (unsigned long)( DiskLoad[ id ].s[ 4 ].delta
                                                    / timeInterval * 2 ) );
}

void printDiskWBlkInfo( const char* cmd )
{
  int id;

  sscanf( cmd + 9, "%d", &id );
  fprintf( CurrentClient, "Disk%d Write Data\t0\t0\tkBytes/s\n", id );
}

void printPageIn( const char* cmd )
{
  (void)cmd;

  if ( Dirty )
    processStat();

  fprintf( CurrentClient, "%lu\n", (unsigned long)( PageIn / timeInterval ) );
}

void printPageInInfo( const char* cmd )
{
  (void)cmd;
  fprintf( CurrentClient, "Paged in Pages\t0\t0\t1/s\n" );
}

void printPageOut( const char* cmd )
{
  (void)cmd;

  if ( Dirty )
    processStat();

  fprintf( CurrentClient, "%lu\n", (unsigned long)( PageOut / timeInterval ) );
}

void printPageOutInfo( const char* cmd )
{
  (void)cmd;
  fprintf( CurrentClient, "Paged out Pages\t0\t0\t1/s\n" );
}

void printInterruptx( const char* cmd )
{
  int id;

  if ( Dirty )
    processStat();

  sscanf( cmd + strlen( "cpu/interrupts/int" ), "%d", &id );
  fprintf( CurrentClient, "%lu\n", (unsigned long)( Intr[ id ] / timeInterval ) );
}

void printInterruptxInfo( const char* cmd )
{
  int id;

  sscanf( cmd + strlen( "cpu/interrupt/int" ), "%d", &id );
  fprintf( CurrentClient, "Interrupt %d\t0\t0\t1/s\n", id );
}

void printCtxt( const char* cmd )
{
  (void)cmd;

  if ( Dirty )
    processStat();

  fprintf( CurrentClient, "%lu\n", (unsigned long)( Ctxt / timeInterval ) );
}

void printCtxtInfo( const char* cmd )
{
  (void)cmd;
  fprintf( CurrentClient, "Context switches\t0\t0\t1/s\n" );
}

void printDiskIO( const char* cmd )
{
  int major, minor;
  char name[ 17 ];
  DiskIOInfo* ptr;

  sscanf( cmd, "disk/%d:%d/%16s", &major, &minor, name );

  if ( Dirty )
    processStat();

  ptr = DiskIO;
  while ( ptr && ( ptr->major != major || ptr->minor != minor ) )
    ptr = ptr->next;

  if ( !ptr ) {
    print_error( "RECONFIGURE" );
    fprintf( CurrentClient, "0\n" );

    log_error( "Disk device disappeared" );
    return;
  }

  if ( strcmp( name, "total" ) == 0 )
    fprintf( CurrentClient, "%lu\n", (unsigned long)( ptr->total.delta
                                                      / timeInterval ) );
  else if ( strcmp( name, "rio" ) == 0 )
    fprintf( CurrentClient, "%lu\n", (unsigned long)( ptr->rio.delta
                                                      / timeInterval ) );
  else if ( strcmp( name, "wio" ) == 0 )
    fprintf( CurrentClient, "%lu\n", (unsigned long)( ptr->wio.delta
                                                      / timeInterval ) );
  else if ( strcmp( name, "rblk" ) == 0 )
    fprintf( CurrentClient, "%lu\n", (unsigned long)( ptr->rblk.delta
                                                      / ( timeInterval * 2 ) ) );
  else if ( strcmp( name, "wblk" ) == 0 )
    fprintf( CurrentClient, "%lu\n", (unsigned long)( ptr->wblk.delta
                                                      / ( timeInterval * 2 ) ) );
  else {
    fprintf( CurrentClient, "0\n" );
    log_error( "Unknown disk device property \'%s\'", name );
  }
}

void printDiskIOInfo( const char* cmd )
{
  int major, minor;
  char name[ 17 ];
  DiskIOInfo* ptr = DiskIO;

  sscanf( cmd, "disk/%d:%d/%16s", &major, &minor, name );

  while ( ptr && ( ptr->major != major || ptr->minor != minor ) )
    ptr = ptr->next;

  if ( !ptr ) {
    /* Disk device has disappeared. Print a dummy answer. */
    fprintf( CurrentClient, "Dummy\t0\t0\t\n" );
    return;
  }

  /* remove trailing '?' */
  name[ strlen( name ) - 1 ] = '\0';

  if ( strcmp( name, "total" ) == 0 )
    fprintf( CurrentClient, "Total accesses device %d, %d\t0\t0\t1/s\n",
             major, minor );
  else if ( strcmp( name, "rio" ) == 0 )
    fprintf( CurrentClient, "Read data device %d, %d\t0\t0\t1/s\n",
             major, minor );
  else if ( strcmp( name, "wio" ) == 0 )
    fprintf( CurrentClient, "Write data device %d, %d\t0\t0\t1/s\n",
             major, minor );
  else if ( strcmp( name, "rblk" ) == 0 )
    fprintf( CurrentClient, "Read accesses device %d, %d\t0\t0\tkBytes/s\n",
             major, minor );
  else if ( strcmp( name, "wblk" ) == 0 )
    fprintf( CurrentClient, "Write accesses device %d, %d\t0\t0\tkBytes/s\n",
             major, minor );
  else {
    fprintf( CurrentClient, "Dummy\t0\t0\t\n" );
    log_error( "Request for unknown device property \'%s\'",	name );
  }
}