Coverage Report

Created: 2026-08-31 06:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opensips/timer.c
Line
Count
Source
1
/*
2
 * Copyright (C) 2014 OpenSIPS Solutions
3
 * Copyright (C) 2007 Voice Sistem SRL
4
 * Copyright (C) 2001-2003 FhG Fokus
5
 *
6
 * This file is part of opensips, a free SIP server.
7
 *
8
 * opensips is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 2 of the License, or
11
 * (at your option) any later version
12
 *
13
 * opensips is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
21
 *
22
 * History:
23
 * --------
24
 *  2003-03-19  replaced all the mallocs/frees w/ pkg_malloc/pkg_free (andrei)
25
 *  2003-03-29  cleaning pkg_mallocs introduced (jiri)
26
 *  2007-02-02  timer with resolution of microseconds added (bogdan)
27
 *  2014-09-11  timer tasks distributed via reactors (bogdan)
28
 *  2014-10-03  drop all timer processes (aside keeper) (bogdan)
29
 */
30
31
/*!
32
 * \file
33
 * \brief Timer handling
34
 */
35
36
/* keep this first as it needs to include some glib h file with
37
 * special defines enabled (mainly sys/types.h) */
38
#include "reactor.h"
39
#include "pt_load.h"
40
#include "locking.h"
41
42
#include <unistd.h>
43
#include <fcntl.h>
44
#include <sys/select.h>
45
#include <sys/time.h>
46
#include <sys/types.h>
47
#include <unistd.h>
48
49
#include "action.h"
50
#include "timer.h"
51
#include "dprint.h"
52
#include "error.h"
53
#include "ipc.h"
54
#include "config.h"
55
#include "sr_module.h"
56
#include "daemonize.h"
57
#include "cfg_reload.h"
58
#include "profiling.h"
59
#include "mem/mem.h"
60
#include "mem/shm_mem.h"
61
62
#include <stdlib.h>
63
64
/* define internal timer to 10 milliseconds */
65
0
#define ITIMER_TICK 10000
66
67
/* try to synchronize with system time every 5 second(s) */
68
0
#define TIMER_SYNC_TICKS 5000000
69
70
/* synchronize if drift is greater than internal timer tick */
71
0
#define TIMER_MAX_DRIFT_TICKS ITIMER_TICK
72
73
/* list with all the registered timers */
74
static struct os_timer *timer_list = NULL;
75
76
/* list with all the registered utimers */
77
static struct os_timer *utimer_list = NULL;
78
79
static unsigned int  *jiffies=0;
80
static utime_t       *ujiffies=0;
81
static utime_t       *ijiffies=0;
82
/* the value of the last timer drift */
83
static utime_t       *ijiffies_drift=0;
84
/* the time of the last timer drift */
85
static utime_t       *ijiffies_drift_base=0;
86
static unsigned short timer_id=0;
87
static int            timer_pipe[2];
88
static struct scaling_profile *s_profile=NULL;
89
90
static gen_lock_t      *tr_list_lock = NULL;
91
static struct os_timer **tr_timer_list = NULL;
92
static struct os_timer **tr_timer_pending = NULL;
93
94
int timer_fd_out = -1 ;
95
char *timer_auto_scaling_profile = NULL;
96
int timer_workers_no = 1;
97
98
99
100
/* counts the number of timer processes to start with; this number may 
101
 * change during runtime due auto-scaling */
102
int timer_count_processes(unsigned int *extra)
103
0
{
104
0
  if (extra) *extra = 0;
105
106
0
  if (s_profile && extra) {
107
    /* how many can be forked over th number of procs to start with ?*/
108
0
    if (s_profile->max_procs > timer_workers_no)
109
0
      *extra = s_profile->max_procs - timer_workers_no;
110
0
  }
111
112
0
  return 2/*keeper & trigger*/ + timer_workers_no /*workers to start with*/;
113
0
}
114
115
116
/* ret 0 on success, <0 on error*/
117
int init_timer(void)
118
0
{
119
0
  int optval;
120
121
0
  jiffies  = shm_malloc(sizeof(unsigned int));
122
0
  ujiffies = shm_malloc(sizeof(utime_t));
123
0
  ijiffies = shm_malloc(sizeof(utime_t));
124
0
  ijiffies_drift = shm_malloc(sizeof(utime_t));
125
0
  ijiffies_drift_base = shm_malloc(sizeof(utime_t));
126
127
0
  if (jiffies==0 || ujiffies==0 || ijiffies==0 ||
128
0
    ijiffies_drift==0 || ijiffies_drift_base==0){
129
0
    LM_CRIT("could not init jiffies\n");
130
0
    return E_OUT_OF_MEM;
131
0
  }
132
133
0
  if (UTIMER_TICK>TIMER_TICK*1000000) {
134
0
    LM_CRIT("UTIMER > TIMER!!\n");
135
0
    return E_CFG;
136
0
  }
137
138
0
  if ( ((TIMER_TICK*1000000) % UTIMER_TICK)!=0 ) {
139
0
    LM_CRIT("TIMER must be multiple of UTIMER!!\n");
140
0
    return E_CFG;
141
0
  }
142
143
0
  *jiffies=0;
144
0
  *ujiffies=0;
145
0
  *ijiffies=0;
146
0
  *ijiffies_drift=0;
147
0
  *ijiffies_drift_base=0;
148
149
  /* create the pipe for dispatching the timer jobs */
150
0
  if ( pipe(timer_pipe)!=0 ) {
151
0
    LM_ERR("failed to create time pipe (%s)!\n",strerror(errno));
152
0
    return E_UNSPEC;
153
0
  }
154
  /* make reading fd non-blocking */
155
0
  optval=fcntl(timer_pipe[0], F_GETFL);
156
0
  if (optval==-1){
157
0
    LM_ERR("fcntl failed: (%d) %s\n", errno, strerror(errno));
158
0
    return E_UNSPEC;
159
0
  }
160
0
  if (fcntl(timer_pipe[0],F_SETFL,optval|O_NONBLOCK)==-1){
161
0
    LM_ERR("set non-blocking failed: (%d) %s\n",
162
0
      errno, strerror(errno));
163
0
    return E_UNSPEC;
164
0
  }
165
  /* make visible the "read" part of the pipe */
166
0
  timer_fd_out = timer_pipe[0];
167
168
0
  if (timer_auto_scaling_profile) {
169
0
    s_profile = get_scaling_profile(timer_auto_scaling_profile);
170
0
    if ( s_profile==NULL) {
171
0
      LM_ERR("undefined auto-scaling profile <%s> for timers\n",
172
0
        timer_auto_scaling_profile);
173
0
      return E_UNSPEC;
174
0
    }
175
0
    auto_scaling_enabled = 1;
176
0
  }
177
178
  /* lock to protect the list of timer task for timer routes */
179
0
  tr_list_lock = lock_alloc();
180
0
  if (tr_list_lock==0) {
181
0
    LM_ERR("failed to alloc lock\n");
182
0
    return E_UNSPEC;
183
0
  }
184
185
0
  if (lock_init(tr_list_lock)==0) {
186
0
    LM_ERR("failed to init lock\n");
187
0
    return E_UNSPEC;
188
0
  }
189
190
0
  tr_timer_list = (struct os_timer**)shm_malloc(sizeof(struct os_timer*));
191
0
  if (tr_timer_list==NULL) {
192
0
    LM_ERR("failed to alloc timer holder\n");
193
0
    return E_UNSPEC;
194
0
  }
195
0
  *tr_timer_list = NULL;
196
197
0
  tr_timer_pending = (struct os_timer**)shm_malloc(sizeof(struct os_timer*));
198
0
  if (tr_timer_pending==NULL) {
199
0
    LM_ERR("failed to alloc timer pending holder\n");
200
0
    return E_UNSPEC;
201
0
  }
202
0
  *tr_timer_pending = NULL;
203
204
205
0
  return 0;
206
0
}
207
208
209
210
void destroy_timer(void)
211
0
{
212
0
  if (jiffies){
213
0
    shm_free(jiffies); jiffies=0;
214
0
    shm_free(ujiffies); ujiffies=0;
215
0
  }
216
0
}
217
218
219
220
static inline struct os_timer* new_os_timer(char *label, unsigned short flags,
221
            timer_function f, void* param, unsigned int interval)
222
0
{
223
0
  struct os_timer* t;
224
225
0
  if (label==NULL)
226
0
    label = "n/a";
227
228
0
  t=shm_malloc( sizeof(struct os_timer) + strlen(label)+1 );
229
0
  if (t==0){
230
0
    LM_ERR("out of pkg memory\n");
231
0
    return NULL;
232
0
  }
233
0
  t->id=timer_id++;
234
0
  t->flags = flags;
235
0
  t->label = (char*)(t+1);
236
0
  strcpy( t->label, label);
237
0
  t->u.timer_f=f;
238
0
  t->t_param=param;
239
0
  t->interval=interval;
240
0
  t->expires=*jiffies+interval;
241
0
  t->trigger_time = 0;
242
0
  t->time = 0;
243
0
  return t;
244
0
}
245
246
247
/*register a periodic timer;
248
 * ret: <0 on error
249
 * Hint: if you need it in a module, register it from mod_init or it
250
 * won't work otherwise*/
251
int register_timer(char *label, timer_function f, void* param,
252
                unsigned int interval, unsigned short flags)
253
0
{
254
0
  struct os_timer* t;
255
256
0
  flags = flags & (~TIMER_FLAG_IS_UTIMER); /* just to be sure */
257
0
  t = new_os_timer( label, flags, f, param, interval);
258
0
  if (t==NULL)
259
0
    return E_OUT_OF_MEM;
260
  /* insert it into the timer list*/
261
0
  t->next = timer_list;
262
0
  timer_list = t;
263
0
  return t->id;
264
0
}
265
266
267
int register_utimer(char *label, utimer_function f, void* param,
268
                unsigned int interval, unsigned short flags)
269
0
{
270
0
  struct os_timer* t;
271
272
0
  flags = flags | TIMER_FLAG_IS_UTIMER; /* just to be sure */
273
0
  t = new_os_timer( label, flags, (timer_function*)f, param, interval);
274
0
  if (t==NULL)
275
0
    return E_OUT_OF_MEM;
276
  /* insert it into the utimer list*/
277
0
  t->next = utimer_list;
278
0
  utimer_list = t;
279
0
  return t->id;
280
0
}
281
282
283
struct timer_route_param {
284
  unsigned int idx;
285
  unsigned int version;
286
};
287
288
void route_timer_f(unsigned int ticks, void* param)
289
0
{
290
0
  struct timer_route_param *tr=(struct timer_route_param *)param;
291
0
  struct script_route sr;
292
0
  struct sip_msg *req;
293
0
  int old_route_type;
294
295
0
  if (tr->version!=sroutes->version) {
296
0
    LM_WARN("timer route triggering received for an old cfg version "
297
0
      "%d<>%d\n",tr->version, sroutes->version);
298
0
    return;
299
0
  }
300
301
0
  sr.name = sroutes->timer[tr->idx].name;
302
0
  sr.a = sroutes->timer[tr->idx].a;
303
304
0
  if(sr.a == NULL) {
305
0
    LM_ERR("NULL actions for timer_route '%s'/%d\n", sr.name, tr->idx);
306
0
    return;
307
0
  }
308
309
0
  req = get_dummy_sip_msg();
310
0
  if(req == NULL) {
311
0
    LM_ERR("No more memory\n");
312
0
    return;
313
0
  }
314
315
0
  swap_route_type(old_route_type, TIMER_ROUTE);
316
0
  run_top_route(sr, req);
317
0
  set_route_type(old_route_type);
318
319
  /* clean whatever extra structures were added by script functions */
320
0
  release_dummy_sip_msg(req);
321
322
  /* remove all added AVP - here we use all the time the default AVP list */
323
0
  reset_avps( );
324
0
}
325
326
327
/* the function will check the timer routes from the current process,
328
 * so be carefull where you are running it from */
329
int register_route_timers(void)
330
0
{
331
0
  struct timer_route_param *tr_param;
332
0
  struct os_timer *t, *p;
333
0
  int i;
334
335
0
#define move_to_pending( _t) \
336
0
  while(_t) { \
337
0
    p = (_t)->next; \
338
0
    if ((_t)->trigger_time) { \
339
0
      (_t)->next = *tr_timer_pending; \
340
0
      *tr_timer_pending = (_t); \
341
0
    } else { \
342
0
      shm_free( (_t)->t_param ); \
343
0
      shm_free( (_t) ); \
344
0
    } \
345
0
    (_t) = p; \
346
0
  }
347
348
0
  lock_get(tr_list_lock);
349
350
  /* handle the pending list, remove whatever already finished,
351
   * otherwise put back into pending */
352
0
  t = *tr_timer_pending;
353
0
  *tr_timer_pending = NULL;
354
0
  move_to_pending( t);
355
356
  /* handle the existing list -> free if done or move to pending if
357
   * the job is still under execution (for sure triggering cannot be
358
   * done anymore as the have the lock here) */
359
0
  t = *tr_timer_list;
360
0
  move_to_pending( t);
361
0
  *tr_timer_list = NULL;
362
363
  /* convert timer routes to jobs */
364
0
  for(i = 0; i<TIMER_RT_NO && sroutes->timer[i].a ; i++)
365
0
  {
366
0
    LM_DBG("registering timer route [%s] at %d secs\n",
367
0
      sroutes->timer[i].name, sroutes->timer[i].interval);
368
369
0
    tr_param = (struct timer_route_param*)
370
0
      shm_malloc( sizeof(struct timer_route_param) );
371
0
    if (tr_param==NULL) {
372
0
      LM_ERR("no more mem, skipping route timer [%s]\n",
373
0
        sroutes->timer[i].name);
374
0
    } else {
375
0
      tr_param->idx = i;
376
0
      tr_param->version = sroutes->version;
377
0
      t = new_os_timer( "timer_route", 0, route_timer_f, (void*)tr_param,
378
0
        sroutes->timer[i].interval);
379
0
      if (t==NULL) {
380
0
        LM_ERR("no more mem, skipping route timer [%s]\n",
381
0
          sroutes->timer[i].name);
382
0
      } else {
383
        /* insert it into the list*/
384
0
        t->next = *tr_timer_list;
385
0
        *tr_timer_list = t;
386
0
      }
387
0
    }
388
0
  }
389
390
0
  lock_release(tr_list_lock);
391
392
0
  return 1;
393
0
}
394
395
396
0
unsigned int have_ticks(void) {
397
0
  return jiffies==NULL ? 0 : 1;
398
0
}
399
400
0
unsigned int have_uticks(void) {
401
0
  return ujiffies==NULL ? 0 : 1;
402
0
}
403
404
unsigned int get_ticks(void)
405
0
{
406
0
  return *jiffies;
407
0
}
408
409
410
utime_t get_uticks(void)
411
0
{
412
0
  return *ujiffies;
413
0
}
414
415
416
417
static inline void timer_ticker(struct os_timer *tlist)
418
0
{
419
0
  struct os_timer* t;
420
0
  unsigned int j;
421
0
  ssize_t l;
422
423
  /* we need to store the original time as while executing the
424
     the handlers, the time may pass, affecting the way we
425
     calculate the new expire (expire will include the time
426
     taken to run handlers) -bogdan */
427
0
  j = *jiffies;
428
429
0
  for (t=tlist;t; t=t->next){
430
0
    if (j < t->expires)
431
0
      continue;
432
433
0
    if (t->trigger_time) {
434
0
      LM_WARN("timer task <%s> already scheduled %lld ms ago"
435
0
        " (now %lld ms), %s\n", t->label, ((utime_t)*ijiffies/1000) -
436
0
        (utime_t)(t->trigger_time/1000), ((utime_t)*ijiffies/1000),
437
0
        t->flags&TIMER_FLAG_SKIP_ON_DELAY ? "skipping execution" :
438
0
        t->flags&TIMER_FLAG_DELAY_ON_DELAY ? "delaying execution" :
439
0
        "pushing a new one");
440
441
0
      if (t->flags&TIMER_FLAG_SKIP_ON_DELAY) {
442
        /* skip this execution of the timer handler */
443
0
        t->expires = j + t->interval;
444
0
        continue;
445
0
      } else if (t->flags&TIMER_FLAG_DELAY_ON_DELAY) {
446
        /* delay and merge the executions of the timer handler
447
           until the prev one is done */
448
0
        continue;
449
0
      } else {
450
        /* launch the task now, even if overlapping with the
451
           already running one */
452
0
      }
453
0
    }
454
0
    t->expires = j + t->interval;
455
0
    t->trigger_time = *ijiffies;
456
0
    t->time = j;
457
    /* push the jobs for execution */
458
0
again:
459
0
    l = write( timer_pipe[1], &t, sizeof(t));
460
0
    if (l==-1) {
461
0
      if (errno==EAGAIN || errno==EINTR || errno==EWOULDBLOCK )
462
0
        goto again;
463
0
      LM_ERR("writing failed:[%d] %s, skipping job <%s> at %d s\n",
464
0
        errno, strerror(errno),t->label, j);
465
0
    }
466
0
  }
467
0
}
468
469
470
471
static inline void utimer_ticker(struct os_timer *utlist)
472
0
{
473
0
  struct os_timer* t;
474
0
  utime_t uj;
475
0
  ssize_t l;
476
477
  /* see comment on timer_ticket */
478
0
  uj = *ujiffies;
479
480
0
  for ( t=utlist ; t ; t=t->next){
481
0
    if (uj < t->expires)
482
0
      continue;
483
484
0
    if (t->trigger_time) {
485
0
      LM_WARN("utimer task <%s> already scheduled %lld ms ago"
486
0
        " (now %lld ms), %s\n", t->label, ((utime_t)*ijiffies/1000) -
487
0
        (utime_t)(t->trigger_time/1000), ((utime_t)*ijiffies/1000),
488
0
        t->flags&TIMER_FLAG_SKIP_ON_DELAY ? "skipping execution" :
489
0
        t->flags&TIMER_FLAG_DELAY_ON_DELAY ? "delaying execution" :
490
0
        "pushing a new one");
491
492
0
      if (t->flags&TIMER_FLAG_SKIP_ON_DELAY) {
493
        /* skip this execution of the timer handler */
494
0
        t->expires = uj + t->interval;
495
0
        continue;
496
0
      } else if (t->flags&TIMER_FLAG_DELAY_ON_DELAY) {
497
        /* delay the execution of the timer handler
498
           until the prev one is done */
499
0
        continue;
500
0
      } else {
501
        /* launch the task now, even if overlapping with the
502
           already running one */
503
0
      }
504
0
    }
505
0
    t->expires = uj + t->interval;
506
0
    t->trigger_time = *ijiffies;
507
0
    t->time = uj;
508
    /* push the jobs for execution */
509
0
again:
510
0
    l = write( timer_pipe[1], &t, sizeof(t));
511
0
    if (l==-1) {
512
0
      if (errno==EAGAIN || errno==EINTR || errno==EWOULDBLOCK )
513
0
        goto again;
514
0
      LM_ERR("writing failed:[%d] %s, skipping job <%s> at %lld us\n",
515
0
        errno, strerror(errno),t->label, uj);
516
0
    }
517
0
  }
518
0
}
519
520
521
static void run_timer_process( void )
522
0
{
523
0
  unsigned int multiple;
524
0
  unsigned int cnt;
525
0
  struct timeval o_tv;
526
0
  struct timeval tv, comp_tv;
527
0
  utime_t  drift;
528
0
  utime_t  uinterval;
529
0
  utime_t  wait;
530
0
  utime_t  ij;
531
532
/* timer re-calibration to compensate drifting */
533
0
#define compute_wait_with_drift(_tv) \
534
0
  do {                                                         \
535
0
    if ( drift > ITIMER_TICK ) {                             \
536
0
      wait = (drift >= uinterval) ? 0 : uinterval-drift;   \
537
0
      _tv.tv_sec = wait / 1000000;                         \
538
0
      _tv.tv_usec = wait % 1000000;                        \
539
0
      drift -= uinterval-wait;                             \
540
0
    } else {                                                 \
541
0
      _tv = o_tv;                                          \
542
0
    }                                                        \
543
0
  }while(0)
544
545
546
0
  if ( (utimer_list==NULL) || ((TIMER_TICK*1000000) == UTIMER_TICK) ) {
547
0
    o_tv.tv_sec = TIMER_TICK;
548
0
    o_tv.tv_usec = 0;
549
0
    multiple = 1;
550
0
  } else {
551
0
    o_tv.tv_sec = UTIMER_TICK / 1000000;
552
0
    o_tv.tv_usec = UTIMER_TICK % 1000000;
553
0
    multiple = (( TIMER_TICK * 1000000 ) / UTIMER_TICK ) / 1000000;
554
0
  }
555
556
0
  LM_DBG("    tv = %ld, %ld, m=%d\n",
557
0
    (long)o_tv.tv_sec,(long)o_tv.tv_usec,multiple);
558
559
0
  drift = 0;
560
0
  uinterval = o_tv.tv_sec * 1000000 + o_tv.tv_usec;
561
562
0
  if (utimer_list==NULL) {
563
    /* only TIMERs, ticking at TIMER_TICK */
564
0
    for( ; ; ) {
565
0
      ij = *ijiffies;
566
0
      compute_wait_with_drift(comp_tv);
567
0
      tv = comp_tv;
568
0
      select( 0, 0, 0, 0, &tv);
569
570
0
      timer_ticker( timer_list);
571
0
      lock_get(tr_list_lock);
572
0
      timer_ticker( *tr_timer_list);
573
0
      lock_release(tr_list_lock);
574
575
0
      drift += ((utime_t)comp_tv.tv_sec*1000000+comp_tv.tv_usec > (*ijiffies-ij)) ?
576
0
          0 : *ijiffies-ij - ((utime_t)comp_tv.tv_sec*1000000+comp_tv.tv_usec);
577
0
    }
578
579
0
  } else
580
0
  if (multiple==1) {
581
    /* TIMERs and UTIMERs, ticking together TIMER_TICK (synced) */
582
0
    for( ; ; ) {
583
0
      ij = *ijiffies;
584
0
      compute_wait_with_drift(comp_tv);
585
0
      tv = comp_tv;
586
0
      select( 0, 0, 0, 0, &tv);
587
0
      timer_ticker( timer_list);
588
0
      lock_get(tr_list_lock);
589
0
      timer_ticker( *tr_timer_list);
590
0
      lock_release(tr_list_lock);
591
0
      utimer_ticker( utimer_list);
592
593
0
      drift += ((utime_t)comp_tv.tv_sec*1000000+comp_tv.tv_usec > (*ijiffies-ij)) ?
594
0
          0 : *ijiffies-ij - ((utime_t)comp_tv.tv_sec*1000000+comp_tv.tv_usec);
595
0
    }
596
597
0
  } else {
598
    /* TIMERs and UTIMERs, TIMER_TICK is multiple of UTIMER_TICK */
599
0
    for( cnt=1 ; ; cnt++ ) {
600
0
      ij = *ijiffies;
601
0
      compute_wait_with_drift(comp_tv);
602
0
      tv = comp_tv;
603
0
      select( 0, 0, 0, 0, &tv);
604
0
      utimer_ticker(utimer_list);
605
0
      if (cnt==multiple) {
606
0
        timer_ticker(timer_list);
607
0
        lock_get(tr_list_lock);
608
0
        timer_ticker( *tr_timer_list);
609
0
        lock_release(tr_list_lock);
610
0
        cnt = 0;
611
0
      }
612
613
0
      drift += ((utime_t)comp_tv.tv_sec*1000000+comp_tv.tv_usec > (*ijiffies-ij)) ?
614
0
          0 : *ijiffies-ij - ((utime_t)comp_tv.tv_sec*1000000+comp_tv.tv_usec);
615
0
    }
616
0
  }
617
0
}
618
619
static void run_timer_process_jif(void)
620
0
{
621
0
  unsigned int multiple;
622
0
  unsigned int umultiple;
623
0
  unsigned int cnt;
624
0
  unsigned int ucnt;
625
0
  struct timeval o_tv;
626
0
  struct timeval tv;
627
0
  struct timeval sync_ts, last_ts;
628
0
  stime_t interval, drift;
629
0
  utime_t last_ticks, last_sync = 0;
630
631
0
  o_tv.tv_sec = 0;
632
0
  o_tv.tv_usec = ITIMER_TICK; /* internal timer */
633
0
  multiple  = ((TIMER_TICK*1000000)) / (UTIMER_TICK);
634
0
  umultiple = (UTIMER_TICK) / (ITIMER_TICK);
635
636
0
  LM_DBG("tv = %ld,  %ld, m=%d, mu=%d\n",
637
0
    (long)o_tv.tv_sec,(long)o_tv.tv_usec,multiple,umultiple);
638
639
0
  gettimeofday(&last_ts, 0);
640
0
  last_ticks = *ijiffies;
641
642
0
  for( cnt=1,ucnt=1 ; ; ucnt++ ) {
643
0
    tv = o_tv;
644
0
    select( 0, 0, 0, 0, &tv);
645
646
    /* update internal timer */
647
0
    *(ijiffies)+=ITIMER_TICK;
648
649
    /* update public utimer */
650
0
    if (ucnt==umultiple) {
651
0
      *(ujiffies)+=UTIMER_TICK;
652
      /* no overflow test as even if we go for 1 microsecond tick,
653
       * this will happen in 14038618 years :P */
654
0
      ucnt = 0;
655
656
0
      cnt++;
657
      /* update public timer */
658
0
      if (cnt==multiple) {
659
0
        *(jiffies)+=TIMER_TICK;
660
        /* test for overflow (if tick= 1s =>overflow in 136 years)*/
661
0
        cnt = 0;
662
0
      }
663
0
    }
664
665
    /* synchronize with system time if needed */
666
0
    if (*ijiffies - last_sync >= TIMER_SYNC_TICKS) {
667
0
      last_sync = *ijiffies;
668
669
0
      gettimeofday(&sync_ts, 0);
670
0
      interval = (utime_t)sync_ts.tv_sec*1000000 + sync_ts.tv_usec
671
0
            - (utime_t)last_ts.tv_sec*1000000 - last_ts.tv_usec;
672
673
0
      drift = interval - (*ijiffies - last_ticks);
674
675
      /* protect against sudden time changes */
676
0
      if (interval < 0 || drift < 0 || drift > TIMER_SYNC_TICKS) {
677
0
        last_ts = sync_ts;
678
0
        last_ticks = *ijiffies;
679
0
        LM_DBG("System time changed, ignoring...\n");
680
0
        continue;
681
0
      }
682
683
0
      if (drift > TIMER_MAX_DRIFT_TICKS) {
684
0
        *(ijiffies_drift_base) = *(ijiffies);
685
0
        *(ijiffies) += (drift / ITIMER_TICK) * ITIMER_TICK;
686
0
        *(ijiffies_drift) = (drift / ITIMER_TICK) * ITIMER_TICK;
687
688
0
        ucnt += drift / ITIMER_TICK;
689
0
        *(ujiffies) += (utime_t)(ucnt / umultiple) * (UTIMER_TICK);
690
0
        ucnt = ucnt % umultiple;
691
692
0
        cnt += (unsigned int)(drift / (UTIMER_TICK));
693
0
        *(jiffies) += (cnt / multiple) * TIMER_TICK;
694
0
        cnt = cnt % multiple;
695
0
      }
696
0
    }
697
0
  }
698
0
}
699
700
701
int start_timer_processes(void)
702
0
{
703
0
  int id;
704
0
  const struct internal_fork_params
705
0
      ifp_tk = {
706
0
    .proc_desc = "time_keeper",
707
0
    .flags = OSS_PROC_NO_IPC|OSS_PROC_NO_LOAD,
708
0
    .type = TYPE_NONE,
709
0
      },
710
0
      ifp_timer = {
711
0
    .proc_desc = "timer",
712
0
    .flags = OSS_PROC_NO_IPC|OSS_PROC_NO_LOAD,
713
0
    .type = TYPE_NONE,
714
0
  };
715
716
  /*
717
   * A change of the way timers were run. In the pre-1.5 times,
718
   * all timer processes had their own jiffies and just the first
719
   * one was doing the global ones. Now, there's a separate process
720
  * that increases jiffies - run_timer_process_jif(), and the rest
721
   * just use that one.
722
   *
723
   * The main reason for this change was when a function that relied
724
   * on jiffies for its timeouts got called from the timer thread and
725
   * was unable to detect timeouts.
726
   */
727
0
  if ( (id=internal_fork(&ifp_tk))<0 ) {
728
0
    LM_CRIT("cannot fork time keeper process\n");
729
0
    goto error;
730
0
  } else if (id==0) {
731
    /* new process */
732
0
    clean_write_pipeend();
733
734
0
    run_timer_process_jif();
735
0
    exit(-1);
736
0
  }
737
738
  /* fork a timer-trigger process */
739
0
  if ( (id=internal_fork(&ifp_timer))<0 ) {
740
0
    LM_CRIT("cannot fork timer process\n");
741
0
    goto error;
742
0
  } else if (id==0) {
743
    /* new process */
744
0
    clean_write_pipeend();
745
746
0
    run_timer_process( );
747
0
    exit(-1);
748
0
  }
749
750
0
  return 0;
751
0
error:
752
0
  return -1;
753
0
}
754
755
756
inline static int handle_io(struct fd_map* fm, int idx,int event_type)
757
0
{
758
0
  int n=0;
759
760
0
  pt_become_active();
761
762
0
  pre_run_handle_script_reload(fm->app_flags);
763
764
0
  profiling_proc_start( LEVEL_SIP, 1);
765
766
0
  switch(fm->type){
767
0
    case F_TIMER_JOB:
768
0
      profiling_proc_enter( LEVEL_FULL, "timer_job", 1 );
769
0
      handle_timer_job();
770
0
      profiling_proc_exit( LEVEL_FULL, "timer_job", n);
771
0
      break;
772
0
    case F_SCRIPT_ASYNC:
773
0
      profiling_proc_enter( LEVEL_SIP, "async_script", 0 );
774
0
      n = async_script_resume_f( fm->fd, fm->data,
775
0
        (event_type==IO_WATCH_TIMEOUT)?1:0 );
776
0
      profiling_proc_exit( LEVEL_SIP, "async_script", n);
777
0
      break;
778
0
    case F_FD_ASYNC:
779
0
      profiling_proc_enter( LEVEL_SIP, "async_fd", 0 );
780
0
      n = async_fd_resume( fm->fd, fm->data);
781
0
      profiling_proc_exit( LEVEL_SIP, "async_fd", n);
782
0
      break;
783
0
    case F_LAUNCH_ASYNC:
784
0
      profiling_proc_enter( LEVEL_SIP, "async_launch", 0 );
785
0
      n = async_launch_resume( fm->fd, fm->data);
786
0
      profiling_proc_exit( LEVEL_SIP, "async_launch", n);
787
0
      break;
788
0
    case F_IPC:
789
0
      profiling_proc_enter( LEVEL_SIP, "ipc_job", 1 );
790
0
      ipc_handle_job(fm->fd);
791
0
      profiling_proc_exit( LEVEL_SIP, "ipc_job", n);
792
0
      break;
793
0
    default:
794
0
      LM_CRIT("unknown fd type %d in Timer Extra\n", fm->type);
795
0
      n = -1;
796
0
      break;
797
0
  }
798
799
0
  if (reactor_is_empty() && _termination_in_progress==1) {
800
0
    LM_WARN("reactor got empty while termination in progress\n");
801
0
    ipc_handle_all_pending_jobs(IPC_FD_READ_SELF);
802
0
    if (reactor_is_empty())
803
0
      dynamic_process_final_exit();
804
0
  }
805
806
0
  profiling_proc_end( LEVEL_SIP, n );
807
808
0
  post_run_handle_script_reload();
809
810
0
  pt_become_idle();
811
0
  return n;
812
0
}
813
814
int timer_proc_reactor_init(void)
815
0
{
816
  /* create the reactor for timer proc */
817
0
  if ( init_worker_reactor( "Timer_extra", RCT_PRIO_MAX)<0 ) {
818
0
    LM_ERR("failed to init reactor\n");
819
0
    goto error;
820
0
  }
821
822
  /* init: start watching for the IPC jobs */
823
0
  if (reactor_add_reader(IPC_FD_READ_SELF, F_IPC, RCT_PRIO_ASYNC, NULL)<0){
824
0
    LM_CRIT("failed to add IPC pipe to reactor\n");
825
0
    goto error;
826
0
  }
827
828
  /* init: start watching for the timer jobs */
829
0
  if (reactor_add_reader( timer_fd_out, F_TIMER_JOB,
830
0
      RCT_PRIO_TIMER,NULL)<0){
831
0
    LM_CRIT("failed to add timer pipe_out to reactor\n");
832
0
    goto error;
833
0
  }
834
0
  return 0;
835
836
0
error:
837
0
  destroy_worker_reactor();
838
0
  return -1;
839
0
}
840
841
842
static int fork_dynamic_timer_process(void *si_filter)
843
0
{
844
0
  int p_id;
845
0
  const struct internal_fork_params ifp_th = {
846
0
    .proc_desc = "Timer handler",
847
0
    .flags = OSS_PROC_DYNAMIC|OSS_PROC_NEEDS_SCRIPT,
848
0
    .type = TYPE_TIMER,
849
0
  };
850
851
0
  if ((p_id=internal_fork(&ifp_th))<0){
852
0
    LM_CRIT("cannot fork Timer handler process\n");
853
0
    return -1;
854
0
  } else if (p_id==0) {
855
    /* new Timer process */
856
    /* set a more detailed description */
857
0
    set_proc_attrs("Timer handler");
858
0
    if (timer_proc_reactor_init() < 0 ||
859
0
    init_child(20000) < 0 ||
860
0
    self_update_routing_script() < 0) {
861
0
      goto error;
862
0
    }
863
864
0
    report_conditional_status( 1, 0); /*report success*/
865
    /* the child proc is done read&write) dealing with the status pipe */
866
0
    clean_read_pipeend();
867
868
    /* launch the reactor */
869
0
    reactor_main_loop( worker_reactor_timeout, error , );
870
0
    destroy_worker_reactor();
871
0
error:
872
0
    report_failure_status();
873
0
    LM_ERR("Initializing new process failed, exiting with error \n");
874
0
    pt[process_no].flags |= OSS_PROC_SELFEXIT;
875
0
    exit( -1);
876
0
  } else {
877
    /*parent/main*/
878
0
    return p_id;
879
0
  }
880
0
}
881
882
883
static void timer_process_graceful_terminate(int sender, void *param)
884
0
{
885
  /* we accept this only from the main proccess */
886
0
  if (sender!=0) {
887
0
    LM_BUG("graceful terminate received from a non-main process!!\n");
888
0
    return;
889
0
  }
890
0
  LM_NOTICE("process %d received RPC to terminate from Main\n",process_no);
891
892
  /*remove from reactor all the shared fds, so we stop reading from them */
893
894
  /*remove timer jobs pipe */
895
0
  reactor_del_reader( timer_fd_out, -1, 0);
896
897
  /*remove private IPC pipe */
898
0
  reactor_del_reader( IPC_FD_READ_SELF, -1, 0);
899
900
  /* let's drain the private IPC */
901
0
  ipc_handle_all_pending_jobs(IPC_FD_READ_SELF);
902
903
  /* what is left now is the reactor are async fd's, so we need to 
904
   * wait to complete all of them */
905
0
  if (reactor_is_empty())
906
0
    dynamic_process_final_exit();
907
908
  /* the exit will be triggered by the reactor, when empty */
909
0
  _termination_in_progress = 1;
910
0
  LM_WARN("reactor not empty, waiting for pending async\n");
911
0
}
912
913
914
int start_timer_extra_processes(int *chd_rank)
915
0
{
916
0
  int i, p_id;
917
0
  const struct internal_fork_params ifp_th = {
918
0
    .proc_desc = "Timer handler",
919
0
    .flags = OSS_PROC_NEEDS_SCRIPT,
920
0
    .type = TYPE_TIMER,
921
0
  };
922
923
0
  if (auto_scaling_enabled && s_profile &&
924
0
  create_process_group( TYPE_TIMER, NULL, s_profile ,
925
0
  fork_dynamic_timer_process, timer_process_graceful_terminate)!=0)
926
0
    LM_ERR("failed to create group of TIMER processes, "
927
0
      "auto forking will not be possible\n");
928
929
0
  for( i=0 ; i<timer_workers_no ; i++ ) {
930
931
0
    (*chd_rank)++;
932
0
    if ( (p_id=internal_fork(&ifp_th))<0 ) {
933
0
      LM_CRIT("cannot fork Timer handler process\n");
934
0
      return -1;
935
0
    } else if (p_id==0) {
936
      /* new Timer process */
937
      /* set a more detailed description */
938
0
        set_proc_attrs("Timer handler");
939
0
        if (timer_proc_reactor_init() < 0 ||
940
0
            init_child(*chd_rank) < 0) {
941
0
          report_failure_status();
942
0
          goto error;
943
0
        }
944
945
0
        report_conditional_status( (!no_daemon_mode), 0);
946
947
        /* launch the reactor */
948
0
        reactor_main_loop( worker_reactor_timeout, error , );
949
0
        destroy_worker_reactor();
950
951
0
        exit(-1);
952
0
    }
953
    /*parent*/
954
955
0
  }
956
957
0
  return 0;
958
959
/* only from child process */
960
0
error:
961
0
  exit(-1);
962
0
}
963
964
965
void handle_timer_job(void)
966
0
{
967
0
  struct os_timer *t;
968
0
  ssize_t l;
969
0
  utime_t _ijiffies,_ijiffies_extra;
970
971
  /* read one "os_timer" pointer from the pipe (non-blocking) */
972
0
  l = read( timer_fd_out, &t, sizeof(t) );
973
0
  if (l==-1) {
974
0
    if (errno==EAGAIN || errno==EINTR || errno==EWOULDBLOCK )
975
0
      return;
976
0
    LM_ERR("read failed:[%d] %s\n", errno, strerror(errno));
977
0
    return;
978
0
  }
979
980
981
/*
982
Scheduling and handling of the timer task happens without drifting
983
==================================================================
984
[time_keeper proc] *ijiffies increments:
985
  V          ITIMER_TICK          V         ITIMER_TICK             V
986
->|<----------------------------->|<------------------------------->|<--
987
  +ITIMER_TICK                    +ITIMER_TICK                      +ITIMER_TICK
988
989
[timer proc]           ^schedule timer job
990
                       t->trigger_time
991
[Timer handler proc]                                 ^handling timer job
992
993
The timer task was scheduled before a drift adjustement
994
=======================================================
995
[time_keeper proc] *ijiffies increments:
996
  V          ITIMER_TICK          V         ITIMER_TICK             V
997
->|<----------------------------->|<----------->|<----------------->|<--
998
  +ITIMER_TICK                    +ITIMER_TICK  +DRIFT              +ITIMER_TICK
999
                                                ^*ijifies_drift_base
1000
[timer proc]                        ^schedule timer job || ^schedule timer job
1001
                                    t->trigger_time
1002
[Timer handler proc]                                         ^handling timer job
1003
*/
1004
1005
  /* Cache the entry values for jiffies */
1006
0
  _ijiffies = *ijiffies;
1007
  /* if we read from the queue after or while a drift was detecte
1008
   *  -> take the drift value into consideration too */
1009
0
  _ijiffies_extra =
1010
0
    (t->trigger_time > *ijiffies_drift_base) ? 0 : *ijiffies_drift;
1011
1012
0
  profiling_proc_enter( LEVEL_FULL, t->label, 0 );
1013
1014
  /* run the handler */
1015
0
  if (t->flags&TIMER_FLAG_IS_UTIMER) {
1016
1017
0
    if (t->trigger_time<(_ijiffies-_ijiffies_extra-ITIMER_TICK) ) {
1018
0
      LM_WARN("utimer job <%s> has a %lld us delay in execution: "
1019
0
        "trigger_time=%lld ijiffies=%lld ijiffies_extra=%lld\n",
1020
0
        t->label, _ijiffies-t->trigger_time-_ijiffies_extra,
1021
0
        t->trigger_time, _ijiffies, _ijiffies_extra);
1022
0
    }
1023
1024
0
    t->u.utimer_f( t->time , t->t_param);
1025
0
    t->trigger_time = 0;
1026
1027
0
  } else {
1028
1029
0
    if (t->trigger_time<(_ijiffies-_ijiffies_extra-ITIMER_TICK) ) {
1030
0
      LM_WARN("timer job <%s> has a %lld us delay in execution: "
1031
0
        "trigger_time=%lld ijiffies=%lld ijiffies_extra=%lld\n",
1032
0
        t->label, _ijiffies-t->trigger_time-_ijiffies_extra,
1033
0
        t->trigger_time, _ijiffies, _ijiffies_extra);
1034
0
    }
1035
1036
0
    t->u.timer_f( (unsigned int)t->time , t->t_param);
1037
0
    t->trigger_time = 0;
1038
1039
0
  }
1040
1041
0
  profiling_proc_exit( LEVEL_FULL, t->label, 0 );
1042
1043
0
  return;
1044
0
}