• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #3796

31 Mar 2025 10:39AM UTC coverage: 30.372% (-7.1%) from 37.443%
#3796

push

travis-ci

happyguoxy
test:add test cases

69287 of 309062 branches covered (22.42%)

Branch coverage included in aggregate %.

118044 of 307720 relevant lines covered (38.36%)

278592.15 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

74.6
/source/util/src/ttimer.c
1
/*
2
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
3
 *
4
 * This program is free software: you can use, redistribute, and/or modify
5
 * it under the terms of the GNU Affero General Public License, version 3
6
 * or later ("AGPL"), as published by the Free Software Foundation.
7
 *
8
 * This program is distributed in the hope that it will be useful, but WITHOUT
9
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
 * FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * You should have received a copy of the GNU Affero General Public License
13
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14
 */
15

16
#define _DEFAULT_SOURCE
17
#include "ttimer.h"
18
#include "taoserror.h"
19
#include "tdef.h"
20
#include "tlog.h"
21
#include "tsched.h"
22

23
// clang-format off
24
#define tmrFatal(...) { if (tmrDebugFlag & DEBUG_FATAL) { taosPrintLog("TMR FATAL ", DEBUG_FATAL, tmrDebugFlag, __VA_ARGS__); }}
25
#define tmrError(...) { if (tmrDebugFlag & DEBUG_ERROR) { taosPrintLog("TMR ERROR ", DEBUG_ERROR, tmrDebugFlag, __VA_ARGS__); }}
26
#define tmrWarn(...)  { if (tmrDebugFlag & DEBUG_WARN)  { taosPrintLog("TMR WARN  ", DEBUG_WARN,  tmrDebugFlag, __VA_ARGS__); }}
27
#define tmrInfo(...)  { if (tmrDebugFlag & DEBUG_INFO)  { taosPrintLog("TMR INFO  ", DEBUG_INFO,  tmrDebugFlag, __VA_ARGS__); }}
28
#define tmrDebug(...) { if (tmrDebugFlag & DEBUG_DEBUG) { taosPrintLog("TMR DEBUG ", DEBUG_DEBUG, tmrDebugFlag, __VA_ARGS__); }}
29
#define tmrTrace(...) { if (tmrDebugFlag & DEBUG_TRACE) { taosPrintLog("TMR TRACE ", DEBUG_TRACE, tmrDebugFlag, __VA_ARGS__); }}
30
// clang-format on
31

32
#define TIMER_STATE_WAITING  0
33
#define TIMER_STATE_EXPIRED  1
34
#define TIMER_STATE_STOPPED  2
35
#define TIMER_STATE_CANCELED 3
36

37
typedef union _tmr_ctrl_t {
38
  char label[16];
39
  struct {
40
    // pad to ensure 'next' is the end of this union
41
    char               padding[16 - sizeof(union _tmr_ctrl_t*)];
42
    union _tmr_ctrl_t* next;
43
  };
44
} tmr_ctrl_t;
45

46
typedef struct tmr_obj_t {
47
  uintptr_t         id;
48
  tmr_ctrl_t*       ctrl;
49
  struct tmr_obj_t* mnext;
50
  struct tmr_obj_t* prev;
51
  struct tmr_obj_t* next;
52
  uint16_t          slot;
53
  uint8_t           wheel;
54
  uint8_t           state;
55
  uint8_t           refCount;
56
  uint8_t           reserved1;
57
  uint16_t          reserved2;
58
  union {
59
    int64_t expireAt;
60
    int64_t executedBy;
61
  };
62
  TAOS_TMR_CALLBACK fp;
63
  void*             param;
64
  uint8_t           priority;
65
} tmr_obj_t;
66

67
typedef struct timer_list_t {
68
  int64_t    lockedBy;
69
  tmr_obj_t* timers;
70
} timer_list_t;
71

72
typedef struct timer_map_t {
73
  uint32_t      size;
74
  uint32_t      count;
75
  timer_list_t* slots;
76
} timer_map_t;
77

78
typedef struct time_wheel_t {
79
  TdThreadMutex mutex;
80
  int64_t       nextScanAt;
81
  uint32_t      resolution;
82
  uint16_t      size;
83
  uint16_t      index;
84
  tmr_obj_t**   slots;
85
} time_wheel_t;
86

87
static int32_t tsMaxTmrCtrl = TSDB_MAX_VNODES_PER_DB + 100;
88

89
static int32_t       tmrModuleInit = 0;
90
static TdThreadMutex tmrCtrlMutex;
91
static tmr_ctrl_t*   tmrCtrls;
92
static tmr_ctrl_t*   unusedTmrCtrl = NULL;
93
static void*         tmrQhandle;
94
static void*         tmrQhandleHigh;
95
static int32_t       numOfTmrCtrl = 0;
96

97
int32_t          taosTmrThreads = 1;
98
static uintptr_t nextTimerId = 0;
99

100
static time_wheel_t wheels[] = {
101
    {.resolution = MSECONDS_PER_TICK, .size = 4096},
102
    {.resolution = 1000, .size = 1024},
103
    {.resolution = 60000, .size = 1024},
104
};
105
static timer_map_t timerMap;
106

107
static uintptr_t getNextTimerId() {
1,358✔
108
  uintptr_t id;
109
  do {
110
    id = (uintptr_t)atomic_add_fetch_ptr((void**)&nextTimerId, 1);
1,358✔
111
  } while (id == 0);
1,358!
112
  return id;
1,358✔
113
}
114

115
static void timerAddRef(tmr_obj_t* timer) {
3,659✔
116
  (void)atomic_add_fetch_8(&timer->refCount, 1);
3,659✔
117
}
3,659✔
118

119
static void timerDecRef(tmr_obj_t* timer) {
3,582✔
120
  if (atomic_sub_fetch_8(&timer->refCount, 1) == 0) {
3,582✔
121
    taosMemoryFree(timer);
1,309!
122
  }
123
}
3,582✔
124

125
static void lockTimerList(timer_list_t* list) {
4,351✔
126
  int64_t tid = taosGetSelfPthreadId();
4,351✔
127
  int32_t i = 0;
4,351✔
128
  while (atomic_val_compare_exchange_64(&(list->lockedBy), 0, tid) != 0) {
4,351!
129
    if (++i % 1000 == 0) {
×
130
      (void)sched_yield();
×
131
    }
132
  }
133
}
4,351✔
134

135
static void unlockTimerList(timer_list_t* list) {
4,351✔
136
  int64_t tid = taosGetSelfPthreadId();
4,351✔
137
  if (atomic_val_compare_exchange_64(&(list->lockedBy), tid, 0) != tid) {
4,351!
138
    uError("%" PRId64 " trying to unlock a timer list not locked by current thread.", tid);
×
139
  }
140
}
4,351✔
141

142
static void addTimer(tmr_obj_t* timer) {
1,358✔
143
  timerAddRef(timer);
1,358✔
144
  timer->wheel = tListLen(wheels);
1,358✔
145

146
  uint32_t      idx = (uint32_t)(timer->id % timerMap.size);
1,358✔
147
  timer_list_t* list = timerMap.slots + idx;
1,358✔
148

149
  lockTimerList(list);
1,358✔
150
  timer->mnext = list->timers;
1,358✔
151
  list->timers = timer;
1,358✔
152
  unlockTimerList(list);
1,358✔
153
}
1,358✔
154

155
static tmr_obj_t* findTimer(uintptr_t id) {
1,813✔
156
  tmr_obj_t* timer = NULL;
1,813✔
157
  if (id > 0) {
1,813✔
158
    uint32_t      idx = (uint32_t)(id % timerMap.size);
1,663✔
159
    timer_list_t* list = timerMap.slots + idx;
1,663✔
160
    lockTimerList(list);
1,663✔
161
    for (timer = list->timers; timer != NULL; timer = timer->mnext) {
1,663✔
162
      if (timer->id == id) {
943!
163
        timerAddRef(timer);
943✔
164
        break;
943✔
165
      }
166
    }
167
    unlockTimerList(list);
1,663✔
168
  }
169
  return timer;
1,813✔
170
}
171

172
static void removeTimer(uintptr_t id) {
1,330✔
173
  tmr_obj_t*    prev = NULL;
1,330✔
174
  uint32_t      idx = (uint32_t)(id % timerMap.size);
1,330✔
175
  timer_list_t* list = timerMap.slots + idx;
1,330✔
176
  lockTimerList(list);
1,330✔
177
  for (tmr_obj_t* p = list->timers; p != NULL; p = p->mnext) {
1,330!
178
    if (p->id == id) {
1,330!
179
      if (prev == NULL) {
1,330!
180
        list->timers = p->mnext;
1,330✔
181
      } else {
182
        prev->mnext = p->mnext;
×
183
      }
184
      timerDecRef(p);
1,330✔
185
      break;
1,330✔
186
    }
187
    prev = p;
×
188
  }
189
  unlockTimerList(list);
1,330✔
190
}
1,330✔
191

192
static void addToWheel(tmr_obj_t* timer, uint32_t delay) {
1,358✔
193
  timerAddRef(timer);
1,358✔
194
  // select a wheel for the timer, we are not an accurate timer,
195
  // but the inaccuracy should not be too large.
196
  timer->wheel = tListLen(wheels) - 1;
1,358✔
197
  for (uint8_t i = 0; i < tListLen(wheels); i++) {
1,628!
198
    time_wheel_t* wheel = wheels + i;
1,628✔
199
    if (delay < wheel->resolution * wheel->size) {
1,628✔
200
      timer->wheel = i;
1,358✔
201
      break;
1,358✔
202
    }
203
  }
204

205
  time_wheel_t* wheel = wheels + timer->wheel;
1,358✔
206
  timer->prev = NULL;
1,358✔
207
  timer->expireAt = taosGetMonotonicMs() + delay;
1,358✔
208

209
  (void)taosThreadMutexLock(&wheel->mutex);
1,358✔
210

211
  uint32_t idx = 0;
1,358✔
212
  if (timer->expireAt > wheel->nextScanAt) {
1,358!
213
    // adjust delay according to next scan time of this wheel
214
    // so that the timer is not fired earlier than desired.
215
    delay = (uint32_t)(timer->expireAt - wheel->nextScanAt);
1,358✔
216
    idx = (delay + wheel->resolution - 1) / wheel->resolution;
1,358✔
217
  }
218

219
  timer->slot = (uint16_t)((wheel->index + idx + 1) % wheel->size);
1,358✔
220
  tmr_obj_t* p = wheel->slots[timer->slot];
1,358✔
221
  wheel->slots[timer->slot] = timer;
1,358✔
222
  timer->next = p;
1,358✔
223
  if (p != NULL) {
1,358✔
224
    p->prev = timer;
424✔
225
  }
226

227
  (void)taosThreadMutexUnlock(&wheel->mutex);
1,358✔
228
}
1,358✔
229

230
static bool removeFromWheel(tmr_obj_t* timer) {
378✔
231
  uint8_t wheelIdx = timer->wheel;
378✔
232
  if (wheelIdx >= tListLen(wheels)) {
378!
233
    return false;
×
234
  }
235
  time_wheel_t* wheel = wheels + wheelIdx;
378✔
236

237
  bool removed = false;
378✔
238
  (void)taosThreadMutexLock(&wheel->mutex);
378✔
239
  // other thread may modify timer->wheel, check again.
240
  if (timer->wheel < tListLen(wheels)) {
378!
241
    if (timer->prev != NULL) {
378✔
242
      timer->prev->next = timer->next;
9✔
243
    }
244
    if (timer->next != NULL) {
378✔
245
      timer->next->prev = timer->prev;
46✔
246
    }
247
    if (timer == wheel->slots[timer->slot]) {
378✔
248
      wheel->slots[timer->slot] = timer->next;
369✔
249
    }
250
    timer->wheel = tListLen(wheels);
378✔
251
    timer->next = NULL;
378✔
252
    timer->prev = NULL;
378✔
253
    timerDecRef(timer);
378✔
254
    removed = true;
378✔
255
  }
256
  (void)taosThreadMutexUnlock(&wheel->mutex);
378✔
257

258
  return removed;
378✔
259
}
260

261
static void processExpiredTimer(void* handle, void* arg) {
952✔
262
  tmr_obj_t* timer = (tmr_obj_t*)handle;
952✔
263
  timer->executedBy = taosGetSelfPthreadId();
952✔
264
  uint8_t state = atomic_val_compare_exchange_8(&timer->state, TIMER_STATE_WAITING, TIMER_STATE_EXPIRED);
952✔
265
  if (state == TIMER_STATE_WAITING) {
952!
266
    const char* fmt = "%s timer[id=%" PRIuPTR ", fp=%p, param=%p] execution start.";
952✔
267
    tmrDebug(fmt, timer->ctrl->label, timer->id, timer->fp, timer->param);
952✔
268

269
    (*timer->fp)(timer->param, (tmr_h)timer->id);
952✔
270
    atomic_store_8(&timer->state, TIMER_STATE_STOPPED);
952✔
271

272
    fmt = "%s timer[id=%" PRIuPTR ", fp=%p, param=%p] execution end.";
952✔
273
    tmrDebug(fmt, timer->ctrl->label, timer->id, timer->fp, timer->param);
952✔
274
  }
275
  removeTimer(timer->id);
952✔
276
  timerDecRef(timer);
952✔
277
}
952✔
278

279
static void addToExpired(tmr_obj_t* head) {
1,231,632✔
280
  const char* fmt = "%s adding expired timer[id=%" PRIuPTR ", fp=%p, param=%p] to queue.";
1,231,632✔
281

282
  while (head != NULL) {
1,232,584✔
283
    uintptr_t  id = head->id;
952✔
284
    tmr_obj_t* next = head->next;
952✔
285
    tmrDebug(fmt, head->ctrl->label, id, head->fp, head->param);
952✔
286

287
    SSchedMsg schedMsg;
288
    schedMsg.fp = NULL;
952✔
289
    schedMsg.tfp = processExpiredTimer;
952✔
290
    schedMsg.msg = NULL;
952✔
291
    schedMsg.ahandle = head;
952✔
292
    schedMsg.thandle = NULL;
952✔
293
    uint8_t priority = head->priority;
952✔
294

295
    if (priority == 1) {
952✔
296
      if (taosScheduleTask(tmrQhandle, &schedMsg) != 0) {
951!
297
        tmrError("%s failed to add expired timer[id=%" PRIuPTR "] to queue.", head->ctrl->label, id);
×
298
      }
299
    } else if (priority == 2) {
1!
300
      if (taosScheduleTask(tmrQhandleHigh, &schedMsg) != 0) {
1!
301
        tmrError("%s failed to add expired timer[id=%" PRIuPTR "] to high level queue.", head->ctrl->label, id);
×
302
      }
303
    }
304
    else{
305
      tmrError("%s invalid priority level %d for timer[id=%" PRIuPTR "].", head->ctrl->label, priority, id);
×
306
    }
307

308
    tmrDebug("timer[id=%" PRIuPTR "] has been added to queue priority:%d.", id, priority);
952✔
309
    head = next;
952✔
310
  }
311
}
1,231,632✔
312

313
static uintptr_t doStartTimer(tmr_obj_t* timer, TAOS_TMR_CALLBACK fp, int32_t mseconds, void* param, tmr_ctrl_t* ctrl,
1,358✔
314
                              uint8_t priority) {
315
  uintptr_t id = getNextTimerId();
1,358✔
316
  timer->id = id;
1,358✔
317
  timer->state = TIMER_STATE_WAITING;
1,358✔
318
  timer->fp = fp;
1,358✔
319
  timer->param = param;
1,358✔
320
  timer->ctrl = ctrl;
1,358✔
321
  timer->priority = priority;
1,358✔
322
  addTimer(timer);
1,358✔
323

324
  const char* fmt = "%s timer[id=%" PRIuPTR ", fp=%p, param=%p] started";
1,358✔
325
  tmrDebug(fmt, ctrl->label, timer->id, timer->fp, timer->param);
1,358✔
326

327
  if (mseconds == 0) {
1,358!
328
    timer->wheel = tListLen(wheels);
×
329
    timerAddRef(timer);
×
330
    addToExpired(timer);
×
331
  } else {
332
    addToWheel(timer, mseconds);
1,358✔
333
  }
334

335
  // note: use `timer->id` here is unsafe as `timer` may already be freed
336
  return id;
1,358✔
337
}
338

339
tmr_h taosTmrStartPriority(TAOS_TMR_CALLBACK fp, int32_t mseconds, void* param, void* handle, uint8_t priority) {
1,347✔
340
  tmr_ctrl_t* ctrl = (tmr_ctrl_t*)handle;
1,347✔
341
  if (ctrl == NULL || ctrl->label[0] == 0) {
1,347!
342
    return NULL;
10✔
343
  }
344

345
  tmr_obj_t* timer = (tmr_obj_t*)taosMemoryCalloc(1, sizeof(tmr_obj_t));
1,337!
346
  if (timer == NULL) {
1,337!
347
    tmrError("%s failed to allocated memory for new timer object.", ctrl->label);
×
348
    return NULL;
×
349
  }
350

351
  return (tmr_h)doStartTimer(timer, fp, mseconds, param, ctrl, priority);
1,337✔
352
}
353

354
tmr_h taosTmrStart(TAOS_TMR_CALLBACK fp, int32_t mseconds, void* param, void* handle) {
440✔
355
  return taosTmrStartPriority(fp, mseconds, param, handle, 1);
440✔
356
}
357

358
static void taosTimerLoopFunc(int32_t signo) {
410,544✔
359
  int64_t now = taosGetMonotonicMs();
410,544✔
360

361
  for (int32_t i = 0; i < tListLen(wheels); i++) {
1,642,176✔
362
    // `expried` is a temporary expire list.
363
    // expired timers are first add to this list, then move
364
    // to expired queue as a batch to improve performance.
365
    // note this list is used as a stack in this function.
366
    tmr_obj_t* expired = NULL;
1,231,632✔
367

368
    time_wheel_t* wheel = wheels + i;
1,231,632✔
369
    while (now >= wheel->nextScanAt) {
1,644,191✔
370
      (void)taosThreadMutexLock(&wheel->mutex);
412,559✔
371
      wheel->index = (wheel->index + 1) % wheel->size;
412,559✔
372
      tmr_obj_t* timer = wheel->slots[wheel->index];
412,559✔
373
      while (timer != NULL) {
413,511✔
374
        tmr_obj_t* next = timer->next;
952✔
375
        if (now < timer->expireAt) {
952!
376
          timer = next;
×
377
          continue;
×
378
        }
379

380
        // remove from the wheel
381
        if (timer->prev == NULL) {
952!
382
          wheel->slots[wheel->index] = next;
952✔
383
          if (next != NULL) {
952✔
384
            next->prev = NULL;
361✔
385
          }
386
        } else {
387
          timer->prev->next = next;
×
388
          if (next != NULL) {
×
389
            next->prev = timer->prev;
×
390
          }
391
        }
392
        timer->wheel = tListLen(wheels);
952✔
393

394
        // add to temporary expire list
395
        timer->next = expired;
952✔
396
        timer->prev = NULL;
952✔
397
        if (expired != NULL) {
952✔
398
          expired->prev = timer;
361✔
399
        }
400
        expired = timer;
952✔
401

402
        timer = next;
952✔
403
      }
404
      wheel->nextScanAt += wheel->resolution;
412,559✔
405
      (void)taosThreadMutexUnlock(&wheel->mutex);
412,559✔
406
    }
407

408
    addToExpired(expired);
1,231,632✔
409
  }
410
}
410,544✔
411

412
static bool doStopTimer(tmr_obj_t* timer, uint8_t state) {
943✔
413
  if (state == TIMER_STATE_WAITING) {
943✔
414
    bool reusable = false;
378✔
415
    if (removeFromWheel(timer)) {
378!
416
      removeTimer(timer->id);
378✔
417
      // only safe to reuse the timer when timer is removed from the wheel.
418
      // we cannot guarantee the thread safety of the timr in all other cases.
419
      reusable = true;
378✔
420
    }
421
    const char* fmt = "%s timer[id=%" PRIuPTR ", fp=%p, param=%p] is cancelled.";
378✔
422
    tmrDebug(fmt, timer->ctrl->label, timer->id, timer->fp, timer->param);
378✔
423
    return reusable;
378✔
424
  }
425

426
  if (state != TIMER_STATE_EXPIRED) {
565!
427
    // timer already stopped or cancelled, has nothing to do in this case
428
    return false;
×
429
  }
430

431
  if (timer->executedBy == taosGetSelfPthreadId()) {
565!
432
    // taosTmrReset is called in the timer callback, should do nothing in this
433
    // case to avoid dead lock. note taosTmrReset must be the last statement
434
    // of the callback funtion, will be a bug otherwise.
435
    return false;
565✔
436
  }
437

438
  // timer callback is executing in another thread, we SHOULD wait it to stop,
439
  // BUT this may result in dead lock if current thread are holding a lock which
440
  // the timer callback need to acquire. so, we HAVE TO return directly.
441
  const char* fmt = "%s timer[id=%" PRIuPTR ", fp=%p, param=%p] is executing and cannot be stopped.";
×
442
  tmrDebug(fmt, timer->ctrl->label, timer->id, timer->fp, timer->param);
×
443
  return false;
×
444
}
445

446
bool taosTmrStop(tmr_h timerId) {
864✔
447
  uintptr_t id = (uintptr_t)timerId;
864✔
448

449
  tmr_obj_t* timer = findTimer(id);
864✔
450
  if (timer == NULL) {
864✔
451
    tmrDebug("timer[id=%" PRIuPTR "] does not exist", id);
507✔
452
    return false;
507✔
453
  }
454

455
  uint8_t state = atomic_val_compare_exchange_8(&timer->state, TIMER_STATE_WAITING, TIMER_STATE_CANCELED);
357✔
456
  (void)doStopTimer(timer, state);
357✔
457
  timerDecRef(timer);
357✔
458

459
  return state == TIMER_STATE_WAITING;
357✔
460
}
461

462
bool taosTmrStopA(tmr_h* timerId) {
223✔
463
  bool ret = taosTmrStop(*timerId);
223✔
464
  *timerId = NULL;
223✔
465
  return ret;
223✔
466
}
467

468
bool taosTmrIsStopped(tmr_h* timerId) {
21✔
469
  uintptr_t id = (uintptr_t)*timerId;
21✔
470

471
  tmr_obj_t* timer = findTimer(id);
21✔
472
  if (timer == NULL) {
21!
473
    tmrDebug("timer[id=%" PRIuPTR "] does not exist", id);
21!
474
    return true;
21✔
475
  }
476

477
  uint8_t state = atomic_load_8(&timer->state);
×
478

479
  return (state == TIMER_STATE_CANCELED) || (state == TIMER_STATE_STOPPED);
×
480
}
481

482
bool taosTmrResetPriority(TAOS_TMR_CALLBACK fp, int32_t mseconds, void* param, void* handle, tmr_h* pTmrId,
928✔
483
                          uint8_t priority) {
484
  tmr_ctrl_t* ctrl = (tmr_ctrl_t*)handle;
928✔
485
  if (ctrl == NULL || ctrl->label[0] == 0) {
928!
486
    return false;
×
487
  }
488

489
  uintptr_t  id = (uintptr_t)*pTmrId;
928✔
490
  bool       stopped = false;
928✔
491
  tmr_obj_t* timer = findTimer(id);
928✔
492
  if (timer == NULL) {
928✔
493
    tmrDebug("%s timer[id=%" PRIuPTR "] does not exist", ctrl->label, id);
342✔
494
  } else {
495
    uint8_t state = atomic_val_compare_exchange_8(&timer->state, TIMER_STATE_WAITING, TIMER_STATE_CANCELED);
586✔
496
    if (!doStopTimer(timer, state)) {
586✔
497
      timerDecRef(timer);
565✔
498
      timer = NULL;
565✔
499
    }
500
    stopped = state == TIMER_STATE_WAITING;
586✔
501
  }
502

503
  if (timer == NULL) {
928✔
504
    *pTmrId = taosTmrStartPriority(fp, mseconds, param, handle, priority);
907✔
505
    if (NULL == *pTmrId) {
907!
506
      stopped = true;
×
507
    }
508
    return stopped;
907✔
509
  }
510

511
  tmrDebug("%s timer[id=%" PRIuPTR "] is reused", ctrl->label, timer->id);
21✔
512

513
  // wait until there's no other reference to this timer,
514
  // so that we can reuse this timer safely.
515
  for (int32_t i = 1; atomic_load_8(&timer->refCount) > 1; ++i) {
21!
516
    if (i % 1000 == 0) {
×
517
      (void)sched_yield();
×
518
    }
519
  }
520

521
  if (timer->refCount != 1) {
21!
522
    uError("timer refCount=%d not expected 1", timer->refCount);
×
523
  }
524
  memset(timer, 0, sizeof(*timer));
21✔
525
  *pTmrId = (tmr_h)doStartTimer(timer, fp, mseconds, param, ctrl, priority);
21✔
526

527
  return stopped;
21✔
528
}
529

530
bool taosTmrReset(TAOS_TMR_CALLBACK fp, int32_t mseconds, void* param, void* handle, tmr_h* pTmrId) {
898✔
531
  return taosTmrResetPriority(fp, mseconds, param, handle, pTmrId, 1);
898✔
532
}
533

534
static int32_t taosTmrModuleInit(void) {
136✔
535
  tmrCtrls = taosMemoryMalloc(sizeof(tmr_ctrl_t) * tsMaxTmrCtrl);
136!
536
  if (tmrCtrls == NULL) {
136!
537
    tmrError("failed to allocate memory for timer controllers.");
×
538
    return terrno;
×
539
  }
540

541
  memset(&timerMap, 0, sizeof(timerMap));
136✔
542

543
  for (uint32_t i = 0; i < tsMaxTmrCtrl - 1; ++i) {
152,864✔
544
    tmr_ctrl_t* ctrl = tmrCtrls + i;
152,728✔
545
    ctrl->next = ctrl + 1;
152,728✔
546
  }
547
  (tmrCtrls + tsMaxTmrCtrl - 1)->next = NULL;
136✔
548
  unusedTmrCtrl = tmrCtrls;
136✔
549

550
  (void)taosThreadMutexInit(&tmrCtrlMutex, NULL);
136✔
551

552
  int64_t now = taosGetMonotonicMs();
136✔
553
  for (int32_t i = 0; i < tListLen(wheels); i++) {
544✔
554
    time_wheel_t* wheel = wheels + i;
408✔
555
    if (taosThreadMutexInit(&wheel->mutex, NULL) != 0) {
408!
556
      tmrError("failed to create the mutex for wheel, reason:%s", strerror(ERRNO));
×
557
      return terrno;
×
558
    }
559
    wheel->nextScanAt = now + wheel->resolution;
408✔
560
    wheel->index = 0;
408✔
561
    wheel->slots = (tmr_obj_t**)taosMemoryCalloc(wheel->size, sizeof(tmr_obj_t*));
408!
562
    if (wheel->slots == NULL) {
408!
563
      tmrError("failed to allocate wheel slots");
×
564
      return terrno;
×
565
    }
566
    timerMap.size += wheel->size;
408✔
567
  }
568

569
  timerMap.count = 0;
136✔
570
  timerMap.slots = (timer_list_t*)taosMemoryCalloc(timerMap.size, sizeof(timer_list_t));
136!
571
  if (timerMap.slots == NULL) {
136!
572
    tmrError("failed to allocate hash map");
×
573
    return terrno;
×
574
  }
575

576
  tmrQhandle = taosInitScheduler(10000, taosTmrThreads, "tmr", NULL);
136✔
577
  tmrQhandleHigh = taosInitScheduler(10000, taosTmrThreads, "high-tmr", NULL);
136✔
578
  if (taosInitTimer(taosTimerLoopFunc, MSECONDS_PER_TICK) != 0) {
136!
579
    tmrError("failed to initialize timer");
×
580
  }
581

582
  tmrDebug("timer module is initialized, number of threads: %d", taosTmrThreads);
136✔
583

584
  return 2;
136✔
585
}
586

587
static int32_t taosTmrInitModule(void) {
526✔
588
  if (atomic_load_32(&tmrModuleInit) == 2) {
526✔
589
    return 0;
390✔
590
  }
591

592
  if (atomic_load_32(&tmrModuleInit) < 0) {
136!
593
    return -1;
×
594
  }
595

596
  while (true) {
597
    if (0 == atomic_val_compare_exchange_32(&tmrModuleInit, 0, 1)) {
272✔
598
      atomic_store_32(&tmrModuleInit, taosTmrModuleInit());
136✔
599
    } else if (atomic_load_32(&tmrModuleInit) < 0) {
136!
600
      return -1;
×
601
    } else if (atomic_load_32(&tmrModuleInit) == 2) {
136!
602
      return 0;
136✔
603
    } else {
604
      taosMsleep(1);
×
605
    }
606
  }
607

608
  return -1;
609
}
610

611
void* taosTmrInit(int32_t maxNumOfTmrs, int32_t resolution, int32_t longest, const char* label) {
526✔
612
  const char* ret = taosMonotonicInit();
526✔
613
  tmrDebug("ttimer monotonic clock source:%s", ret);
526✔
614

615
  if (taosTmrInitModule() < 0) {
526!
616
    return NULL;
×
617
  }
618

619
  (void)taosThreadMutexLock(&tmrCtrlMutex);
526✔
620
  tmr_ctrl_t* ctrl = unusedTmrCtrl;
526✔
621
  if (ctrl != NULL) {
526!
622
    unusedTmrCtrl = ctrl->next;
526✔
623
    numOfTmrCtrl++;
526✔
624
  }
625
  (void)taosThreadMutexUnlock(&tmrCtrlMutex);
526✔
626

627
  if (ctrl == NULL) {
526!
628
    tmrError("%s too many timer controllers, failed to create timer controller.", label);
×
629
    terrno = TSDB_CODE_OUT_OF_MEMORY;
×
630
    return NULL;
×
631
  }
632

633
  tstrncpy(ctrl->label, label, sizeof(ctrl->label));
526✔
634

635
  tmrDebug("%s timer controller is initialized, number of timer controllers: %d.", label, numOfTmrCtrl);
526✔
636
  return ctrl;
526✔
637
}
638

639
void taosTmrCleanUp(void* handle) {
372✔
640
  tmr_ctrl_t* ctrl = (tmr_ctrl_t*)handle;
372✔
641
  if (ctrl == NULL || ctrl->label[0] == 0) {
372!
642
    return;
×
643
  }
644

645
  tmrDebug("%s timer controller is cleaned up.", ctrl->label);
372✔
646
  ctrl->label[0] = 0;
372✔
647

648
  (void)taosThreadMutexLock(&tmrCtrlMutex);
372✔
649
  ctrl->next = unusedTmrCtrl;
372✔
650
  numOfTmrCtrl--;
372✔
651
  unusedTmrCtrl = ctrl;
372✔
652
  (void)taosThreadMutexUnlock(&tmrCtrlMutex);
372✔
653

654
  tmrDebug("time controller's tmr ctrl size:  %d", numOfTmrCtrl);
372✔
655
  if (numOfTmrCtrl <= 0) {
372✔
656
    taosUninitTimer();
41✔
657

658
    taosCleanUpScheduler(tmrQhandle);
41✔
659
    taosMemoryFreeClear(tmrQhandle);
41!
660

661
    taosCleanUpScheduler(tmrQhandleHigh);
41✔
662
    taosMemoryFreeClear(tmrQhandleHigh);
41!
663

664
    for (int32_t i = 0; i < tListLen(wheels); i++) {
164✔
665
      time_wheel_t* wheel = wheels + i;
123✔
666
      (void)taosThreadMutexDestroy(&wheel->mutex);
123✔
667
      taosMemoryFree(wheel->slots);
123!
668
    }
669

670
    (void)taosThreadMutexDestroy(&tmrCtrlMutex);
41✔
671

672
    for (size_t i = 0; i < timerMap.size; i++) {
251,945✔
673
      timer_list_t* list = timerMap.slots + i;
251,904✔
674
      tmr_obj_t*    t = list->timers;
251,904✔
675
      while (t != NULL) {
251,904!
676
        tmr_obj_t* next = t->mnext;
×
677
        taosMemoryFree(t);
×
678
        t = next;
×
679
      }
680
    }
681
    taosMemoryFree(timerMap.slots);
41!
682
    taosMemoryFree(tmrCtrls);
41!
683

684
    tmrCtrls = NULL;
41✔
685
    unusedTmrCtrl = NULL;
41✔
686
    atomic_store_32(&tmrModuleInit, 0);
41✔
687
  }
688
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc