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

taosdata / TDengine / #4712

06 Sep 2025 04:27PM UTC coverage: 58.144% (-1.0%) from 59.134%
#4712

push

travis-ci

GitHub
test: update case description (#32878)

133123 of 291691 branches covered (45.64%)

Branch coverage included in aggregate %.

201244 of 283375 relevant lines covered (71.02%)

5637899.03 hits per line

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

75.4
/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() {
803,579✔
108
  uintptr_t id;
109
  do {
110
    id = (uintptr_t)atomic_add_fetch_ptr((void**)&nextTimerId, 1);
803,579✔
111
  } while (id == 0);
803,583!
112
  return id;
803,584✔
113
}
114

115
static void timerAddRef(tmr_obj_t* timer) {
2,408,162✔
116
  (void)atomic_add_fetch_8(&timer->refCount, 1);
2,408,162✔
117
}
2,408,166✔
118

119
static void timerDecRef(tmr_obj_t* timer) {
2,406,201✔
120
  if (atomic_sub_fetch_8(&timer->refCount, 1) == 0) {
2,406,201✔
121
    taosMemoryFree(timer);
802,605!
122
  }
123
}
2,406,210✔
124

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

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

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

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

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

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

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

192
static void addToWheel(tmr_obj_t* timer, uint32_t delay) {
803,583✔
193
  timerAddRef(timer);
803,583✔
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;
803,584✔
197
  for (uint8_t i = 0; i < tListLen(wheels); i++) {
812,530!
198
    time_wheel_t* wheel = wheels + i;
812,530✔
199
    if (delay < wheel->resolution * wheel->size) {
812,530✔
200
      timer->wheel = i;
803,584✔
201
      break;
803,584✔
202
    }
203
  }
204

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

209
  (void)taosThreadMutexLock(&wheel->mutex);
803,583✔
210

211
  uint32_t idx = 0;
803,585✔
212
  if (timer->expireAt > wheel->nextScanAt) {
803,585!
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);
803,585✔
216
    idx = (delay + wheel->resolution - 1) / wheel->resolution;
803,585✔
217
  }
218

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

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

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

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

258
  return removed;
331,708✔
259
}
260

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

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

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

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

282
  while (head != NULL) {
66,738,835✔
283
    uintptr_t  id = head->id;
470,899✔
284
    tmr_obj_t* next = head->next;
470,899✔
285
    tmrDebug(fmt, head->ctrl->label, id, head->fp, head->param);
470,899✔
286

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

295
    if (priority == 1) {
470,899✔
296
      if (taosScheduleTask(tmrQhandle, &schedMsg) != 0) {
400,412!
297
        tmrError("%s failed to add expired timer[id=%" PRIuPTR "] to queue.", head->ctrl->label, id);
×
298
      }
299
    } else if (priority == 2) {
70,487!
300
      if (taosScheduleTask(tmrQhandleHigh, &schedMsg) != 0) {
70,487!
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);
470,899✔
309
    head = next;
470,899✔
310
  }
311
}
66,267,936✔
312

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

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

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

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

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

345
  tmr_obj_t* timer = (tmr_obj_t*)taosMemoryCalloc(1, sizeof(tmr_obj_t));
803,579!
346
  if (timer == NULL) {
803,580!
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);
803,580✔
352
}
353

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

358
static void taosTimerLoopFunc(int32_t signo) {
22,089,312✔
359
  int64_t now = taosGetMonotonicMs();
22,089,312✔
360

361
  for (int32_t i = 0; i < tListLen(wheels); i++) {
88,357,248✔
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;
66,267,936✔
367

368
    time_wheel_t* wheel = wheels + i;
66,267,936✔
369
    while (now >= wheel->nextScanAt) {
88,481,057✔
370
      (void)taosThreadMutexLock(&wheel->mutex);
22,213,121✔
371
      wheel->index = (wheel->index + 1) % wheel->size;
22,213,121✔
372
      tmr_obj_t* timer = wheel->slots[wheel->index];
22,213,121✔
373
      while (timer != NULL) {
22,684,020✔
374
        tmr_obj_t* next = timer->next;
470,899✔
375
        if (now < timer->expireAt) {
470,899!
376
          timer = next;
×
377
          continue;
×
378
        }
379

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

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

402
        timer = next;
470,899✔
403
      }
404
      wheel->nextScanAt += wheel->resolution;
22,213,121✔
405
      (void)taosThreadMutexUnlock(&wheel->mutex);
22,213,121✔
406
    }
407

408
    addToExpired(expired);
66,267,936✔
409
  }
410
}
22,089,312✔
411

412
static bool doStopTimer(tmr_obj_t* timer, uint8_t state) {
801,003✔
413
  if (state == TIMER_STATE_WAITING) {
801,003✔
414
    bool reusable = false;
331,709✔
415
    if (removeFromWheel(timer)) {
331,709✔
416
      removeTimer(timer->id);
331,708✔
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;
331,708✔
420
    }
421
    const char* fmt = "%s timer[id=%" PRIuPTR ", fp=%p, param=%p] is cancelled.";
331,710✔
422
    tmrDebug(fmt, timer->ctrl->label, timer->id, timer->fp, timer->param);
331,710✔
423
    return reusable;
331,710✔
424
  }
425

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

431
  if (timer->executedBy == taosGetSelfPthreadId()) {
469,294!
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;
469,294✔
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) {
413,886✔
447
  uintptr_t id = (uintptr_t)timerId;
413,886✔
448

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

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

459
  return state == TIMER_STATE_WAITING;
331,708✔
460
}
461

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

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

471
  tmr_obj_t* timer = findTimer(id);
×
472
  if (timer == NULL) {
×
473
    tmrDebug("timer[id=%" PRIuPTR "] does not exist", id);
×
474
    return true;
×
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,
775,211✔
483
                          uint8_t priority) {
484
  tmr_ctrl_t* ctrl = (tmr_ctrl_t*)handle;
775,211✔
485
  if (ctrl == NULL || ctrl->label[0] == 0) {
775,211!
486
    return false;
1✔
487
  }
488

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

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

511
  tmrDebug("%s timer[id=%" PRIuPTR "] is reused", ctrl->label, timer->id);
2!
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) {
2!
516
    if (i % 1000 == 0) {
×
517
      (void)sched_yield();
×
518
    }
519
  }
520

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

527
  return stopped;
2✔
528
}
529

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

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

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

543
  for (uint32_t i = 0; i < tsMaxTmrCtrl - 1; ++i) {
5,074,860✔
544
    tmr_ctrl_t* ctrl = tmrCtrls + i;
5,070,345✔
545
    ctrl->next = ctrl + 1;
5,070,345✔
546
  }
547
  (tmrCtrls + tsMaxTmrCtrl - 1)->next = NULL;
4,515✔
548
  unusedTmrCtrl = tmrCtrls;
4,515✔
549

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

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

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

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

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

584
  return 2;
4,515✔
585
}
586

587
static int32_t taosTmrInitModule(void) {
30,478✔
588
  if (atomic_load_32(&tmrModuleInit) == 2) {
30,478✔
589
    return 0;
25,963✔
590
  }
591

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

596
  while (true) {
597
    if (0 == atomic_val_compare_exchange_32(&tmrModuleInit, 0, 1)) {
9,030✔
598
      atomic_store_32(&tmrModuleInit, taosTmrModuleInit());
4,515✔
599
    } else if (atomic_load_32(&tmrModuleInit) < 0) {
4,515!
600
      return -1;
×
601
    } else if (atomic_load_32(&tmrModuleInit) == 2) {
4,515!
602
      return 0;
4,515✔
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) {
30,478✔
612
  const char* ret = taosMonotonicInit();
30,478✔
613
  tmrDebug("ttimer monotonic clock source:%s", ret);
30,478✔
614

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

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

627
  if (ctrl == NULL) {
30,478!
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));
30,478✔
634

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

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

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

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

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

658
    taosCleanUpScheduler(tmrQhandle);
2,476✔
659
    taosMemoryFreeClear(tmrQhandle);
2,476!
660

661
    taosCleanUpScheduler(tmrQhandleHigh);
2,476✔
662
    taosMemoryFreeClear(tmrQhandleHigh);
2,476!
663

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

670
    (void)taosThreadMutexDestroy(&tmrCtrlMutex);
2,476✔
671

672
    for (size_t i = 0; i < timerMap.size; i++) {
15,215,020✔
673
      timer_list_t* list = timerMap.slots + i;
15,212,544✔
674
      tmr_obj_t*    t = list->timers;
15,212,544✔
675
      while (t != NULL) {
15,213,493✔
676
        tmr_obj_t* next = t->mnext;
949✔
677
        taosMemoryFree(t);
949!
678
        t = next;
949✔
679
      }
680
    }
681
    taosMemoryFree(timerMap.slots);
2,476!
682
    taosMemoryFree(tmrCtrls);
2,476!
683

684
    tmrCtrls = NULL;
2,476✔
685
    unusedTmrCtrl = NULL;
2,476✔
686
    atomic_store_32(&tmrModuleInit, 0);
2,476✔
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