inline is something for the compiler to figure ...
[rrdtool.git] / src / rrd_update.c
1 /*****************************************************************************
2  * RRDtool 1.3.2  Copyright by Tobi Oetiker, 1997-2008
3  *                Copyright by Florian Forster, 2008
4  *****************************************************************************
5  * rrd_update.c  RRD Update Function
6  *****************************************************************************
7  * $Id$
8  *****************************************************************************/
9
10 #include "rrd_tool.h"
11
12 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
13 #include <sys/locking.h>
14 #include <sys/stat.h>
15 #include <io.h>
16 #endif
17
18 #include <locale.h>
19
20 #include "rrd_hw.h"
21 #include "rrd_rpncalc.h"
22
23 #include "rrd_is_thread_safe.h"
24 #include "unused.h"
25
26 #include "rrd_client.h"
27
28 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
29 /*
30  * WIN32 does not have gettimeofday     and struct timeval. This is a quick and dirty
31  * replacement.
32  */
33 #include <sys/timeb.h>
34
35 #ifndef __MINGW32__
36 struct timeval {
37     time_t    tv_sec;   /* seconds */
38     long      tv_usec;  /* microseconds */
39 };
40 #endif
41
42 struct __timezone {
43     int       tz_minuteswest;   /* minutes W of Greenwich */
44     int       tz_dsttime;   /* type of dst correction */
45 };
46
47 static int gettimeofday(
48     struct timeval *t,
49     struct __timezone *tz)
50 {
51
52     struct _timeb current_time;
53
54     _ftime(&current_time);
55
56     t->tv_sec = current_time.time;
57     t->tv_usec = current_time.millitm * 1000;
58
59     return 0;
60 }
61
62 #endif
63
64 /* FUNCTION PROTOTYPES */
65
66 int       rrd_update_r(
67     const char *filename,
68     const char *tmplt,
69     int argc,
70     const char **argv);
71 int       _rrd_update(
72     const char *filename,
73     const char *tmplt,
74     int argc,
75     const char **argv,
76     rrd_info_t *);
77
78 static int allocate_data_structures(
79     rrd_t *rrd,
80     char ***updvals,
81     rrd_value_t **pdp_temp,
82     const char *tmplt,
83     long **tmpl_idx,
84     unsigned long *tmpl_cnt,
85     unsigned long **rra_step_cnt,
86     unsigned long **skip_update,
87     rrd_value_t **pdp_new);
88
89 static int parse_template(
90     rrd_t *rrd,
91     const char *tmplt,
92     unsigned long *tmpl_cnt,
93     long *tmpl_idx);
94
95 static int process_arg(
96     char *step_start,
97     rrd_t *rrd,
98     rrd_file_t *rrd_file,
99     unsigned long rra_begin,
100     time_t *current_time,
101     unsigned long *current_time_usec,
102     rrd_value_t *pdp_temp,
103     rrd_value_t *pdp_new,
104     unsigned long *rra_step_cnt,
105     char **updvals,
106     long *tmpl_idx,
107     unsigned long tmpl_cnt,
108     rrd_info_t ** pcdp_summary,
109     int version,
110     unsigned long *skip_update,
111     int *schedule_smooth);
112
113 static int parse_ds(
114     rrd_t *rrd,
115     char **updvals,
116     long *tmpl_idx,
117     char *input,
118     unsigned long tmpl_cnt,
119     time_t *current_time,
120     unsigned long *current_time_usec,
121     int version);
122
123 static int get_time_from_reading(
124     rrd_t *rrd,
125     char timesyntax,
126     char **updvals,
127     time_t *current_time,
128     unsigned long *current_time_usec,
129     int version);
130
131 static int update_pdp_prep(
132     rrd_t *rrd,
133     char **updvals,
134     rrd_value_t *pdp_new,
135     double interval);
136
137 static int calculate_elapsed_steps(
138     rrd_t *rrd,
139     unsigned long current_time,
140     unsigned long current_time_usec,
141     double interval,
142     double *pre_int,
143     double *post_int,
144     unsigned long *proc_pdp_cnt);
145
146 static void simple_update(
147     rrd_t *rrd,
148     double interval,
149     rrd_value_t *pdp_new);
150
151 static int process_all_pdp_st(
152     rrd_t *rrd,
153     double interval,
154     double pre_int,
155     double post_int,
156     unsigned long elapsed_pdp_st,
157     rrd_value_t *pdp_new,
158     rrd_value_t *pdp_temp);
159
160 static int process_pdp_st(
161     rrd_t *rrd,
162     unsigned long ds_idx,
163     double interval,
164     double pre_int,
165     double post_int,
166     long diff_pdp_st,
167     rrd_value_t *pdp_new,
168     rrd_value_t *pdp_temp);
169
170 static int update_all_cdp_prep(
171     rrd_t *rrd,
172     unsigned long *rra_step_cnt,
173     unsigned long rra_begin,
174     rrd_file_t *rrd_file,
175     unsigned long elapsed_pdp_st,
176     unsigned long proc_pdp_cnt,
177     rrd_value_t **last_seasonal_coef,
178     rrd_value_t **seasonal_coef,
179     rrd_value_t *pdp_temp,
180     unsigned long *skip_update,
181     int *schedule_smooth);
182
183 static int do_schedule_smooth(
184     rrd_t *rrd,
185     unsigned long rra_idx,
186     unsigned long elapsed_pdp_st);
187
188 static int update_cdp_prep(
189     rrd_t *rrd,
190     unsigned long elapsed_pdp_st,
191     unsigned long start_pdp_offset,
192     unsigned long *rra_step_cnt,
193     int rra_idx,
194     rrd_value_t *pdp_temp,
195     rrd_value_t *last_seasonal_coef,
196     rrd_value_t *seasonal_coef,
197     int current_cf);
198
199 static void update_cdp(
200     unival *scratch,
201     int current_cf,
202     rrd_value_t pdp_temp_val,
203     unsigned long rra_step_cnt,
204     unsigned long elapsed_pdp_st,
205     unsigned long start_pdp_offset,
206     unsigned long pdp_cnt,
207     rrd_value_t xff,
208     int i,
209     int ii);
210
211 static void initialize_cdp_val(
212     unival *scratch,
213     int current_cf,
214     rrd_value_t pdp_temp_val,
215     unsigned long elapsed_pdp_st,
216     unsigned long start_pdp_offset,
217     unsigned long pdp_cnt);
218
219 static void reset_cdp(
220     rrd_t *rrd,
221     unsigned long elapsed_pdp_st,
222     rrd_value_t *pdp_temp,
223     rrd_value_t *last_seasonal_coef,
224     rrd_value_t *seasonal_coef,
225     int rra_idx,
226     int ds_idx,
227     int cdp_idx,
228     enum cf_en current_cf);
229
230 static rrd_value_t initialize_average_carry_over(
231     rrd_value_t pdp_temp_val,
232     unsigned long elapsed_pdp_st,
233     unsigned long start_pdp_offset,
234     unsigned long pdp_cnt);
235
236 static rrd_value_t calculate_cdp_val(
237     rrd_value_t cdp_val,
238     rrd_value_t pdp_temp_val,
239     unsigned long elapsed_pdp_st,
240     int current_cf,
241     int i,
242     int ii);
243
244 static int update_aberrant_cdps(
245     rrd_t *rrd,
246     rrd_file_t *rrd_file,
247     unsigned long rra_begin,
248     unsigned long elapsed_pdp_st,
249     rrd_value_t *pdp_temp,
250     rrd_value_t **seasonal_coef);
251
252 static int write_to_rras(
253     rrd_t *rrd,
254     rrd_file_t *rrd_file,
255     unsigned long *rra_step_cnt,
256     unsigned long rra_begin,
257     time_t current_time,
258     unsigned long *skip_update,
259     rrd_info_t ** pcdp_summary);
260
261 static int write_RRA_row(
262     rrd_file_t *rrd_file,
263     rrd_t *rrd,
264     unsigned long rra_idx,
265     unsigned short CDP_scratch_idx,
266     rrd_info_t ** pcdp_summary,
267     time_t rra_time);
268
269 static int smooth_all_rras(
270     rrd_t *rrd,
271     rrd_file_t *rrd_file,
272     unsigned long rra_begin);
273
274 #ifndef HAVE_MMAP
275 static int write_changes_to_disk(
276     rrd_t *rrd,
277     rrd_file_t *rrd_file,
278     int version);
279 #endif
280
281 /*
282  * normalize time as returned by gettimeofday. usec part must
283  * be always >= 0
284  */
285 static void normalize_time(
286     struct timeval *t)
287 {
288     if (t->tv_usec < 0) {
289         t->tv_sec--;
290         t->tv_usec += 1e6L;
291     }
292 }
293
294 /*
295  * Sets current_time and current_time_usec based on the current time.
296  * current_time_usec is set to 0 if the version number is 1 or 2.
297  */
298 static void initialize_time(
299     time_t *current_time,
300     unsigned long *current_time_usec,
301     int version)
302 {
303     struct timeval tmp_time;    /* used for time conversion */
304
305     gettimeofday(&tmp_time, 0);
306     normalize_time(&tmp_time);
307     *current_time = tmp_time.tv_sec;
308     if (version >= 3) {
309         *current_time_usec = tmp_time.tv_usec;
310     } else {
311         *current_time_usec = 0;
312     }
313 }
314
315 #define IFDNAN(X,Y) (isnan(X) ? (Y) : (X));
316
317 rrd_info_t *rrd_update_v(
318     int argc,
319     char **argv)
320 {
321     char     *tmplt = NULL;
322     rrd_info_t *result = NULL;
323     rrd_infoval_t rc;
324     char *opt_daemon = NULL;
325     struct option long_options[] = {
326         {"template", required_argument, 0, 't'},
327         {0, 0, 0, 0}
328     };
329
330     rc.u_int = -1;
331     optind = 0;
332     opterr = 0;         /* initialize getopt */
333
334     while (1) {
335         int       option_index = 0;
336         int       opt;
337
338         opt = getopt_long(argc, argv, "t:", long_options, &option_index);
339
340         if (opt == EOF)
341             break;
342
343         switch (opt) {
344         case 't':
345             tmplt = optarg;
346             break;
347
348         case '?':
349             rrd_set_error("unknown option '%s'", argv[optind - 1]);
350             goto end_tag;
351         }
352     }
353
354     opt_daemon = getenv (ENV_RRDCACHED_ADDRESS);
355     if (opt_daemon != NULL) {
356         rrd_set_error ("The \"%s\" environment variable is defined, "
357                 "but \"%s\" cannot work with rrdcached. Either unset "
358                 "the environment variable or use \"update\" instead.",
359                 ENV_RRDCACHED_ADDRESS, argv[0]);
360         goto end_tag;
361     }
362
363     /* need at least 2 arguments: filename, data. */
364     if (argc - optind < 2) {
365         rrd_set_error("Not enough arguments");
366         goto end_tag;
367     }
368     rc.u_int = 0;
369     result = rrd_info_push(NULL, sprintf_alloc("return_value"), RD_I_INT, rc);
370     rc.u_int = _rrd_update(argv[optind], tmplt,
371                            argc - optind - 1,
372                            (const char **) (argv + optind + 1), result);
373     result->value.u_int = rc.u_int;
374   end_tag:
375     return result;
376 }
377
378 int rrd_update(
379     int argc,
380     char **argv)
381 {
382     struct option long_options[] = {
383         {"template", required_argument, 0, 't'},
384         {"daemon",   required_argument, 0, 'd'},
385         {0, 0, 0, 0}
386     };
387     int       option_index = 0;
388     int       opt;
389     char     *tmplt = NULL;
390     int       rc = -1;
391     char     *opt_daemon = NULL;
392
393     optind = 0;
394     opterr = 0;         /* initialize getopt */
395
396     while (1) {
397         opt = getopt_long(argc, argv, "t:d:", long_options, &option_index);
398
399         if (opt == EOF)
400             break;
401
402         switch (opt) {
403         case 't':
404             tmplt = strdup(optarg);
405             break;
406
407         case 'd':
408             if (opt_daemon != NULL)
409                 free (opt_daemon);
410             opt_daemon = strdup (optarg);
411             if (opt_daemon == NULL)
412             {
413                 rrd_set_error("strdup failed.");
414                 goto out;
415             }
416             break;
417
418         case '?':
419             rrd_set_error("unknown option '%s'", argv[optind - 1]);
420             goto out;
421         }
422     }
423
424     /* need at least 2 arguments: filename, data. */
425     if (argc - optind < 2) {
426         rrd_set_error("Not enough arguments");
427         goto out;
428     }
429
430     {   /* try to connect to rrdcached */
431         int status = rrdc_connect(opt_daemon);
432         if (status != 0) return status;
433     }
434
435     if ((tmplt != NULL) && rrdc_is_connected(opt_daemon))
436     {
437         rrd_set_error("The caching daemon cannot be used together with "
438                 "templates yet.");
439         goto out;
440     }
441
442     if (! rrdc_is_connected(opt_daemon))
443     {
444       rc = rrd_update_r(argv[optind], tmplt,
445                         argc - optind - 1, (const char **) (argv + optind + 1));
446     }
447     else /* we are connected */
448     {
449         rc = rrdc_update (argv[optind], /* file */
450                           argc - optind - 1, /* values_num */
451                           (const char *const *) (argv + optind + 1)); /* values */
452         if (rc > 0)
453             rrd_set_error("Failed sending the values to rrdcached: %s",
454                           rrd_strerror (rc));
455     }
456
457   out:
458     if (tmplt != NULL)
459     {
460         free(tmplt);
461         tmplt = NULL;
462     }
463     if (opt_daemon != NULL)
464     {
465         free (opt_daemon);
466         opt_daemon = NULL;
467     }
468     return rc;
469 }
470
471 int rrd_update_r(
472     const char *filename,
473     const char *tmplt,
474     int argc,
475     const char **argv)
476 {
477     return _rrd_update(filename, tmplt, argc, argv, NULL);
478 }
479
480 int _rrd_update(
481     const char *filename,
482     const char *tmplt,
483     int argc,
484     const char **argv,
485     rrd_info_t * pcdp_summary)
486 {
487
488     int       arg_i = 2;
489
490     unsigned long rra_begin;    /* byte pointer to the rra
491                                  * area in the rrd file.  this
492                                  * pointer never changes value */
493     rrd_value_t *pdp_new;   /* prepare the incoming data to be added 
494                              * to the existing entry */
495     rrd_value_t *pdp_temp;  /* prepare the pdp values to be added 
496                              * to the cdp values */
497
498     long     *tmpl_idx; /* index representing the settings
499                          * transported by the tmplt index */
500     unsigned long tmpl_cnt = 2; /* time and data */
501     rrd_t     rrd;
502     time_t    current_time = 0;
503     unsigned long current_time_usec = 0;    /* microseconds part of current time */
504     char    **updvals;
505     int       schedule_smooth = 0;
506
507     /* number of elapsed PDP steps since last update */
508     unsigned long *rra_step_cnt = NULL;
509
510     int       version;  /* rrd version */
511     rrd_file_t *rrd_file;
512     char     *arg_copy; /* for processing the argv */
513     unsigned long *skip_update; /* RRAs to advance but not write */
514
515     /* need at least 1 arguments: data. */
516     if (argc < 1) {
517         rrd_set_error("Not enough arguments");
518         goto err_out;
519     }
520
521     rrd_init(&rrd);
522     if ((rrd_file = rrd_open(filename, &rrd, RRD_READWRITE)) == NULL) {
523         goto err_free;
524     }
525     /* We are now at the beginning of the rra's */
526     rra_begin = rrd_file->header_len;
527
528     version = atoi(rrd.stat_head->version);
529
530     initialize_time(&current_time, &current_time_usec, version);
531
532     /* get exclusive lock to whole file.
533      * lock gets removed when we close the file.
534      */
535     if (rrd_lock(rrd_file) != 0) {
536         rrd_set_error("could not lock RRD");
537         goto err_close;
538     }
539
540     if (allocate_data_structures(&rrd, &updvals,
541                                  &pdp_temp, tmplt, &tmpl_idx, &tmpl_cnt,
542                                  &rra_step_cnt, &skip_update,
543                                  &pdp_new) == -1) {
544         goto err_close;
545     }
546
547     /* loop through the arguments. */
548     for (arg_i = 0; arg_i < argc; arg_i++) {
549         if ((arg_copy = strdup(argv[arg_i])) == NULL) {
550             rrd_set_error("failed duplication argv entry");
551             break;
552         }
553         if (process_arg(arg_copy, &rrd, rrd_file, rra_begin,
554                         &current_time, &current_time_usec, pdp_temp, pdp_new,
555                         rra_step_cnt, updvals, tmpl_idx, tmpl_cnt,
556                         &pcdp_summary, version, skip_update,
557                         &schedule_smooth) == -1) {
558             if (rrd_test_error()) { /* Should have error string always here */
559                 char     *save_error;
560
561                 /* Prepend file name to error message */
562                 if ((save_error = strdup(rrd_get_error())) != NULL) {
563                     rrd_set_error("%s: %s", filename, save_error);
564                     free(save_error);
565                 }
566             }
567             free(arg_copy);
568             break;
569         }
570         free(arg_copy);
571     }
572
573     free(rra_step_cnt);
574
575     /* if we got here and if there is an error and if the file has not been
576      * written to, then close things up and return. */
577     if (rrd_test_error()) {
578         goto err_free_structures;
579     }
580 #ifndef HAVE_MMAP
581     if (write_changes_to_disk(&rrd, rrd_file, version) == -1) {
582         goto err_free_structures;
583     }
584 #endif
585
586     /* calling the smoothing code here guarantees at most one smoothing
587      * operation per rrd_update call. Unfortunately, it is possible with bulk
588      * updates, or a long-delayed update for smoothing to occur off-schedule.
589      * This really isn't critical except during the burn-in cycles. */
590     if (schedule_smooth) {
591         smooth_all_rras(&rrd, rrd_file, rra_begin);
592     }
593
594 /*    rrd_dontneed(rrd_file,&rrd); */
595     rrd_free(&rrd);
596     rrd_close(rrd_file);
597
598     free(pdp_new);
599     free(tmpl_idx);
600     free(pdp_temp);
601     free(skip_update);
602     free(updvals);
603     return 0;
604
605   err_free_structures:
606     free(pdp_new);
607     free(tmpl_idx);
608     free(pdp_temp);
609     free(skip_update);
610     free(updvals);
611   err_close:
612     rrd_close(rrd_file);
613   err_free:
614     rrd_free(&rrd);
615   err_out:
616     return -1;
617 }
618
619 /*
620  * Allocate some important arrays used, and initialize the template.
621  *
622  * When it returns, either all of the structures are allocated
623  * or none of them are.
624  *
625  * Returns 0 on success, -1 on error.
626  */
627 static int allocate_data_structures(
628     rrd_t *rrd,
629     char ***updvals,
630     rrd_value_t **pdp_temp,
631     const char *tmplt,
632     long **tmpl_idx,
633     unsigned long *tmpl_cnt,
634     unsigned long **rra_step_cnt,
635     unsigned long **skip_update,
636     rrd_value_t **pdp_new)
637 {
638     unsigned  i, ii;
639     if ((*updvals = (char **) malloc(sizeof(char *)
640                                      * (rrd->stat_head->ds_cnt + 1))) == NULL) {
641         rrd_set_error("allocating updvals pointer array.");
642         return -1;
643     }
644     if ((*pdp_temp = (rrd_value_t *) malloc(sizeof(rrd_value_t)
645                                             * rrd->stat_head->ds_cnt)) ==
646         NULL) {
647         rrd_set_error("allocating pdp_temp.");
648         goto err_free_updvals;
649     }
650     if ((*skip_update = (unsigned long *) malloc(sizeof(unsigned long)
651                                                  *
652                                                  rrd->stat_head->rra_cnt)) ==
653         NULL) {
654         rrd_set_error("allocating skip_update.");
655         goto err_free_pdp_temp;
656     }
657     if ((*tmpl_idx = (long *) malloc(sizeof(unsigned long)
658                                      * (rrd->stat_head->ds_cnt + 1))) == NULL) {
659         rrd_set_error("allocating tmpl_idx.");
660         goto err_free_skip_update;
661     }
662     if ((*rra_step_cnt = (unsigned long *) malloc(sizeof(unsigned long)
663                                                   *
664                                                   (rrd->stat_head->
665                                                    rra_cnt))) == NULL) {
666         rrd_set_error("allocating rra_step_cnt.");
667         goto err_free_tmpl_idx;
668     }
669
670     /* initialize tmplt redirector */
671     /* default config example (assume DS 1 is a CDEF DS)
672        tmpl_idx[0] -> 0; (time)
673        tmpl_idx[1] -> 1; (DS 0)
674        tmpl_idx[2] -> 3; (DS 2)
675        tmpl_idx[3] -> 4; (DS 3) */
676     (*tmpl_idx)[0] = 0; /* time */
677     for (i = 1, ii = 1; i <= rrd->stat_head->ds_cnt; i++) {
678         if (dst_conv(rrd->ds_def[i - 1].dst) != DST_CDEF)
679             (*tmpl_idx)[ii++] = i;
680     }
681     *tmpl_cnt = ii;
682
683     if (tmplt != NULL) {
684         if (parse_template(rrd, tmplt, tmpl_cnt, *tmpl_idx) == -1) {
685             goto err_free_rra_step_cnt;
686         }
687     }
688
689     if ((*pdp_new = (rrd_value_t *) malloc(sizeof(rrd_value_t)
690                                            * rrd->stat_head->ds_cnt)) == NULL) {
691         rrd_set_error("allocating pdp_new.");
692         goto err_free_rra_step_cnt;
693     }
694
695     return 0;
696
697   err_free_rra_step_cnt:
698     free(*rra_step_cnt);
699   err_free_tmpl_idx:
700     free(*tmpl_idx);
701   err_free_skip_update:
702     free(*skip_update);
703   err_free_pdp_temp:
704     free(*pdp_temp);
705   err_free_updvals:
706     free(*updvals);
707     return -1;
708 }
709
710 /*
711  * Parses tmplt and puts an ordered list of DS's into tmpl_idx.
712  *
713  * Returns 0 on success.
714  */
715 static int parse_template(
716     rrd_t *rrd,
717     const char *tmplt,
718     unsigned long *tmpl_cnt,
719     long *tmpl_idx)
720 {
721     char     *dsname, *tmplt_copy;
722     unsigned int tmpl_len, i;
723     int       ret = 0;
724
725     *tmpl_cnt = 1;      /* the first entry is the time */
726
727     /* we should work on a writeable copy here */
728     if ((tmplt_copy = strdup(tmplt)) == NULL) {
729         rrd_set_error("error copying tmplt '%s'", tmplt);
730         ret = -1;
731         goto out;
732     }
733
734     dsname = tmplt_copy;
735     tmpl_len = strlen(tmplt_copy);
736     for (i = 0; i <= tmpl_len; i++) {
737         if (tmplt_copy[i] == ':' || tmplt_copy[i] == '\0') {
738             tmplt_copy[i] = '\0';
739             if (*tmpl_cnt > rrd->stat_head->ds_cnt) {
740                 rrd_set_error("tmplt contains more DS definitions than RRD");
741                 ret = -1;
742                 goto out_free_tmpl_copy;
743             }
744             if ((tmpl_idx[(*tmpl_cnt)++] = ds_match(rrd, dsname) + 1) == 0) {
745                 rrd_set_error("unknown DS name '%s'", dsname);
746                 ret = -1;
747                 goto out_free_tmpl_copy;
748             }
749             /* go to the next entry on the tmplt_copy */
750             if (i < tmpl_len)
751                 dsname = &tmplt_copy[i + 1];
752         }
753     }
754   out_free_tmpl_copy:
755     free(tmplt_copy);
756   out:
757     return ret;
758 }
759
760 /*
761  * Parse an update string, updates the primary data points (PDPs)
762  * and consolidated data points (CDPs), and writes changes to the RRAs.
763  *
764  * Returns 0 on success, -1 on error.
765  */
766 static int process_arg(
767     char *step_start,
768     rrd_t *rrd,
769     rrd_file_t *rrd_file,
770     unsigned long rra_begin,
771     time_t *current_time,
772     unsigned long *current_time_usec,
773     rrd_value_t *pdp_temp,
774     rrd_value_t *pdp_new,
775     unsigned long *rra_step_cnt,
776     char **updvals,
777     long *tmpl_idx,
778     unsigned long tmpl_cnt,
779     rrd_info_t ** pcdp_summary,
780     int version,
781     unsigned long *skip_update,
782     int *schedule_smooth)
783 {
784     rrd_value_t *seasonal_coef = NULL, *last_seasonal_coef = NULL;
785
786     /* a vector of future Holt-Winters seasonal coefs */
787     unsigned long elapsed_pdp_st;
788
789     double    interval, pre_int, post_int;  /* interval between this and
790                                              * the last run */
791     unsigned long proc_pdp_cnt;
792
793     if (parse_ds(rrd, updvals, tmpl_idx, step_start, tmpl_cnt,
794                  current_time, current_time_usec, version) == -1) {
795         return -1;
796     }
797
798     interval = (double) (*current_time - rrd->live_head->last_up)
799         + (double) ((long) *current_time_usec -
800                     (long) rrd->live_head->last_up_usec) / 1e6f;
801
802     /* process the data sources and update the pdp_prep 
803      * area accordingly */
804     if (update_pdp_prep(rrd, updvals, pdp_new, interval) == -1) {
805         return -1;
806     }
807
808     elapsed_pdp_st = calculate_elapsed_steps(rrd,
809                                              *current_time,
810                                              *current_time_usec, interval,
811                                              &pre_int, &post_int,
812                                              &proc_pdp_cnt);
813
814     /* has a pdp_st moment occurred since the last run ? */
815     if (elapsed_pdp_st == 0) {
816         /* no we have not passed a pdp_st moment. therefore update is simple */
817         simple_update(rrd, interval, pdp_new);
818     } else {
819         /* an pdp_st has occurred. */
820         if (process_all_pdp_st(rrd, interval,
821                                pre_int, post_int,
822                                elapsed_pdp_st, pdp_new, pdp_temp) == -1) {
823             return -1;
824         }
825         if (update_all_cdp_prep(rrd, rra_step_cnt,
826                                 rra_begin, rrd_file,
827                                 elapsed_pdp_st,
828                                 proc_pdp_cnt,
829                                 &last_seasonal_coef,
830                                 &seasonal_coef,
831                                 pdp_temp,
832                                 skip_update, schedule_smooth) == -1) {
833             goto err_free_coefficients;
834         }
835         if (update_aberrant_cdps(rrd, rrd_file, rra_begin,
836                                  elapsed_pdp_st, pdp_temp,
837                                  &seasonal_coef) == -1) {
838             goto err_free_coefficients;
839         }
840         if (write_to_rras(rrd, rrd_file, rra_step_cnt, rra_begin,
841                           *current_time, skip_update,
842                           pcdp_summary) == -1) {
843             goto err_free_coefficients;
844         }
845     }                   /* endif a pdp_st has occurred */
846     rrd->live_head->last_up = *current_time;
847     rrd->live_head->last_up_usec = *current_time_usec;
848
849     if (version < 3) {
850         *rrd->legacy_last_up = rrd->live_head->last_up;
851     }
852     free(seasonal_coef);
853     free(last_seasonal_coef);
854     return 0;
855
856   err_free_coefficients:
857     free(seasonal_coef);
858     free(last_seasonal_coef);
859     return -1;
860 }
861
862 /*
863  * Parse a DS string (time + colon-separated values), storing the
864  * results in current_time, current_time_usec, and updvals.
865  *
866  * Returns 0 on success, -1 on error.
867  */
868 static int parse_ds(
869     rrd_t *rrd,
870     char **updvals,
871     long *tmpl_idx,
872     char *input,
873     unsigned long tmpl_cnt,
874     time_t *current_time,
875     unsigned long *current_time_usec,
876     int version)
877 {
878     char     *p;
879     unsigned long i;
880     char      timesyntax;
881
882     updvals[0] = input;
883     /* initialize all ds input to unknown except the first one
884        which has always got to be set */
885     for (i = 1; i <= rrd->stat_head->ds_cnt; i++)
886         updvals[i] = "U";
887
888     /* separate all ds elements; first must be examined separately
889        due to alternate time syntax */
890     if ((p = strchr(input, '@')) != NULL) {
891         timesyntax = '@';
892     } else if ((p = strchr(input, ':')) != NULL) {
893         timesyntax = ':';
894     } else {
895         rrd_set_error("expected timestamp not found in data source from %s",
896                       input);
897         return -1;
898     }
899     *p = '\0';
900     i = 1;
901     updvals[tmpl_idx[i++]] = p + 1;
902     while (*(++p)) {
903         if (*p == ':') {
904             *p = '\0';
905             if (i < tmpl_cnt) {
906                 updvals[tmpl_idx[i++]] = p + 1;
907             }
908         }
909     }
910
911     if (i != tmpl_cnt) {
912         rrd_set_error("expected %lu data source readings (got %lu) from %s",
913                       tmpl_cnt - 1, i, input);
914         return -1;
915     }
916
917     if (get_time_from_reading(rrd, timesyntax, updvals,
918                               current_time, current_time_usec,
919                               version) == -1) {
920         return -1;
921     }
922     return 0;
923 }
924
925 /*
926  * Parse the time in a DS string, store it in current_time and 
927  * current_time_usec and verify that it's later than the last
928  * update for this DS.
929  *
930  * Returns 0 on success, -1 on error.
931  */
932 static int get_time_from_reading(
933     rrd_t *rrd,
934     char timesyntax,
935     char **updvals,
936     time_t *current_time,
937     unsigned long *current_time_usec,
938     int version)
939 {
940     double    tmp;
941     char     *parsetime_error = NULL;
942     char     *old_locale;
943     rrd_time_value_t ds_tv;
944     struct timeval tmp_time;    /* used for time conversion */
945
946     /* get the time from the reading ... handle N */
947     if (timesyntax == '@') {    /* at-style */
948         if ((parsetime_error = rrd_parsetime(updvals[0], &ds_tv))) {
949             rrd_set_error("ds time: %s: %s", updvals[0], parsetime_error);
950             return -1;
951         }
952         if (ds_tv.type == RELATIVE_TO_END_TIME ||
953             ds_tv.type == RELATIVE_TO_START_TIME) {
954             rrd_set_error("specifying time relative to the 'start' "
955                           "or 'end' makes no sense here: %s", updvals[0]);
956             return -1;
957         }
958         *current_time = mktime(&ds_tv.tm) +ds_tv.offset;
959         *current_time_usec = 0; /* FIXME: how to handle usecs here ? */
960     } else if (strcmp(updvals[0], "N") == 0) {
961         gettimeofday(&tmp_time, 0);
962         normalize_time(&tmp_time);
963         *current_time = tmp_time.tv_sec;
964         *current_time_usec = tmp_time.tv_usec;
965     } else {
966         old_locale = setlocale(LC_NUMERIC, "C");
967         errno = 0;
968         tmp = strtod(updvals[0], 0);
969         if (errno > 0) {
970             rrd_set_error("converting '%s' to float: %s",
971                 updvals[0], rrd_strerror(errno));
972             return -1;
973         };
974         setlocale(LC_NUMERIC, old_locale);
975         *current_time = floor(tmp);
976         *current_time_usec = (long) ((tmp - (double) *current_time) * 1e6f);
977     }
978     /* dont do any correction for old version RRDs */
979     if (version < 3)
980         *current_time_usec = 0;
981
982     if (*current_time < rrd->live_head->last_up ||
983         (*current_time == rrd->live_head->last_up &&
984          (long) *current_time_usec <= (long) rrd->live_head->last_up_usec)) {
985         rrd_set_error("illegal attempt to update using time %ld when "
986                       "last update time is %ld (minimum one second step)",
987                       *current_time, rrd->live_head->last_up);
988         return -1;
989     }
990     return 0;
991 }
992
993 /*
994  * Update pdp_new by interpreting the updvals according to the DS type
995  * (COUNTER, GAUGE, etc.).
996  *
997  * Returns 0 on success, -1 on error.
998  */
999 static int update_pdp_prep(
1000     rrd_t *rrd,
1001     char **updvals,
1002     rrd_value_t *pdp_new,
1003     double interval)
1004 {
1005     unsigned long ds_idx;
1006     int       ii;
1007     char     *endptr;   /* used in the conversion */
1008     double    rate;
1009     char     *old_locale;
1010     enum dst_en dst_idx;
1011
1012     for (ds_idx = 0; ds_idx < rrd->stat_head->ds_cnt; ds_idx++) {
1013         dst_idx = dst_conv(rrd->ds_def[ds_idx].dst);
1014
1015         /* make sure we do not build diffs with old last_ds values */
1016         if (rrd->ds_def[ds_idx].par[DS_mrhb_cnt].u_cnt < interval) {
1017             strncpy(rrd->pdp_prep[ds_idx].last_ds, "U", LAST_DS_LEN - 1);
1018             rrd->pdp_prep[ds_idx].last_ds[LAST_DS_LEN - 1] = '\0';
1019         }
1020
1021         /* NOTE: DST_CDEF should never enter this if block, because
1022          * updvals[ds_idx+1][0] is initialized to 'U'; unless the caller
1023          * accidently specified a value for the DST_CDEF. To handle this case,
1024          * an extra check is required. */
1025
1026         if ((updvals[ds_idx + 1][0] != 'U') &&
1027             (dst_idx != DST_CDEF) &&
1028             rrd->ds_def[ds_idx].par[DS_mrhb_cnt].u_cnt >= interval) {
1029             rate = DNAN;
1030
1031             /* pdp_new contains rate * time ... eg the bytes transferred during
1032              * the interval. Doing it this way saves a lot of math operations
1033              */
1034             switch (dst_idx) {
1035             case DST_COUNTER:
1036             case DST_DERIVE:
1037                 for (ii = 0; updvals[ds_idx + 1][ii] != '\0'; ii++) {
1038                     if ((updvals[ds_idx + 1][ii] < '0'
1039                          || updvals[ds_idx + 1][ii] > '9')
1040                         && (ii != 0 && updvals[ds_idx + 1][ii] != '-')) {
1041                         rrd_set_error("not a simple integer: '%s'",
1042                                       updvals[ds_idx + 1]);
1043                         return -1;
1044                     }
1045                 }
1046                 if (rrd->pdp_prep[ds_idx].last_ds[0] != 'U') {
1047                     pdp_new[ds_idx] =
1048                         rrd_diff(updvals[ds_idx + 1],
1049                                  rrd->pdp_prep[ds_idx].last_ds);
1050                     if (dst_idx == DST_COUNTER) {
1051                         /* simple overflow catcher. This will fail
1052                          * terribly for non 32 or 64 bit counters
1053                          * ... are there any others in SNMP land?
1054                          */
1055                         if (pdp_new[ds_idx] < (double) 0.0)
1056                             pdp_new[ds_idx] += (double) 4294967296.0;   /* 2^32 */
1057                         if (pdp_new[ds_idx] < (double) 0.0)
1058                             pdp_new[ds_idx] += (double) 18446744069414584320.0; /* 2^64-2^32 */
1059                     }
1060                     rate = pdp_new[ds_idx] / interval;
1061                 } else {
1062                     pdp_new[ds_idx] = DNAN;
1063                 }
1064                 break;
1065             case DST_ABSOLUTE:
1066                 old_locale = setlocale(LC_NUMERIC, "C");
1067                 errno = 0;
1068                 pdp_new[ds_idx] = strtod(updvals[ds_idx + 1], &endptr);
1069                 if (errno > 0) {
1070                     rrd_set_error("converting '%s' to float: %s",
1071                                   updvals[ds_idx + 1], rrd_strerror(errno));
1072                     return -1;
1073                 };
1074                 setlocale(LC_NUMERIC, old_locale);
1075                 if (endptr[0] != '\0') {
1076                     rrd_set_error
1077                         ("conversion of '%s' to float not complete: tail '%s'",
1078                          updvals[ds_idx + 1], endptr);
1079                     return -1;
1080                 }
1081                 rate = pdp_new[ds_idx] / interval;
1082                 break;
1083             case DST_GAUGE:
1084                 errno = 0;
1085                 old_locale = setlocale(LC_NUMERIC, "C");
1086                 pdp_new[ds_idx] =
1087                     strtod(updvals[ds_idx + 1], &endptr) * interval;
1088                 if (errno) {
1089                     rrd_set_error("converting '%s' to float: %s",
1090                                   updvals[ds_idx + 1], rrd_strerror(errno));
1091                     return -1;
1092                 };
1093                 setlocale(LC_NUMERIC, old_locale);
1094                 if (endptr[0] != '\0') {
1095                     rrd_set_error
1096                         ("conversion of '%s' to float not complete: tail '%s'",
1097                          updvals[ds_idx + 1], endptr);
1098                     return -1;
1099                 }
1100                 rate = pdp_new[ds_idx] / interval;
1101                 break;
1102             default:
1103                 rrd_set_error("rrd contains unknown DS type : '%s'",
1104                               rrd->ds_def[ds_idx].dst);
1105                 return -1;
1106             }
1107             /* break out of this for loop if the error string is set */
1108             if (rrd_test_error()) {
1109                 return -1;
1110             }
1111             /* make sure pdp_temp is neither too large or too small
1112              * if any of these occur it becomes unknown ...
1113              * sorry folks ... */
1114             if (!isnan(rate) &&
1115                 ((!isnan(rrd->ds_def[ds_idx].par[DS_max_val].u_val) &&
1116                   rate > rrd->ds_def[ds_idx].par[DS_max_val].u_val) ||
1117                  (!isnan(rrd->ds_def[ds_idx].par[DS_min_val].u_val) &&
1118                   rate < rrd->ds_def[ds_idx].par[DS_min_val].u_val))) {
1119                 pdp_new[ds_idx] = DNAN;
1120             }
1121         } else {
1122             /* no news is news all the same */
1123             pdp_new[ds_idx] = DNAN;
1124         }
1125
1126
1127         /* make a copy of the command line argument for the next run */
1128 #ifdef DEBUG
1129         fprintf(stderr, "prep ds[%lu]\t"
1130                 "last_arg '%s'\t"
1131                 "this_arg '%s'\t"
1132                 "pdp_new %10.2f\n",
1133                 ds_idx, rrd->pdp_prep[ds_idx].last_ds, updvals[ds_idx + 1],
1134                 pdp_new[ds_idx]);
1135 #endif
1136         strncpy(rrd->pdp_prep[ds_idx].last_ds, updvals[ds_idx + 1],
1137                 LAST_DS_LEN - 1);
1138         rrd->pdp_prep[ds_idx].last_ds[LAST_DS_LEN - 1] = '\0';
1139     }
1140     return 0;
1141 }
1142
1143 /*
1144  * How many PDP steps have elapsed since the last update? Returns the answer,
1145  * and stores the time between the last update and the last PDP in pre_time,
1146  * and the time between the last PDP and the current time in post_int.
1147  */
1148 static int calculate_elapsed_steps(
1149     rrd_t *rrd,
1150     unsigned long current_time,
1151     unsigned long current_time_usec,
1152     double interval,
1153     double *pre_int,
1154     double *post_int,
1155     unsigned long *proc_pdp_cnt)
1156 {
1157     unsigned long proc_pdp_st;  /* which pdp_st was the last to be processed */
1158     unsigned long occu_pdp_st;  /* when was the pdp_st before the last update
1159                                  * time */
1160     unsigned long proc_pdp_age; /* how old was the data in the pdp prep area 
1161                                  * when it was last updated */
1162     unsigned long occu_pdp_age; /* how long ago was the last pdp_step time */
1163
1164     /* when was the current pdp started */
1165     proc_pdp_age = rrd->live_head->last_up % rrd->stat_head->pdp_step;
1166     proc_pdp_st = rrd->live_head->last_up - proc_pdp_age;
1167
1168     /* when did the last pdp_st occur */
1169     occu_pdp_age = current_time % rrd->stat_head->pdp_step;
1170     occu_pdp_st = current_time - occu_pdp_age;
1171
1172     if (occu_pdp_st > proc_pdp_st) {
1173         /* OK we passed the pdp_st moment */
1174         *pre_int = (long) occu_pdp_st - rrd->live_head->last_up;    /* how much of the input data
1175                                                                      * occurred before the latest
1176                                                                      * pdp_st moment*/
1177         *pre_int -= ((double) rrd->live_head->last_up_usec) / 1e6f; /* adjust usecs */
1178         *post_int = occu_pdp_age;   /* how much after it */
1179         *post_int += ((double) current_time_usec) / 1e6f;   /* adjust usecs */
1180     } else {
1181         *pre_int = interval;
1182         *post_int = 0;
1183     }
1184
1185     *proc_pdp_cnt = proc_pdp_st / rrd->stat_head->pdp_step;
1186
1187 #ifdef DEBUG
1188     printf("proc_pdp_age %lu\t"
1189            "proc_pdp_st %lu\t"
1190            "occu_pfp_age %lu\t"
1191            "occu_pdp_st %lu\t"
1192            "int %lf\t"
1193            "pre_int %lf\t"
1194            "post_int %lf\n", proc_pdp_age, proc_pdp_st,
1195            occu_pdp_age, occu_pdp_st, interval, *pre_int, *post_int);
1196 #endif
1197
1198     /* compute the number of elapsed pdp_st moments */
1199     return (occu_pdp_st - proc_pdp_st) / rrd->stat_head->pdp_step;
1200 }
1201
1202 /*
1203  * Increment the PDP values by the values in pdp_new, or else initialize them.
1204  */
1205 static void simple_update(
1206     rrd_t *rrd,
1207     double interval,
1208     rrd_value_t *pdp_new)
1209 {
1210     int       i;
1211
1212     for (i = 0; i < (signed) rrd->stat_head->ds_cnt; i++) {
1213         if (isnan(pdp_new[i])) {
1214             /* this is not really accurate if we use subsecond data arrival time
1215                should have thought of it when going subsecond resolution ...
1216                sorry next format change we will have it! */
1217             rrd->pdp_prep[i].scratch[PDP_unkn_sec_cnt].u_cnt +=
1218                 floor(interval);
1219         } else {
1220             if (isnan(rrd->pdp_prep[i].scratch[PDP_val].u_val)) {
1221                 rrd->pdp_prep[i].scratch[PDP_val].u_val = pdp_new[i];
1222             } else {
1223                 rrd->pdp_prep[i].scratch[PDP_val].u_val += pdp_new[i];
1224             }
1225         }
1226 #ifdef DEBUG
1227         fprintf(stderr,
1228                 "NO PDP  ds[%i]\t"
1229                 "value %10.2f\t"
1230                 "unkn_sec %5lu\n",
1231                 i,
1232                 rrd->pdp_prep[i].scratch[PDP_val].u_val,
1233                 rrd->pdp_prep[i].scratch[PDP_unkn_sec_cnt].u_cnt);
1234 #endif
1235     }
1236 }
1237
1238 /*
1239  * Call process_pdp_st for each DS.
1240  *
1241  * Returns 0 on success, -1 on error.
1242  */
1243 static int process_all_pdp_st(
1244     rrd_t *rrd,
1245     double interval,
1246     double pre_int,
1247     double post_int,
1248     unsigned long elapsed_pdp_st,
1249     rrd_value_t *pdp_new,
1250     rrd_value_t *pdp_temp)
1251 {
1252     unsigned long ds_idx;
1253
1254     /* in pdp_prep[].scratch[PDP_val].u_val we have collected
1255        rate*seconds which occurred up to the last run.
1256        pdp_new[] contains rate*seconds from the latest run.
1257        pdp_temp[] will contain the rate for cdp */
1258
1259     for (ds_idx = 0; ds_idx < rrd->stat_head->ds_cnt; ds_idx++) {
1260         if (process_pdp_st(rrd, ds_idx, interval, pre_int, post_int,
1261                            elapsed_pdp_st * rrd->stat_head->pdp_step,
1262                            pdp_new, pdp_temp) == -1) {
1263             return -1;
1264         }
1265 #ifdef DEBUG
1266         fprintf(stderr, "PDP UPD ds[%lu]\t"
1267                 "elapsed_pdp_st %lu\t"
1268                 "pdp_temp %10.2f\t"
1269                 "new_prep %10.2f\t"
1270                 "new_unkn_sec %5lu\n",
1271                 ds_idx,
1272                 elapsed_pdp_st,
1273                 pdp_temp[ds_idx],
1274                 rrd->pdp_prep[ds_idx].scratch[PDP_val].u_val,
1275                 rrd->pdp_prep[ds_idx].scratch[PDP_unkn_sec_cnt].u_cnt);
1276 #endif
1277     }
1278     return 0;
1279 }
1280
1281 /*
1282  * Process an update that occurs after one of the PDP moments.
1283  * Increments the PDP value, sets NAN if time greater than the
1284  * heartbeats have elapsed, processes CDEFs.
1285  *
1286  * Returns 0 on success, -1 on error.
1287  */
1288 static int process_pdp_st(
1289     rrd_t *rrd,
1290     unsigned long ds_idx,
1291     double interval,
1292     double pre_int,
1293     double post_int,
1294     long diff_pdp_st,   /* number of seconds in full steps passed since last update */
1295     rrd_value_t *pdp_new,
1296     rrd_value_t *pdp_temp)
1297 {
1298     int       i;
1299
1300     /* update pdp_prep to the current pdp_st. */
1301     double    pre_unknown = 0.0;
1302     unival   *scratch = rrd->pdp_prep[ds_idx].scratch;
1303     unsigned long mrhb = rrd->ds_def[ds_idx].par[DS_mrhb_cnt].u_cnt;
1304
1305     rpnstack_t rpnstack;    /* used for COMPUTE DS */
1306
1307     rpnstack_init(&rpnstack);
1308
1309
1310     if (isnan(pdp_new[ds_idx])) {
1311         /* a final bit of unknown to be added before calculation
1312            we use a temporary variable for this so that we
1313            don't have to turn integer lines before using the value */
1314         pre_unknown = pre_int;
1315     } else {
1316         if (isnan(scratch[PDP_val].u_val)) {
1317             scratch[PDP_val].u_val = 0;
1318         }
1319         scratch[PDP_val].u_val += pdp_new[ds_idx] / interval * pre_int;
1320     }
1321
1322     /* if too much of the pdp_prep is unknown we dump it */
1323     /* if the interval is larger thatn mrhb we get NAN */
1324     if ((interval > mrhb) ||
1325         (rrd->stat_head->pdp_step / 2.0 <
1326          (signed) scratch[PDP_unkn_sec_cnt].u_cnt)) {
1327         pdp_temp[ds_idx] = DNAN;
1328     } else {
1329         pdp_temp[ds_idx] = scratch[PDP_val].u_val /
1330             ((double) (diff_pdp_st - scratch[PDP_unkn_sec_cnt].u_cnt) -
1331              pre_unknown);
1332     }
1333
1334     /* process CDEF data sources; remember each CDEF DS can
1335      * only reference other DS with a lower index number */
1336     if (dst_conv(rrd->ds_def[ds_idx].dst) == DST_CDEF) {
1337         rpnp_t   *rpnp;
1338
1339         rpnp =
1340             rpn_expand((rpn_cdefds_t *) &(rrd->ds_def[ds_idx].par[DS_cdef]));
1341         /* substitute data values for OP_VARIABLE nodes */
1342         for (i = 0; rpnp[i].op != OP_END; i++) {
1343             if (rpnp[i].op == OP_VARIABLE) {
1344                 rpnp[i].op = OP_NUMBER;
1345                 rpnp[i].val = pdp_temp[rpnp[i].ptr];
1346             }
1347         }
1348         /* run the rpn calculator */
1349         if (rpn_calc(rpnp, &rpnstack, 0, pdp_temp, ds_idx) == -1) {
1350             free(rpnp);
1351             rpnstack_free(&rpnstack);
1352             return -1;
1353         }
1354     }
1355
1356     /* make pdp_prep ready for the next run */
1357     if (isnan(pdp_new[ds_idx])) {
1358         /* this is not realy accurate if we use subsecond data arival time
1359            should have thought of it when going subsecond resolution ...
1360            sorry next format change we will have it! */
1361         scratch[PDP_unkn_sec_cnt].u_cnt = floor(post_int);
1362         scratch[PDP_val].u_val = DNAN;
1363     } else {
1364         scratch[PDP_unkn_sec_cnt].u_cnt = 0;
1365         scratch[PDP_val].u_val = pdp_new[ds_idx] / interval * post_int;
1366     }
1367     rpnstack_free(&rpnstack);
1368     return 0;
1369 }
1370
1371 /*
1372  * Iterate over all the RRAs for a given DS and:
1373  * 1. Decide whether to schedule a smooth later
1374  * 2. Decide whether to skip updating SEASONAL and DEVSEASONAL
1375  * 3. Update the CDP
1376  *
1377  * Returns 0 on success, -1 on error
1378  */
1379 static int update_all_cdp_prep(
1380     rrd_t *rrd,
1381     unsigned long *rra_step_cnt,
1382     unsigned long rra_begin,
1383     rrd_file_t *rrd_file,
1384     unsigned long elapsed_pdp_st,
1385     unsigned long proc_pdp_cnt,
1386     rrd_value_t **last_seasonal_coef,
1387     rrd_value_t **seasonal_coef,
1388     rrd_value_t *pdp_temp,
1389     unsigned long *skip_update,
1390     int *schedule_smooth)
1391 {
1392     unsigned long rra_idx;
1393
1394     /* index into the CDP scratch array */
1395     enum cf_en current_cf;
1396     unsigned long rra_start;
1397
1398     /* number of rows to be updated in an RRA for a data value. */
1399     unsigned long start_pdp_offset;
1400
1401     rra_start = rra_begin;
1402     for (rra_idx = 0; rra_idx < rrd->stat_head->rra_cnt; rra_idx++) {
1403         current_cf = cf_conv(rrd->rra_def[rra_idx].cf_nam);
1404         start_pdp_offset =
1405             rrd->rra_def[rra_idx].pdp_cnt -
1406             proc_pdp_cnt % rrd->rra_def[rra_idx].pdp_cnt;
1407         skip_update[rra_idx] = 0;
1408         if (start_pdp_offset <= elapsed_pdp_st) {
1409             rra_step_cnt[rra_idx] = (elapsed_pdp_st - start_pdp_offset) /
1410                 rrd->rra_def[rra_idx].pdp_cnt + 1;
1411         } else {
1412             rra_step_cnt[rra_idx] = 0;
1413         }
1414
1415         if (current_cf == CF_SEASONAL || current_cf == CF_DEVSEASONAL) {
1416             /* If this is a bulk update, we need to skip ahead in the seasonal arrays
1417              * so that they will be correct for the next observed value; note that for
1418              * the bulk update itself, no update will occur to DEVSEASONAL or SEASONAL;
1419              * futhermore, HWPREDICT and DEVPREDICT will be set to DNAN. */
1420             if (rra_step_cnt[rra_idx] > 1) {
1421                 skip_update[rra_idx] = 1;
1422                 lookup_seasonal(rrd, rra_idx, rra_start, rrd_file,
1423                                 elapsed_pdp_st, last_seasonal_coef);
1424                 lookup_seasonal(rrd, rra_idx, rra_start, rrd_file,
1425                                 elapsed_pdp_st + 1, seasonal_coef);
1426             }
1427             /* periodically run a smoother for seasonal effects */
1428             if (do_schedule_smooth(rrd, rra_idx, elapsed_pdp_st)) {
1429 #ifdef DEBUG
1430                 fprintf(stderr,
1431                         "schedule_smooth: cur_row %lu, elapsed_pdp_st %lu, smooth idx %lu\n",
1432                         rrd->rra_ptr[rra_idx].cur_row, elapsed_pdp_st,
1433                         rrd->rra_def[rra_idx].par[RRA_seasonal_smooth_idx].
1434                         u_cnt);
1435 #endif
1436                 *schedule_smooth = 1;
1437             }
1438         }
1439         if (rrd_test_error())
1440             return -1;
1441
1442         if (update_cdp_prep
1443             (rrd, elapsed_pdp_st, start_pdp_offset, rra_step_cnt, rra_idx,
1444              pdp_temp, *last_seasonal_coef, *seasonal_coef,
1445              current_cf) == -1) {
1446             return -1;
1447         }
1448         rra_start +=
1449             rrd->rra_def[rra_idx].row_cnt * rrd->stat_head->ds_cnt *
1450             sizeof(rrd_value_t);
1451     }
1452     return 0;
1453 }
1454
1455 /* 
1456  * Are we due for a smooth? Also increments our position in the burn-in cycle.
1457  */
1458 static int do_schedule_smooth(
1459     rrd_t *rrd,
1460     unsigned long rra_idx,
1461     unsigned long elapsed_pdp_st)
1462 {
1463     unsigned long cdp_idx = rra_idx * (rrd->stat_head->ds_cnt);
1464     unsigned long cur_row = rrd->rra_ptr[rra_idx].cur_row;
1465     unsigned long row_cnt = rrd->rra_def[rra_idx].row_cnt;
1466     unsigned long seasonal_smooth_idx =
1467         rrd->rra_def[rra_idx].par[RRA_seasonal_smooth_idx].u_cnt;
1468     unsigned long *init_seasonal =
1469         &(rrd->cdp_prep[cdp_idx].scratch[CDP_init_seasonal].u_cnt);
1470
1471     /* Need to use first cdp parameter buffer to track burnin (burnin requires
1472      * a specific smoothing schedule).  The CDP_init_seasonal parameter is
1473      * really an RRA level, not a data source within RRA level parameter, but
1474      * the rra_def is read only for rrd_update (not flushed to disk). */
1475     if (*init_seasonal > BURNIN_CYCLES) {
1476         /* someone has no doubt invented a trick to deal with this wrap around,
1477          * but at least this code is clear. */
1478         if (seasonal_smooth_idx > cur_row) {
1479             /* here elapsed_pdp_st = rra_step_cnt[rra_idx] because of 1-1 mapping
1480              * between PDP and CDP */
1481             return (cur_row + elapsed_pdp_st >= seasonal_smooth_idx);
1482         }
1483         /* can't rely on negative numbers because we are working with
1484          * unsigned values */
1485         return (cur_row + elapsed_pdp_st >= row_cnt
1486                 && cur_row + elapsed_pdp_st >= row_cnt + seasonal_smooth_idx);
1487     }
1488     /* mark off one of the burn-in cycles */
1489     return (cur_row + elapsed_pdp_st >= row_cnt && ++(*init_seasonal));
1490 }
1491
1492 /*
1493  * For a given RRA, iterate over the data sources and call the appropriate
1494  * consolidation function.
1495  *
1496  * Returns 0 on success, -1 on error.
1497  */
1498 static int update_cdp_prep(
1499     rrd_t *rrd,
1500     unsigned long elapsed_pdp_st,
1501     unsigned long start_pdp_offset,
1502     unsigned long *rra_step_cnt,
1503     int rra_idx,
1504     rrd_value_t *pdp_temp,
1505     rrd_value_t *last_seasonal_coef,
1506     rrd_value_t *seasonal_coef,
1507     int current_cf)
1508 {
1509     unsigned long ds_idx, cdp_idx;
1510
1511     /* update CDP_PREP areas */
1512     /* loop over data soures within each RRA */
1513     for (ds_idx = 0; ds_idx < rrd->stat_head->ds_cnt; ds_idx++) {
1514
1515         cdp_idx = rra_idx * rrd->stat_head->ds_cnt + ds_idx;
1516
1517         if (rrd->rra_def[rra_idx].pdp_cnt > 1) {
1518             update_cdp(rrd->cdp_prep[cdp_idx].scratch, current_cf,
1519                        pdp_temp[ds_idx], rra_step_cnt[rra_idx],
1520                        elapsed_pdp_st, start_pdp_offset,
1521                        rrd->rra_def[rra_idx].pdp_cnt,
1522                        rrd->rra_def[rra_idx].par[RRA_cdp_xff_val].u_val,
1523                        rra_idx, ds_idx);
1524         } else {
1525             /* Nothing to consolidate if there's one PDP per CDP. However, if
1526              * we've missed some PDPs, let's update null counters etc. */
1527             if (elapsed_pdp_st > 2) {
1528                 reset_cdp(rrd, elapsed_pdp_st, pdp_temp, last_seasonal_coef,
1529                           seasonal_coef, rra_idx, ds_idx, cdp_idx,
1530                           current_cf);
1531             }
1532         }
1533
1534         if (rrd_test_error())
1535             return -1;
1536     }                   /* endif data sources loop */
1537     return 0;
1538 }
1539
1540 /*
1541  * Given the new reading (pdp_temp_val), update or initialize the CDP value,
1542  * primary value, secondary value, and # of unknowns.
1543  */
1544 static void update_cdp(
1545     unival *scratch,
1546     int current_cf,
1547     rrd_value_t pdp_temp_val,
1548     unsigned long rra_step_cnt,
1549     unsigned long elapsed_pdp_st,
1550     unsigned long start_pdp_offset,
1551     unsigned long pdp_cnt,
1552     rrd_value_t xff,
1553     int i,
1554     int ii)
1555 {
1556     /* shorthand variables */
1557     rrd_value_t *cdp_val = &scratch[CDP_val].u_val;
1558     rrd_value_t *cdp_primary_val = &scratch[CDP_primary_val].u_val;
1559     rrd_value_t *cdp_secondary_val = &scratch[CDP_secondary_val].u_val;
1560     unsigned long *cdp_unkn_pdp_cnt = &scratch[CDP_unkn_pdp_cnt].u_cnt;
1561
1562     if (rra_step_cnt) {
1563         /* If we are in this block, as least 1 CDP value will be written to
1564          * disk, this is the CDP_primary_val entry. If more than 1 value needs
1565          * to be written, then the "fill in" value is the CDP_secondary_val
1566          * entry. */
1567         if (isnan(pdp_temp_val)) {
1568             *cdp_unkn_pdp_cnt += start_pdp_offset;
1569             *cdp_secondary_val = DNAN;
1570         } else {
1571             /* CDP_secondary value is the RRA "fill in" value for intermediary
1572              * CDP data entries. No matter the CF, the value is the same because
1573              * the average, max, min, and last of a list of identical values is
1574              * the same, namely, the value itself. */
1575             *cdp_secondary_val = pdp_temp_val;
1576         }
1577
1578         if (*cdp_unkn_pdp_cnt > pdp_cnt * xff) {
1579             *cdp_primary_val = DNAN;
1580             if (current_cf == CF_AVERAGE) {
1581                 *cdp_val =
1582                     initialize_average_carry_over(pdp_temp_val,
1583                                                   elapsed_pdp_st,
1584                                                   start_pdp_offset, pdp_cnt);
1585             } else {
1586                 *cdp_val = pdp_temp_val;
1587             }
1588         } else {
1589             initialize_cdp_val(scratch, current_cf, pdp_temp_val,
1590                                elapsed_pdp_st, start_pdp_offset, pdp_cnt);
1591         }               /* endif meets xff value requirement for a valid value */
1592         /* initialize carry over CDP_unkn_pdp_cnt, this must after CDP_primary_val
1593          * is set because CDP_unkn_pdp_cnt is required to compute that value. */
1594         if (isnan(pdp_temp_val))
1595             *cdp_unkn_pdp_cnt = (elapsed_pdp_st - start_pdp_offset) % pdp_cnt;
1596         else
1597             *cdp_unkn_pdp_cnt = 0;
1598     } else {            /* rra_step_cnt[i]  == 0 */
1599
1600 #ifdef DEBUG
1601         if (isnan(*cdp_val)) {
1602             fprintf(stderr, "schedule CDP_val update, RRA %d DS %d, DNAN\n",
1603                     i, ii);
1604         } else {
1605             fprintf(stderr, "schedule CDP_val update, RRA %d DS %d, %10.2f\n",
1606                     i, ii, *cdp_val);
1607         }
1608 #endif
1609         if (isnan(pdp_temp_val)) {
1610             *cdp_unkn_pdp_cnt += elapsed_pdp_st;
1611         } else {
1612             *cdp_val =
1613                 calculate_cdp_val(*cdp_val, pdp_temp_val, elapsed_pdp_st,
1614                                   current_cf, i, ii);
1615         }
1616     }
1617 }
1618
1619 /*
1620  * Set the CDP_primary_val and CDP_val to the appropriate initial value based
1621  * on the type of consolidation function.
1622  */
1623 static void initialize_cdp_val(
1624     unival *scratch,
1625     int current_cf,
1626     rrd_value_t pdp_temp_val,
1627     unsigned long elapsed_pdp_st,
1628     unsigned long start_pdp_offset,
1629     unsigned long pdp_cnt)
1630 {
1631     rrd_value_t cum_val, cur_val;
1632
1633     switch (current_cf) {
1634     case CF_AVERAGE:
1635         cum_val = IFDNAN(scratch[CDP_val].u_val, 0.0);
1636         cur_val = IFDNAN(pdp_temp_val, 0.0);
1637         scratch[CDP_primary_val].u_val =
1638             (cum_val + cur_val * start_pdp_offset) /
1639             (pdp_cnt - scratch[CDP_unkn_pdp_cnt].u_cnt);
1640         scratch[CDP_val].u_val =
1641             initialize_average_carry_over(pdp_temp_val, elapsed_pdp_st,
1642                                           start_pdp_offset, pdp_cnt);
1643         break;
1644     case CF_MAXIMUM:
1645         cum_val = IFDNAN(scratch[CDP_val].u_val, -DINF);
1646         cur_val = IFDNAN(pdp_temp_val, -DINF);
1647 #if 0
1648 #ifdef DEBUG
1649         if (isnan(scratch[CDP_val].u_val) && isnan(pdp_temp)) {
1650             fprintf(stderr,
1651                     "RRA %lu, DS %lu, both CDP_val and pdp_temp are DNAN!",
1652                     i, ii);
1653             exit(-1);
1654         }
1655 #endif
1656 #endif
1657         if (cur_val > cum_val)
1658             scratch[CDP_primary_val].u_val = cur_val;
1659         else
1660             scratch[CDP_primary_val].u_val = cum_val;
1661         /* initialize carry over value */
1662         scratch[CDP_val].u_val = pdp_temp_val;
1663         break;
1664     case CF_MINIMUM:
1665         cum_val = IFDNAN(scratch[CDP_val].u_val, DINF);
1666         cur_val = IFDNAN(pdp_temp_val, DINF);
1667 #if 0
1668 #ifdef DEBUG
1669         if (isnan(scratch[CDP_val].u_val) && isnan(pdp_temp)) {
1670             fprintf(stderr,
1671                     "RRA %lu, DS %lu, both CDP_val and pdp_temp are DNAN!", i,
1672                     ii);
1673             exit(-1);
1674         }
1675 #endif
1676 #endif
1677         if (cur_val < cum_val)
1678             scratch[CDP_primary_val].u_val = cur_val;
1679         else
1680             scratch[CDP_primary_val].u_val = cum_val;
1681         /* initialize carry over value */
1682         scratch[CDP_val].u_val = pdp_temp_val;
1683         break;
1684     case CF_LAST:
1685     default:
1686         scratch[CDP_primary_val].u_val = pdp_temp_val;
1687         /* initialize carry over value */
1688         scratch[CDP_val].u_val = pdp_temp_val;
1689         break;
1690     }
1691 }
1692
1693 /*
1694  * Update the consolidation function for Holt-Winters functions as
1695  * well as other functions that don't actually consolidate multiple
1696  * PDPs.
1697  */
1698 static void reset_cdp(
1699     rrd_t *rrd,
1700     unsigned long elapsed_pdp_st,
1701     rrd_value_t *pdp_temp,
1702     rrd_value_t *last_seasonal_coef,
1703     rrd_value_t *seasonal_coef,
1704     int rra_idx,
1705     int ds_idx,
1706     int cdp_idx,
1707     enum cf_en current_cf)
1708 {
1709     unival   *scratch = rrd->cdp_prep[cdp_idx].scratch;
1710
1711     switch (current_cf) {
1712     case CF_AVERAGE:
1713     default:
1714         scratch[CDP_primary_val].u_val = pdp_temp[ds_idx];
1715         scratch[CDP_secondary_val].u_val = pdp_temp[ds_idx];
1716         break;
1717     case CF_SEASONAL:
1718     case CF_DEVSEASONAL:
1719         /* need to update cached seasonal values, so they are consistent
1720          * with the bulk update */
1721         /* WARNING: code relies on the fact that CDP_hw_last_seasonal and
1722          * CDP_last_deviation are the same. */
1723         scratch[CDP_hw_last_seasonal].u_val = last_seasonal_coef[ds_idx];
1724         scratch[CDP_hw_seasonal].u_val = seasonal_coef[ds_idx];
1725         break;
1726     case CF_HWPREDICT:
1727     case CF_MHWPREDICT:
1728         /* need to update the null_count and last_null_count.
1729          * even do this for non-DNAN pdp_temp because the
1730          * algorithm is not learning from batch updates. */
1731         scratch[CDP_null_count].u_cnt += elapsed_pdp_st;
1732         scratch[CDP_last_null_count].u_cnt += elapsed_pdp_st - 1;
1733         /* fall through */
1734     case CF_DEVPREDICT:
1735         scratch[CDP_primary_val].u_val = DNAN;
1736         scratch[CDP_secondary_val].u_val = DNAN;
1737         break;
1738     case CF_FAILURES:
1739         /* do not count missed bulk values as failures */
1740         scratch[CDP_primary_val].u_val = 0;
1741         scratch[CDP_secondary_val].u_val = 0;
1742         /* need to reset violations buffer.
1743          * could do this more carefully, but for now, just
1744          * assume a bulk update wipes away all violations. */
1745         erase_violations(rrd, cdp_idx, rra_idx);
1746         break;
1747     }
1748 }
1749
1750 static rrd_value_t initialize_average_carry_over(
1751     rrd_value_t pdp_temp_val,
1752     unsigned long elapsed_pdp_st,
1753     unsigned long start_pdp_offset,
1754     unsigned long pdp_cnt)
1755 {
1756     /* initialize carry over value */
1757     if (isnan(pdp_temp_val)) {
1758         return DNAN;
1759     }
1760     return pdp_temp_val * ((elapsed_pdp_st - start_pdp_offset) % pdp_cnt);
1761 }
1762
1763 /*
1764  * Update or initialize a CDP value based on the consolidation
1765  * function.
1766  *
1767  * Returns the new value.
1768  */
1769 static rrd_value_t calculate_cdp_val(
1770     rrd_value_t cdp_val,
1771     rrd_value_t pdp_temp_val,
1772     unsigned long elapsed_pdp_st,
1773     int current_cf,
1774 #ifdef DEBUG
1775     int i,
1776     int ii
1777 #else
1778     int UNUSED(i),
1779     int UNUSED(ii)
1780 #endif
1781     )
1782 {
1783     if (isnan(cdp_val)) {
1784         if (current_cf == CF_AVERAGE) {
1785             pdp_temp_val *= elapsed_pdp_st;
1786         }
1787 #ifdef DEBUG
1788         fprintf(stderr, "Initialize CDP_val for RRA %d DS %d: %10.2f\n",
1789                 i, ii, pdp_temp_val);
1790 #endif
1791         return pdp_temp_val;
1792     }
1793     if (current_cf == CF_AVERAGE)
1794         return cdp_val + pdp_temp_val * elapsed_pdp_st;
1795     if (current_cf == CF_MINIMUM)
1796         return (pdp_temp_val < cdp_val) ? pdp_temp_val : cdp_val;
1797     if (current_cf == CF_MAXIMUM)
1798         return (pdp_temp_val > cdp_val) ? pdp_temp_val : cdp_val;
1799
1800     return pdp_temp_val;
1801 }
1802
1803 /*
1804  * For each RRA, update the seasonal values and then call update_aberrant_CF
1805  * for each data source.
1806  *
1807  * Return 0 on success, -1 on error.
1808  */
1809 static int update_aberrant_cdps(
1810     rrd_t *rrd,
1811     rrd_file_t *rrd_file,
1812     unsigned long rra_begin,
1813     unsigned long elapsed_pdp_st,
1814     rrd_value_t *pdp_temp,
1815     rrd_value_t **seasonal_coef)
1816 {
1817     unsigned long rra_idx, ds_idx, j;
1818
1819     /* number of PDP steps since the last update that
1820      * are assigned to the first CDP to be generated
1821      * since the last update. */
1822     unsigned short scratch_idx;
1823     unsigned long rra_start;
1824     enum cf_en current_cf;
1825
1826     /* this loop is only entered if elapsed_pdp_st < 3 */
1827     for (j = elapsed_pdp_st, scratch_idx = CDP_primary_val;
1828          j > 0 && j < 3; j--, scratch_idx = CDP_secondary_val) {
1829         rra_start = rra_begin;
1830         for (rra_idx = 0; rra_idx < rrd->stat_head->rra_cnt; rra_idx++) {
1831             if (rrd->rra_def[rra_idx].pdp_cnt == 1) {
1832                 current_cf = cf_conv(rrd->rra_def[rra_idx].cf_nam);
1833                 if (current_cf == CF_SEASONAL || current_cf == CF_DEVSEASONAL) {
1834                     if (scratch_idx == CDP_primary_val) {
1835                         lookup_seasonal(rrd, rra_idx, rra_start, rrd_file,
1836                                         elapsed_pdp_st + 1, seasonal_coef);
1837                     } else {
1838                         lookup_seasonal(rrd, rra_idx, rra_start, rrd_file,
1839                                         elapsed_pdp_st + 2, seasonal_coef);
1840                     }
1841                 }
1842                 if (rrd_test_error())
1843                     return -1;
1844                 /* loop over data soures within each RRA */
1845                 for (ds_idx = 0; ds_idx < rrd->stat_head->ds_cnt; ds_idx++) {
1846                     update_aberrant_CF(rrd, pdp_temp[ds_idx], current_cf,
1847                                        rra_idx * (rrd->stat_head->ds_cnt) +
1848                                        ds_idx, rra_idx, ds_idx, scratch_idx,
1849                                        *seasonal_coef);
1850                 }
1851             }
1852             rra_start += rrd->rra_def[rra_idx].row_cnt
1853                 * rrd->stat_head->ds_cnt * sizeof(rrd_value_t);
1854         }
1855     }
1856     return 0;
1857 }
1858
1859 /* 
1860  * Move sequentially through the file, writing one RRA at a time.  Note this
1861  * architecture divorces the computation of CDP with flushing updated RRA
1862  * entries to disk.
1863  *
1864  * Return 0 on success, -1 on error.
1865  */
1866 static int write_to_rras(
1867     rrd_t *rrd,
1868     rrd_file_t *rrd_file,
1869     unsigned long *rra_step_cnt,
1870     unsigned long rra_begin,
1871     time_t current_time,
1872     unsigned long *skip_update,
1873     rrd_info_t ** pcdp_summary)
1874 {
1875     unsigned long rra_idx;
1876     unsigned long rra_start;
1877     time_t    rra_time = 0; /* time of update for a RRA */
1878
1879     unsigned long ds_cnt = rrd->stat_head->ds_cnt;
1880     
1881     /* Ready to write to disk */
1882     rra_start = rra_begin;
1883
1884     for (rra_idx = 0; rra_idx < rrd->stat_head->rra_cnt; rra_idx++) {
1885         rra_def_t *rra_def = &rrd->rra_def[rra_idx];
1886         rra_ptr_t *rra_ptr = &rrd->rra_ptr[rra_idx];
1887
1888         /* for cdp_prep */
1889         unsigned short scratch_idx;
1890         unsigned long step_subtract;
1891
1892         for (scratch_idx = CDP_primary_val,
1893                  step_subtract = 1;
1894              rra_step_cnt[rra_idx] > 0;
1895              rra_step_cnt[rra_idx]--,
1896                  scratch_idx = CDP_secondary_val,
1897                  step_subtract = 2) {
1898
1899             off_t rra_pos_new;
1900 #ifdef DEBUG
1901             fprintf(stderr, "  -- RRA Preseek %ld\n", rrd_file->pos);
1902 #endif
1903             /* increment, with wrap-around */
1904             if (++rra_ptr->cur_row >= rra_def->row_cnt)
1905               rra_ptr->cur_row = 0;
1906
1907             /* we know what our position should be */
1908             rra_pos_new = rra_start
1909               + ds_cnt * rra_ptr->cur_row * sizeof(rrd_value_t);
1910
1911             /* re-seek if the position is wrong or we wrapped around */
1912             if ((size_t)rra_pos_new != rrd_file->pos) {
1913                 if (rrd_seek(rrd_file, rra_pos_new, SEEK_SET) != 0) {
1914                     rrd_set_error("seek error in rrd");
1915                     return -1;
1916                 }
1917             }
1918 #ifdef DEBUG
1919             fprintf(stderr, "  -- RRA Postseek %ld\n", rrd_file->pos);
1920 #endif
1921
1922             if (skip_update[rra_idx])
1923                 continue;
1924
1925             if (*pcdp_summary != NULL) {
1926                 unsigned long step_time = rra_def->pdp_cnt * rrd->stat_head->pdp_step;
1927
1928                 rra_time = (current_time - current_time % step_time)
1929                     - ((rra_step_cnt[rra_idx] - step_subtract) * step_time);
1930             }
1931
1932             if (write_RRA_row
1933                 (rrd_file, rrd, rra_idx, scratch_idx,
1934                  pcdp_summary, rra_time) == -1)
1935                 return -1;
1936
1937             rrd_notify_row(rrd_file, rra_idx, rra_pos_new, rra_time);
1938         }
1939
1940         rra_start += rra_def->row_cnt * ds_cnt * sizeof(rrd_value_t);
1941     } /* RRA LOOP */
1942
1943     return 0;
1944 }
1945
1946 /*
1947  * Write out one row of values (one value per DS) to the archive.
1948  *
1949  * Returns 0 on success, -1 on error.
1950  */
1951 static int write_RRA_row(
1952     rrd_file_t *rrd_file,
1953     rrd_t *rrd,
1954     unsigned long rra_idx,
1955     unsigned short CDP_scratch_idx,
1956     rrd_info_t ** pcdp_summary,
1957     time_t rra_time)
1958 {
1959     unsigned long ds_idx, cdp_idx;
1960     rrd_infoval_t iv;
1961
1962     for (ds_idx = 0; ds_idx < rrd->stat_head->ds_cnt; ds_idx++) {
1963         /* compute the cdp index */
1964         cdp_idx = rra_idx * (rrd->stat_head->ds_cnt) + ds_idx;
1965 #ifdef DEBUG
1966         fprintf(stderr, "  -- RRA WRITE VALUE %e, at %ld CF:%s\n",
1967                 rrd->cdp_prep[cdp_idx].scratch[CDP_scratch_idx].u_val,
1968                 rrd_file->pos, rrd->rra_def[rra_idx].cf_nam);
1969 #endif
1970         if (*pcdp_summary != NULL) {
1971             iv.u_val = rrd->cdp_prep[cdp_idx].scratch[CDP_scratch_idx].u_val;
1972             /* append info to the return hash */
1973             *pcdp_summary = rrd_info_push(*pcdp_summary,
1974                                           sprintf_alloc
1975                                           ("[%lli]RRA[%s][%lu]DS[%s]", 
1976                                            (long long)rra_time,
1977                                            rrd->rra_def[rra_idx].cf_nam,
1978                                            rrd->rra_def[rra_idx].pdp_cnt,
1979                                            rrd->ds_def[ds_idx].ds_nam),
1980                                            RD_I_VAL, iv);
1981         }
1982         if (rrd_write(rrd_file,
1983                       &(rrd->cdp_prep[cdp_idx].scratch[CDP_scratch_idx].
1984                         u_val), sizeof(rrd_value_t)) != sizeof(rrd_value_t)) {
1985             rrd_set_error("writing rrd: %s", rrd_strerror(errno));
1986             return -1;
1987         }
1988     }
1989     return 0;
1990 }
1991
1992 /*
1993  * Call apply_smoother for all DEVSEASONAL and SEASONAL RRAs.
1994  *
1995  * Returns 0 on success, -1 otherwise
1996  */
1997 static int smooth_all_rras(
1998     rrd_t *rrd,
1999     rrd_file_t *rrd_file,
2000     unsigned long rra_begin)
2001 {
2002     unsigned long rra_start = rra_begin;
2003     unsigned long rra_idx;
2004
2005     for (rra_idx = 0; rra_idx < rrd->stat_head->rra_cnt; ++rra_idx) {
2006         if (cf_conv(rrd->rra_def[rra_idx].cf_nam) == CF_DEVSEASONAL ||
2007             cf_conv(rrd->rra_def[rra_idx].cf_nam) == CF_SEASONAL) {
2008 #ifdef DEBUG
2009             fprintf(stderr, "Running smoother for rra %lu\n", rra_idx);
2010 #endif
2011             apply_smoother(rrd, rra_idx, rra_start, rrd_file);
2012             if (rrd_test_error())
2013                 return -1;
2014         }
2015         rra_start += rrd->rra_def[rra_idx].row_cnt
2016             * rrd->stat_head->ds_cnt * sizeof(rrd_value_t);
2017     }
2018     return 0;
2019 }
2020
2021 #ifndef HAVE_MMAP
2022 /*
2023  * Flush changes to disk (unless we're using mmap)
2024  *
2025  * Returns 0 on success, -1 otherwise
2026  */
2027 static int write_changes_to_disk(
2028     rrd_t *rrd,
2029     rrd_file_t *rrd_file,
2030     int version)
2031 {
2032     /* we just need to write back the live header portion now */
2033     if (rrd_seek(rrd_file, (sizeof(stat_head_t)
2034                             + sizeof(ds_def_t) * rrd->stat_head->ds_cnt
2035                             + sizeof(rra_def_t) * rrd->stat_head->rra_cnt),
2036                  SEEK_SET) != 0) {
2037         rrd_set_error("seek rrd for live header writeback");
2038         return -1;
2039     }
2040     if (version >= 3) {
2041         if (rrd_write(rrd_file, rrd->live_head,
2042                       sizeof(live_head_t) * 1) != sizeof(live_head_t) * 1) {
2043             rrd_set_error("rrd_write live_head to rrd");
2044             return -1;
2045         }
2046     } else {
2047         if (rrd_write(rrd_file, rrd->legacy_last_up,
2048                       sizeof(time_t) * 1) != sizeof(time_t) * 1) {
2049             rrd_set_error("rrd_write live_head to rrd");
2050             return -1;
2051         }
2052     }
2053
2054
2055     if (rrd_write(rrd_file, rrd->pdp_prep,
2056                   sizeof(pdp_prep_t) * rrd->stat_head->ds_cnt)
2057         != (ssize_t) (sizeof(pdp_prep_t) * rrd->stat_head->ds_cnt)) {
2058         rrd_set_error("rrd_write pdp_prep to rrd");
2059         return -1;
2060     }
2061
2062     if (rrd_write(rrd_file, rrd->cdp_prep,
2063                   sizeof(cdp_prep_t) * rrd->stat_head->rra_cnt *
2064                   rrd->stat_head->ds_cnt)
2065         != (ssize_t) (sizeof(cdp_prep_t) * rrd->stat_head->rra_cnt *
2066                       rrd->stat_head->ds_cnt)) {
2067
2068         rrd_set_error("rrd_write cdp_prep to rrd");
2069         return -1;
2070     }
2071
2072     if (rrd_write(rrd_file, rrd->rra_ptr,
2073                   sizeof(rra_ptr_t) * rrd->stat_head->rra_cnt)
2074         != (ssize_t) (sizeof(rra_ptr_t) * rrd->stat_head->rra_cnt)) {
2075         rrd_set_error("rrd_write rra_ptr to rrd");
2076         return -1;
2077     }
2078     return 0;
2079 }
2080 #endif