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

taosdata / TDengine / #4907

30 Dec 2025 10:52AM UTC coverage: 65.541% (+0.03%) from 65.514%
#4907

push

travis-ci

web-flow
enh: drop multi-stream (#33962)

60 of 106 new or added lines in 4 files covered. (56.6%)

808 existing lines in 106 files now uncovered.

193920 of 295877 relevant lines covered (65.54%)

118520209.34 hits per line

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

88.68
/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() {
396,511,348✔
108
  uintptr_t id;
109
  do {
110
    id = (uintptr_t)atomic_add_fetch_ptr((void**)&nextTimerId, 1);
396,511,348✔
111
  } while (id == 0);
396,512,753✔
112
  return id;
396,512,639✔
113
}
114

115
static void timerAddRef(tmr_obj_t* timer) {
1,182,215,530✔
116
  (void)atomic_add_fetch_8(&timer->refCount, 1);
1,182,215,530✔
117
}
1,182,217,165✔
118

119
static void timerDecRef(tmr_obj_t* timer) {
1,180,802,959✔
120
  if (atomic_sub_fetch_8(&timer->refCount, 1) == 0) {
1,180,802,959✔
121
    taosMemoryFree(timer);
395,805,542✔
122
  }
123
}
1,180,802,242✔
124

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

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

142
static void addTimer(tmr_obj_t* timer) {
396,512,137✔
143
  timerAddRef(timer);
396,512,137✔
144
  timer->wheel = tListLen(wheels);
396,512,075✔
145

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

149
  lockTimerList(list);
396,512,394✔
150
  timer->mnext = list->timers;
396,512,508✔
151
  list->timers = timer;
396,512,248✔
152
  unlockTimerList(list);
396,512,003✔
153
}
396,511,768✔
154

155
static tmr_obj_t* findTimer(uintptr_t id) {
528,775,766✔
156
  tmr_obj_t* timer = NULL;
528,775,766✔
157
  if (id > 0) {
528,775,766✔
158
    uint32_t      idx = (uint32_t)(id % timerMap.size);
396,620,283✔
159
    timer_list_t* list = timerMap.slots + idx;
396,620,283✔
160
    lockTimerList(list);
396,620,730✔
161
    for (timer = list->timers; timer != NULL; timer = timer->mnext) {
396,619,891✔
162
      if (timer->id == id) {
389,192,671✔
163
        timerAddRef(timer);
389,193,155✔
164
        break;
389,193,162✔
165
      }
166
    }
167
    unlockTimerList(list);
396,620,737✔
168
  }
169
  return timer;
528,776,045✔
170
}
171

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

192
static void addToWheel(tmr_obj_t* timer, uint32_t delay) {
396,510,671✔
193
  timerAddRef(timer);
396,510,671✔
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;
396,512,248✔
197
  for (uint8_t i = 0; i < tListLen(wheels); i++) {
404,661,417✔
198
    time_wheel_t* wheel = wheels + i;
404,660,283✔
199
    if (delay < wheel->resolution * wheel->size) {
404,660,283✔
200
      timer->wheel = i;
396,512,753✔
201
      break;
396,512,273✔
202
    }
203
  }
204

205
  time_wheel_t* wheel = wheels + timer->wheel;
396,513,407✔
206
  timer->prev = NULL;
396,512,273✔
207
  timer->expireAt = taosGetMonotonicMs() + delay;
396,512,273✔
208

209
  (void)taosThreadMutexLock(&wheel->mutex);
396,512,035✔
210

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

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

227
  (void)taosThreadMutexUnlock(&wheel->mutex);
396,512,753✔
228
}
396,512,753✔
229

230
static bool removeFromWheel(tmr_obj_t* timer) {
117,110,158✔
231
  uint8_t wheelIdx = timer->wheel;
117,110,158✔
232
  if (wheelIdx >= tListLen(wheels)) {
117,110,158✔
233
    return false;
799✔
234
  }
235
  time_wheel_t* wheel = wheels + wheelIdx;
117,109,359✔
236

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

258
  return removed;
117,109,616✔
259
}
260

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

269
    (*timer->fp)(timer->param, (tmr_h)timer->id);
278,694,093✔
270
    atomic_store_8(&timer->state, TIMER_STATE_STOPPED);
278,695,961✔
271

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

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

282
  while (head != NULL) {
2,147,483,647✔
283
    uintptr_t  id = head->id;
278,696,760✔
284
    tmr_obj_t* next = head->next;
278,696,760✔
285
    tmrDebug(fmt, head->ctrl->label, id, head->fp, head->param);
278,696,760✔
286

287
    SSchedMsg schedMsg;
278,573,964✔
288
    schedMsg.fp = NULL;
278,696,760✔
289
    schedMsg.tfp = processExpiredTimer;
278,696,760✔
290
    schedMsg.msg = NULL;
278,696,760✔
291
    schedMsg.ahandle = head;
278,696,760✔
292
    schedMsg.thandle = NULL;
278,696,760✔
293
    uint8_t priority = head->priority;
278,696,760✔
294

295
    if (priority == 1) {
278,696,760✔
296
      if (taosScheduleTask(tmrQhandle, &schedMsg) != 0) {
244,844,874✔
297
        tmrError("%s failed to add expired timer[id=%" PRIuPTR "] to queue.", head->ctrl->label, id);
×
298
      }
299
    } else if (priority == 2) {
33,851,886✔
300
      if (taosScheduleTask(tmrQhandleHigh, &schedMsg) != 0) {
33,851,886✔
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);
278,696,760✔
309
    head = next;
278,696,760✔
310
  }
311
}
2,147,483,647✔
312

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

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

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

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

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

345
  tmr_obj_t* timer = (tmr_obj_t*)taosMemoryCalloc(1, sizeof(tmr_obj_t));
396,510,532✔
346
  if (timer == NULL) {
396,510,400✔
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);
396,510,400✔
352
}
353

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

358
static void taosTimerLoopFunc(int32_t signo) {
2,147,483,647✔
359
  int64_t now = taosGetMonotonicMs();
2,147,483,647✔
360

361
  for (int32_t i = 0; i < tListLen(wheels); i++) {
2,147,483,647✔
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;
2,147,483,647✔
367

368
    time_wheel_t* wheel = wheels + i;
2,147,483,647✔
369
    while (now >= wheel->nextScanAt) {
2,147,483,647✔
370
      (void)taosThreadMutexLock(&wheel->mutex);
2,147,483,647✔
371
      wheel->index = (wheel->index + 1) % wheel->size;
2,147,483,647✔
372
      tmr_obj_t* timer = wheel->slots[wheel->index];
2,147,483,647✔
373
      while (timer != NULL) {
2,147,483,647✔
374
        tmr_obj_t* next = timer->next;
278,696,760✔
375
        if (now < timer->expireAt) {
278,696,760✔
376
          timer = next;
×
377
          continue;
×
378
        }
379

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

394
        // add to temporary expire list
395
        timer->next = expired;
278,696,760✔
396
        timer->prev = NULL;
278,696,760✔
397
        if (expired != NULL) {
278,696,760✔
398
          expired->prev = timer;
24,033,299✔
399
        }
400
        expired = timer;
278,696,760✔
401

402
        timer = next;
278,696,760✔
403
      }
404
      wheel->nextScanAt += wheel->resolution;
2,147,483,647✔
405
      (void)taosThreadMutexUnlock(&wheel->mutex);
2,147,483,647✔
406
    }
407

408
    addToExpired(expired);
2,147,483,647✔
409
  }
410
}
2,147,483,647✔
411

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

426
  if (state != TIMER_STATE_EXPIRED) {
272,082,914✔
427
    // timer already stopped or cancelled, has nothing to do in this case
428
    return false;
2,006✔
429
  }
430

431
  if (timer->executedBy == taosGetSelfPthreadId()) {
272,080,908✔
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;
272,078,125✔
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.";
2,872✔
442
  tmrDebug(fmt, timer->ctrl->label, timer->id, timer->fp, timer->param);
2,872✔
443
  return false;
2,872✔
444
}
445

446
bool taosTmrStop(tmr_h timerId) {
143,063,471✔
447
  uintptr_t id = (uintptr_t)timerId;
143,063,471✔
448

449
  tmr_obj_t* timer = findTimer(id);
143,063,471✔
450
  if (timer == NULL) {
143,063,111✔
451
    tmrDebug("timer[id=%" PRIuPTR "] does not exist", id);
25,951,204✔
452
    return false;
25,949,613✔
453
  }
454

455
  uint8_t state = atomic_val_compare_exchange_8(&timer->state, TIMER_STATE_WAITING, TIMER_STATE_CANCELED);
117,111,907✔
456
  (void)doStopTimer(timer, state);
117,112,657✔
457
  timerDecRef(timer);
117,111,575✔
458

459
  return state == TIMER_STATE_WAITING;
117,112,046✔
460
}
461

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

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

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

489
  uintptr_t  id = (uintptr_t)*pTmrId;
385,689,243✔
490
  bool       stopped = false;
385,689,502✔
491
  tmr_obj_t* timer = findTimer(id);
385,689,502✔
492
  if (timer == NULL) {
385,689,257✔
493
    tmrDebug("%s timer[id=%" PRIuPTR "] does not exist", ctrl->label, id);
113,608,496✔
494
  } else {
495
    uint8_t state = atomic_val_compare_exchange_8(&timer->state, TIMER_STATE_WAITING, TIMER_STATE_CANCELED);
272,080,761✔
496
    if (!doStopTimer(timer, state)) {
272,080,761✔
497
      timerDecRef(timer);
272,079,927✔
498
      timer = NULL;
272,079,927✔
499
    }
500
    stopped = state == TIMER_STATE_WAITING;
272,080,761✔
501
  }
502

503
  if (timer == NULL) {
385,689,502✔
504
    *pTmrId = taosTmrStartPriority(fp, mseconds, param, handle, priority);
385,688,668✔
505
    if (NULL == *pTmrId) {
385,688,668✔
506
      stopped = true;
×
507
    }
508
    return stopped;
385,688,668✔
509
  }
510

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

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

527
  return stopped;
834✔
528
}
529

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

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

541
  memset(&timerMap, 0, sizeof(timerMap));
2,153,568✔
542

543
  for (uint32_t i = 0; i < tsMaxTmrCtrl - 1; ++i) {
2,147,483,647✔
544
    tmr_ctrl_t* ctrl = tmrCtrls + i;
2,147,483,647✔
545
    ctrl->next = ctrl + 1;
2,147,483,647✔
546
  }
547
  (tmrCtrls + tsMaxTmrCtrl - 1)->next = NULL;
2,153,568✔
548
  unusedTmrCtrl = tmrCtrls;
2,153,568✔
549

550
  (void)taosThreadMutexInit(&tmrCtrlMutex, NULL);
2,153,568✔
551

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

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

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

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

584
  return 2;
2,153,568✔
585
}
586

587
static int32_t taosTmrInitModule(void) {
12,200,906✔
588
  if (atomic_load_32(&tmrModuleInit) == 2) {
12,200,906✔
589
    return 0;
10,047,338✔
590
  }
591

592
  if (atomic_load_32(&tmrModuleInit) < 0) {
2,153,568✔
593
    return -1;
×
594
  }
595

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

615
  if (taosTmrInitModule() < 0) {
12,200,906✔
616
    return NULL;
×
617
  }
618

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

627
  if (ctrl == NULL) {
12,200,906✔
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));
12,200,906✔
634

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

639
void taosTmrCleanUp(void* handle) {
10,595,921✔
640
  tmr_ctrl_t* ctrl = (tmr_ctrl_t*)handle;
10,595,921✔
641
  if (ctrl == NULL || ctrl->label[0] == 0) {
10,595,921✔
642
    return;
167✔
643
  }
644

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

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

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

658
    taosCleanUpScheduler(tmrQhandle);
548,478✔
659
    taosMemoryFreeClear(tmrQhandle);
548,478✔
660

661
    taosCleanUpScheduler(tmrQhandleHigh);
548,478✔
662
    taosMemoryFreeClear(tmrQhandleHigh);
548,478✔
663

664
    for (int32_t i = 0; i < tListLen(wheels); i++) {
2,193,912✔
665
      time_wheel_t* wheel = wheels + i;
1,645,434✔
666
      (void)taosThreadMutexDestroy(&wheel->mutex);
1,645,434✔
667
      taosMemoryFree(wheel->slots);
1,645,434✔
668
    }
669

670
    (void)taosThreadMutexDestroy(&tmrCtrlMutex);
548,478✔
671

672
    for (size_t i = 0; i < timerMap.size; i++) {
2,147,483,647✔
673
      timer_list_t* list = timerMap.slots + i;
2,147,483,647✔
674
      tmr_obj_t*    t = list->timers;
2,147,483,647✔
675
      while (t != NULL) {
2,147,483,647✔
676
        tmr_obj_t* next = t->mnext;
299,095✔
677
        taosMemoryFree(t);
299,095✔
678
        t = next;
299,095✔
679
      }
680
    }
681
    taosMemoryFree(timerMap.slots);
548,478✔
682
    taosMemoryFree(tmrCtrls);
548,478✔
683

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