preparatory patch for -Wwrite-strings #7: sed
[oweals/busybox.git] / miscutils / nmeter.c
1 /*
2 ** Licensed under the GPL v2, see the file LICENSE in this tarball
3 **
4 ** Based on nanotop.c from floppyfw project
5 **
6 ** Contact me: vda.linux@googlemail.com */
7
8 //TODO:
9 // simplify code
10 // /proc/locks
11 // /proc/stat:
12 // disk_io: (3,0):(22272,17897,410702,4375,54750)
13 // btime 1059401962
14
15 #include "busybox.h"
16 #include <time.h>
17
18 typedef unsigned long long ullong;
19
20 enum { proc_file_size = 4096 };
21
22 typedef struct proc_file {
23         const char *name;
24         int gen;
25         char *file;
26 } proc_file;
27
28 static proc_file proc_stat = { "/proc/stat", -1 };
29 static proc_file proc_loadavg = { "/proc/loadavg", -1 };
30 static proc_file proc_net_dev = { "/proc/net/dev", -1 };
31 static proc_file proc_meminfo = { "/proc/meminfo", -1 };
32 static proc_file proc_diskstats = { "/proc/diskstats", -1 };
33 // Sample #
34 static int gen = -1;
35 // Linux 2.6? (otherwise assumes 2.4)
36 static int is26 = 0;
37 static struct timeval tv;
38 static int delta = 1000000;
39 static int deltanz = 1000000;
40 static int need_seconds = 0;
41 static const char *final_str = "\n";
42
43 // We depend on this being a char[], not char* - we take sizeof() of it
44 #define outbuf bb_common_bufsiz1
45 static char *cur_outbuf = outbuf;
46
47
48 static inline void reset_outbuf(void)
49 {
50         cur_outbuf = outbuf;
51 }
52
53 static inline int outbuf_count(void)
54 {
55         return cur_outbuf - outbuf;
56 }
57
58 static void print_outbuf(void)
59 {
60         int sz = cur_outbuf - outbuf;
61         if (sz > 0) {
62                 write(1, outbuf, sz);
63                 cur_outbuf = outbuf;
64         }
65 }
66
67 static void put(const char *s)
68 {
69         int sz = strlen(s);
70         if (sz > outbuf + sizeof(outbuf) - cur_outbuf)
71                 sz = outbuf + sizeof(outbuf) - cur_outbuf;
72         memcpy(cur_outbuf, s, sz);
73         cur_outbuf += sz;
74 }
75
76 static void put_c(char c)
77 {
78         if (cur_outbuf < outbuf + sizeof(outbuf))
79                 *cur_outbuf++ = c;
80 }
81
82 static void put_question_marks(int count)
83 {
84         while (count--)
85                 put_c('?');
86 }
87
88 static int readfile_z(char *buf, int sz, const char* fname)
89 {
90         sz = open_read_close(fname, buf, sz-1);
91         if (sz < 0) {
92                 buf[0] = '\0';
93                 return 1;
94         }
95         buf[sz] = '\0';
96         return 0;
97 }
98
99 static const char* get_file(proc_file *pf)
100 {
101         if (pf->gen != gen) {
102                 pf->gen = gen;
103                 // We allocate proc_file_size bytes. This wastes memory,
104                 // but allows us to allocate only once (at first sample)
105                 // per proc file, and reuse buffer for each sample
106                 if (!pf->file)
107                         pf->file = xmalloc(proc_file_size);
108                 readfile_z(pf->file, proc_file_size, pf->name);
109         }
110         return pf->file;
111 }
112
113 static inline ullong read_after_slash(const char *p)
114 {
115         p = strchr(p, '/');
116         if (!p) return 0;
117         return strtoull(p+1, NULL, 10);
118 }
119
120 enum conv_type { conv_decimal, conv_slash };
121
122 // Reads decimal values from line. Values start after key, for example:
123 // "cpu  649369 0 341297 4336769..." - key is "cpu" here.
124 // Values are stored in vec[]. arg_ptr has list of positions
125 // we are interested in: for example: 1,2,5 - we want 1st, 2nd and 5th value.
126 static int vrdval(const char* p, const char* key,
127         enum conv_type conv, ullong *vec, va_list arg_ptr)
128 {
129         int indexline;
130         int indexnext;
131
132         p = strstr(p, key);
133         if (!p) return 1;
134
135         p += strlen(key);
136         indexline = 1;
137         indexnext = va_arg(arg_ptr, int);
138         while (1) {
139                 while (*p == ' ' || *p == '\t') p++;
140                 if (*p == '\n' || *p == '\0') break;
141
142                 if (indexline == indexnext) { // read this value
143                         *vec++ = conv==conv_decimal ?
144                                 strtoull(p, NULL, 10) :
145                                 read_after_slash(p);
146                         indexnext = va_arg(arg_ptr, int);
147                 }
148                 while (*p > ' ') p++; // skip over value
149                 indexline++;
150         }
151         return 0;
152 }
153
154 // Parses files with lines like "cpu0 21727 0 15718 1813856 9461 10485 0 0":
155 // rdval(file_contents, "string_to_find", result_vector, value#, value#...)
156 // value# start with 1
157 static int rdval(const char* p, const char* key, ullong *vec, ...)
158 {
159         va_list arg_ptr;
160         int result;
161
162         va_start(arg_ptr, vec);
163         result = vrdval(p, key, conv_decimal, vec, arg_ptr);
164         va_end(arg_ptr);
165
166         return result;
167 }
168
169 // Parses files with lines like "... ... ... 3/148 ...."
170 static int rdval_loadavg(const char* p, ullong *vec, ...)
171 {
172         va_list arg_ptr;
173         int result;
174
175         va_start(arg_ptr, vec);
176         result = vrdval(p, "", conv_slash, vec, arg_ptr);
177         va_end(arg_ptr);
178
179         return result;
180 }
181
182 // Parses /proc/diskstats
183 //   1  2 3   4  5        6(rd)  7      8     9     10(wr) 11     12 13     14
184 //   3  0 hda 51292 14441 841783 926052 25717 79650 843256 3029804 0 148459 3956933
185 //   3  1 hda1 0 0 0 0 <- ignore if only 4 fields
186 static int rdval_diskstats(const char* p, ullong *vec)
187 {
188         ullong rd = 0; // to avoid "warning: 'rd' might be used uninitialized"
189         int indexline = 0;
190         vec[0] = 0;
191         vec[1] = 0;
192         while (1) {
193                 indexline++;
194                 while (*p == ' ' || *p == '\t') p++;
195                 if (*p == '\0') break;
196                 if (*p == '\n') {
197                         indexline = 0;
198                         p++;
199                         continue;
200                 }
201                 if (indexline == 6) {
202                         rd = strtoull(p, NULL, 10);
203                 } else if (indexline == 10) {
204                         vec[0] += rd;  // TODO: *sectorsize (don't know how to find out sectorsize)
205                         vec[1] += strtoull(p, NULL, 10);
206                         while (*p != '\n' && *p != '\0') p++;
207                         continue;
208                 }
209                 while (*p > ' ') p++; // skip over value
210         }
211         return 0;
212 }
213
214 static void scale(ullong ul)
215 {
216         char buf[5];
217         smart_ulltoa5(ul, buf);
218         put(buf);
219 }
220
221
222 #define S_STAT(a) \
223 typedef struct a { \
224         struct s_stat *next; \
225         void (*collect)(struct a *s); \
226         const char *label;
227 #define S_STAT_END(a) } a;
228
229 S_STAT(s_stat)
230 S_STAT_END(s_stat)
231
232 static void collect_literal(s_stat *s)
233 {
234 }
235
236 static s_stat* init_literal(void)
237 {
238         s_stat *s = xmalloc(sizeof(s_stat));
239         s->collect = collect_literal;
240         return (s_stat*)s;
241 }
242
243 static s_stat* init_delay(const char *param)
244 {
245         delta = strtol(param, NULL, 0)*1000;
246         deltanz = delta > 0 ? delta : 1;
247         need_seconds = (1000000%deltanz) != 0;
248         return (s_stat*)0;
249 }
250
251 static s_stat* init_cr(const char *param)
252 {
253         final_str = "\r";
254         return (s_stat*)0;
255 }
256
257
258 //     user nice system idle  iowait irq  softirq (last 3 only in 2.6)
259 //cpu  649369 0 341297 4336769 11640 7122 1183
260 //cpuN 649369 0 341297 4336769 11640 7122 1183
261 enum { CPU_FIELDCNT = 7 };
262 S_STAT(cpu_stat)
263         ullong old[CPU_FIELDCNT];
264         int bar_sz;
265         char *bar;
266 S_STAT_END(cpu_stat)
267
268
269 static void collect_cpu(cpu_stat *s)
270 {
271         ullong data[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
272         unsigned frac[CPU_FIELDCNT] = { 0, 0, 0, 0, 0, 0, 0 };
273         ullong all = 0;
274         int norm_all = 0;
275         int bar_sz = s->bar_sz;
276         char *bar = s->bar;
277         int i;
278
279         if (rdval(get_file(&proc_stat), "cpu ", data, 1, 2, 3, 4, 5, 6, 7)) {
280                 put_question_marks(bar_sz);
281                 return;
282         }
283
284         for (i=0; i<CPU_FIELDCNT; i++) {
285                 ullong old = s->old[i];
286                 if (data[i] < old) old = data[i];               //sanitize
287                 s->old[i] = data[i];
288                 all += (data[i] -= old);
289         }
290
291         if (all) {
292                 for (i=0; i<CPU_FIELDCNT; i++) {
293                         ullong t = bar_sz * data[i];
294                         norm_all += data[i] = t / all;
295                         frac[i] = t % all;
296                 }
297
298                 while (norm_all < bar_sz) {
299                         unsigned max = frac[0];
300                         int pos = 0;
301                         for (i=1; i<CPU_FIELDCNT; i++) {
302                                 if (frac[i] > max) max = frac[i], pos = i;
303                         }
304                         frac[pos] = 0;  //avoid bumping up same value twice
305                         data[pos]++;
306                         norm_all++;
307                 }
308
309                 memset(bar, '.', bar_sz);
310                 memset(bar, 'S', data[2]); bar += data[2]; //sys
311                 memset(bar, 'U', data[0]); bar += data[0]; //usr
312                 memset(bar, 'N', data[1]); bar += data[1]; //nice
313                 memset(bar, 'D', data[4]); bar += data[4]; //iowait
314                 memset(bar, 'I', data[5]); bar += data[5]; //irq
315                 memset(bar, 'i', data[6]); bar += data[6]; //softirq
316         } else {
317                 memset(bar, '?', bar_sz);
318         }
319         put(s->bar);
320 }
321
322
323 static s_stat* init_cpu(const char *param)
324 {
325         int sz;
326         cpu_stat *s = xmalloc(sizeof(cpu_stat));
327         s->collect = collect_cpu;
328         sz = strtol(param, NULL, 0);
329         if (sz < 10) sz = 10;
330         if (sz > 1000) sz = 1000;
331         s->bar = xmalloc(sz+1);
332         s->bar[sz] = '\0';
333         s->bar_sz = sz;
334         return (s_stat*)s;
335 }
336
337
338 S_STAT(int_stat)
339         ullong old;
340         int no;
341 S_STAT_END(int_stat)
342
343 static void collect_int(int_stat *s)
344 {
345         ullong data[1];
346         ullong old;
347
348         if (rdval(get_file(&proc_stat), "intr", data, s->no)) {
349                 put_question_marks(4);
350                 return;
351         }
352
353         old = s->old;
354         if (data[0] < old) old = data[0];               //sanitize
355         s->old = data[0];
356         scale(data[0] - old);
357 }
358
359 static s_stat* init_int(const char *param)
360 {
361         int_stat *s = xmalloc(sizeof(int_stat));
362         s->collect = collect_int;
363         if (param[0]=='\0') {
364                 s->no = 1;
365         } else {
366                 int n = strtoul(param, NULL, 0);
367                 s->no = n+2;
368         }
369         return (s_stat*)s;
370 }
371
372
373 S_STAT(ctx_stat)
374         ullong old;
375 S_STAT_END(ctx_stat)
376
377 static void collect_ctx(ctx_stat *s)
378 {
379         ullong data[1];
380         ullong old;
381
382         if (rdval(get_file(&proc_stat), "ctxt", data, 1)) {
383                 put_question_marks(4);
384                 return;
385         }
386
387         old = s->old;
388         if (data[0] < old) old = data[0];               //sanitize
389         s->old = data[0];
390         scale(data[0] - old);
391 }
392
393 static s_stat* init_ctx(const char *param)
394 {
395         ctx_stat *s = xmalloc(sizeof(ctx_stat));
396         s->collect = collect_ctx;
397         return (s_stat*)s;
398 }
399
400
401 S_STAT(blk_stat)
402         const char* lookfor;
403         ullong old[2];
404 S_STAT_END(blk_stat)
405
406 static void collect_blk(blk_stat *s)
407 {
408         ullong data[2];
409         int i;
410
411         if (is26) {
412                 i = rdval_diskstats(get_file(&proc_diskstats), data);
413         } else {
414                 i = rdval(get_file(&proc_stat), s->lookfor, data, 1, 2);
415                 // Linux 2.4 reports bio in Kbytes, convert to sectors:
416                 data[0] *= 2;
417                 data[1] *= 2;
418         }
419         if (i) {
420                 put_question_marks(9);
421                 return;
422         }
423
424         for (i=0; i<2; i++) {
425                 ullong old = s->old[i];
426                 if (data[i] < old) old = data[i];               //sanitize
427                 s->old[i] = data[i];
428                 data[i] -= old;
429         }
430         scale(data[0]*512); // TODO: *sectorsize
431         put_c(' ');
432         scale(data[1]*512);
433 }
434
435 static s_stat* init_blk(const char *param)
436 {
437         blk_stat *s = xmalloc(sizeof(blk_stat));
438         s->collect = collect_blk;
439         s->lookfor = "page";
440         return (s_stat*)s;
441 }
442
443
444 S_STAT(fork_stat)
445         ullong old;
446 S_STAT_END(fork_stat)
447
448 static void collect_thread_nr(fork_stat *s)
449 {
450         ullong data[1];
451
452         if (rdval_loadavg(get_file(&proc_loadavg), data, 4)) {
453                 put_question_marks(4);
454                 return;
455         }
456         scale(data[0]);
457 }
458
459 static void collect_fork(fork_stat *s)
460 {
461         ullong data[1];
462         ullong old;
463
464         if (rdval(get_file(&proc_stat), "processes", data, 1)) {
465                 put_question_marks(4);
466                 return;
467         }
468
469         old = s->old;
470         if (data[0] < old) old = data[0];       //sanitize
471         s->old = data[0];
472         scale(data[0] - old);
473 }
474
475 static s_stat* init_fork(const char *param)
476 {
477         fork_stat *s = xmalloc(sizeof(fork_stat));
478         if (*param == 'n') {
479                 s->collect = collect_thread_nr;
480         } else {
481                 s->collect = collect_fork;
482         }
483         return (s_stat*)s;
484 }
485
486
487 S_STAT(if_stat)
488         ullong old[4];
489         const char *device;
490         char *device_colon;
491 S_STAT_END(if_stat)
492
493 static void collect_if(if_stat *s)
494 {
495         ullong data[4];
496         int i;
497
498         if (rdval(get_file(&proc_net_dev), s->device_colon, data, 1, 3, 9, 11)) {
499                 put_question_marks(10);
500                 return;
501         }
502
503         for (i=0; i<4; i++) {
504                 ullong old = s->old[i];
505                 if (data[i] < old) old = data[i];               //sanitize
506                 s->old[i] = data[i];
507                 data[i] -= old;
508         }
509         put_c(data[1] ? '*' : ' ');
510         scale(data[0]);
511         put_c(data[3] ? '*' : ' ');
512         scale(data[2]);
513 }
514
515 static s_stat* init_if(const char *device)
516 {
517         if_stat *s = xmalloc(sizeof(if_stat));
518
519         if (!device || !device[0])
520                 bb_show_usage();
521         s->collect = collect_if;
522
523         s->device = device;
524         s->device_colon = xmalloc(strlen(device)+2);
525         strcpy(s->device_colon, device);
526         strcat(s->device_colon, ":");
527         return (s_stat*)s;
528 }
529
530
531 S_STAT(mem_stat)
532         char opt;
533 S_STAT_END(mem_stat)
534
535 // "Memory" value should not include any caches.
536 // IOW: neither "ls -laR /" nor heavy read/write activity
537 //      should affect it. We'd like to also include any
538 //      long-term allocated kernel-side mem, but it is hard
539 //      to figure out. For now, bufs, cached & slab are
540 //      counted as "free" memory
541 //2.6.16:
542 //MemTotal:       773280 kB
543 //MemFree:         25912 kB - genuinely free
544 //Buffers:        320672 kB - cache
545 //Cached:         146396 kB - cache
546 //SwapCached:          0 kB
547 //Active:         183064 kB
548 //Inactive:       356892 kB
549 //HighTotal:           0 kB
550 //HighFree:            0 kB
551 //LowTotal:       773280 kB
552 //LowFree:         25912 kB
553 //SwapTotal:      131064 kB
554 //SwapFree:       131064 kB
555 //Dirty:              48 kB
556 //Writeback:           0 kB
557 //Mapped:          96620 kB
558 //Slab:           200668 kB - takes 7 Mb on my box fresh after boot,
559 //                            but includes dentries and inodes
560 //                            (== can take arbitrary amount of mem)
561 //CommitLimit:    517704 kB
562 //Committed_AS:   236776 kB
563 //PageTables:       1248 kB
564 //VmallocTotal:   516052 kB
565 //VmallocUsed:      3852 kB
566 //VmallocChunk:   512096 kB
567 //HugePages_Total:     0
568 //HugePages_Free:      0
569 //Hugepagesize:     4096 kB
570 static void collect_mem(mem_stat *s)
571 {
572         ullong m_total = 0;
573         ullong m_free = 0;
574         ullong m_bufs = 0;
575         ullong m_cached = 0;
576         ullong m_slab = 0;
577
578         if (rdval(get_file(&proc_meminfo), "MemTotal:", &m_total, 1)) {
579                 put_question_marks(4);
580                 return;
581         }
582         if (s->opt == 'f') {
583                 scale(m_total << 10);
584                 return;
585         }
586
587         if (rdval(proc_meminfo.file, "MemFree:", &m_free  , 1)
588          || rdval(proc_meminfo.file, "Buffers:", &m_bufs  , 1)
589          || rdval(proc_meminfo.file, "Cached:",  &m_cached, 1)
590          || rdval(proc_meminfo.file, "Slab:",    &m_slab  , 1)
591         ) {
592                 put_question_marks(4);
593                 return;
594         }
595
596         m_free += m_bufs + m_cached + m_slab;
597         switch (s->opt) {
598         case 'f':
599                 scale(m_free << 10); break;
600         default:
601                 scale((m_total - m_free) << 10); break;
602         }
603 }
604
605 static s_stat* init_mem(const char *param)
606 {
607         mem_stat *s = xmalloc(sizeof(mem_stat));
608         s->collect = collect_mem;
609         s->opt = param[0];
610         return (s_stat*)s;
611 }
612
613
614 S_STAT(swp_stat)
615 S_STAT_END(swp_stat)
616
617 static void collect_swp(swp_stat *s)
618 {
619         ullong s_total[1];
620         ullong s_free[1];
621         if (rdval(get_file(&proc_meminfo), "SwapTotal:", s_total, 1)
622          || rdval(proc_meminfo.file,       "SwapFree:" , s_free,  1)
623         ) {
624                 put_question_marks(4);
625                 return;
626         }
627         scale((s_total[0]-s_free[0]) << 10);
628 }
629
630 static s_stat* init_swp(const char *param)
631 {
632         swp_stat *s = xmalloc(sizeof(swp_stat));
633         s->collect = collect_swp;
634         return (s_stat*)s;
635 }
636
637
638 S_STAT(fd_stat)
639 S_STAT_END(fd_stat)
640
641 static void collect_fd(fd_stat *s)
642 {
643         char file[4096];
644         ullong data[2];
645
646         readfile_z(file, sizeof(file), "/proc/sys/fs/file-nr");
647         if (rdval(file, "", data, 1, 2)) {
648                 put_question_marks(4);
649                 return;
650         }
651
652         scale(data[0] - data[1]);
653 }
654
655 static s_stat* init_fd(const char *param)
656 {
657         fd_stat *s = xmalloc(sizeof(fd_stat));
658         s->collect = collect_fd;
659         return (s_stat*)s;
660 }
661
662
663 S_STAT(time_stat)
664         int prec;
665         int scale;
666 S_STAT_END(time_stat)
667
668 static void collect_time(time_stat *s)
669 {
670         char buf[sizeof("12:34:56.123456")];
671         struct tm* tm;
672         int us = tv.tv_usec + s->scale/2;
673         time_t t = tv.tv_sec;
674
675         if (us >= 1000000) {
676                 t++;
677                 us -= 1000000;
678         }
679         tm = localtime(&t);
680
681         sprintf(buf, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
682         if (s->prec)
683                 sprintf(buf+8, ".%0*d", s->prec, us / s->scale);
684         put(buf);
685 }
686
687 static s_stat* init_time(const char *param)
688 {
689         int prec;
690         time_stat *s = xmalloc(sizeof(time_stat));
691
692         s->collect = collect_time;
693         prec = param[0]-'0';
694         if (prec < 0) prec = 0;
695         else if (prec > 6) prec = 6;
696         s->prec = prec;
697         s->scale = 1;
698         while (prec++ < 6)
699                 s->scale *= 10;
700         return (s_stat*)s;
701 }
702
703 static void collect_info(s_stat *s)
704 {
705         gen++;
706         while (s) {
707                 put(s->label);
708                 s->collect(s);
709                 s = s->next;
710         }
711 }
712
713
714 typedef s_stat* init_func(const char *param);
715
716 static const char options[] = "ncmsfixptbdr";
717 static init_func* init_functions[] = {
718         init_if,
719         init_cpu,
720         init_mem,
721         init_swp,
722         init_fd,
723         init_int,
724         init_ctx,
725         init_fork,
726         init_time,
727         init_blk,
728         init_delay,
729         init_cr,
730 };
731
732 int nmeter_main(int argc, char* argv[])
733 {
734         char buf[32];
735         s_stat *first = NULL;
736         s_stat *last = NULL;
737         s_stat *s;
738         char *cur, *prev;
739
740         if (argc != 2)
741                 bb_show_usage();
742
743         if (open_read_close("/proc/version", buf, sizeof(buf)) > 0)
744                 is26 = (strstr(buf, " 2.4.")==NULL);
745
746         // Can use argv[1] directly, but this will mess up
747         // parameters as seen by e.g. ps. Making a copy...
748         cur = xstrdup(argv[1]);
749         while (1) {
750                 char *param, *p;
751                 prev = cur;
752 again:
753                 cur = strchr(cur, '%');
754                 if (!cur)
755                         break;
756                 if (cur[1]=='%') {      // %%
757                         strcpy(cur, cur+1);
758                         cur++;
759                         goto again;
760                 }
761                 *cur++ = '\0';          // overwrite %
762                 if (cur[0] == '[') {
763                         // format: %[foptstring]
764                         cur++;
765                         p = strchr(options, cur[0]);
766                         param = cur+1;
767                         while (cur[0] != ']') {
768                                 if (!cur[0])
769                                         bb_show_usage();
770                                 cur++;
771                         }
772                         *cur++ = '\0';  // overwrite [
773                 } else {
774                         // format: %NNNNNNf
775                         param = cur;
776                         while (cur[0] >= '0' && cur[0] <= '9')
777                                 cur++;
778                         if (!cur[0])
779                                 bb_show_usage();
780                         p = strchr(options, cur[0]);
781                         *cur++ = '\0';  // overwrite format char
782                 }
783                 if (!p)
784                         bb_show_usage();
785                 s = init_functions[p-options](param);
786                 if (s) {
787                         s->label = prev;
788                         s->next = 0;
789                         if (!first)
790                                 first = s;
791                         else
792                                 last->next = s;
793                         last = s;
794                 } else {
795                         // %NNNNd or %r option. remove it from string
796                         strcpy(prev + strlen(prev), cur);
797                         cur = prev;
798                 }
799         }
800         if (prev[0]) {
801                 s = init_literal();
802                 s->label = prev;
803                 s->next = 0;
804                 if (!first)
805                         first = s;
806                 else
807                         last->next = s;
808                 last = s;
809         }
810
811         // Generate first samples but do not print them, they're bogus
812         collect_info(first);
813         reset_outbuf();
814         if (delta >= 0) {
815                 gettimeofday(&tv, 0);
816                 usleep(delta > 1000000 ? 1000000 : delta - tv.tv_usec%deltanz);
817         }
818
819         while (1) {
820                 gettimeofday(&tv, 0);
821                 collect_info(first);
822                 put(final_str);
823                 print_outbuf();
824
825                 // Negative delta -> no usleep at all
826                 // This will hog the CPU but you can have REALLY GOOD
827                 // time resolution ;)
828                 // TODO: detect and avoid useless updates
829                 // (like: nothing happens except time)
830                 if (delta >= 0) {
831                         int rem;
832                         // can be commented out, will sacrifice sleep time precision a bit
833                         gettimeofday(&tv, 0);
834                         if (need_seconds)
835                                 rem = delta - ((ullong)tv.tv_sec*1000000+tv.tv_usec)%deltanz;
836                         else
837                                 rem = delta - tv.tv_usec%deltanz;
838                         // Sometimes kernel wakes us up just a tiny bit earlier than asked
839                         // Do not go to very short sleep in this case
840                         if (rem < delta/128) {
841                                 rem += delta;
842                         }
843                         usleep(rem);
844                 }
845         }
846
847         return 0;
848 }