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

taosdata / TDengine / #3848

15 Apr 2025 08:24AM UTC coverage: 62.61% (-0.002%) from 62.612%
#3848

push

travis-ci

web-flow
fix(dataformat): fix single column row copying (#30788)

154522 of 315314 branches covered (49.01%)

Branch coverage included in aggregate %.

34 of 47 new or added lines in 1 file covered. (72.34%)

540 existing lines in 131 files now uncovered.

240217 of 315158 relevant lines covered (76.22%)

19679321.97 hits per line

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

78.25
/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() {
11,175,009✔
108
  uintptr_t id;
109
  do {
110
    id = (uintptr_t)atomic_add_fetch_ptr((void**)&nextTimerId, 1);
11,175,009✔
111
  } while (id == 0);
11,175,020!
112
  return id;
11,175,020✔
113
}
114

115
static void timerAddRef(tmr_obj_t* timer) {
33,444,727✔
116
  (void)atomic_add_fetch_8(&timer->refCount, 1);
33,444,727✔
117
}
33,444,773✔
118

119
static void timerDecRef(tmr_obj_t* timer) {
33,432,039✔
120
  if (atomic_sub_fetch_8(&timer->refCount, 1) == 0) {
33,432,039✔
121
    taosMemoryFree(timer);
11,164,285!
122
  }
123
}
33,432,052✔
124

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

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

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

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

149
  lockTimerList(list);
11,175,019✔
150
  timer->mnext = list->timers;
11,175,020✔
151
  list->timers = timer;
11,175,020✔
152
  unlockTimerList(list);
11,175,020✔
153
}
11,175,014✔
154

155
static tmr_obj_t* findTimer(uintptr_t id) {
11,724,689✔
156
  tmr_obj_t* timer = NULL;
11,724,689✔
157
  if (id > 0) {
11,724,689✔
158
    uint32_t      idx = (uint32_t)(id % timerMap.size);
11,178,905✔
159
    timer_list_t* list = timerMap.slots + idx;
11,178,905✔
160
    lockTimerList(list);
11,178,905✔
161
    for (timer = list->timers; timer != NULL; timer = timer->mnext) {
11,179,089✔
162
      if (timer->id == id) {
11,094,919✔
163
        timerAddRef(timer);
11,094,752✔
164
        break;
11,094,755✔
165
      }
166
    }
167
    unlockTimerList(list);
11,178,925✔
168
  }
169
  return timer;
11,724,715✔
170
}
171

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

192
static void addToWheel(tmr_obj_t* timer, uint32_t delay) {
11,175,007✔
193
  timerAddRef(timer);
11,175,007✔
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;
11,175,021✔
197
  for (uint8_t i = 0; i < tListLen(wheels); i++) {
11,218,653✔
198
    time_wheel_t* wheel = wheels + i;
11,218,651✔
199
    if (delay < wheel->resolution * wheel->size) {
11,218,651✔
200
      timer->wheel = i;
11,175,019✔
201
      break;
11,175,019✔
202
    }
203
  }
204

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

209
  (void)taosThreadMutexLock(&wheel->mutex);
11,175,015✔
210

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

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

227
  (void)taosThreadMutexUnlock(&wheel->mutex);
11,175,023✔
228
}
11,175,022✔
229

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

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

258
  return removed;
547,499✔
259
}
260

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

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

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

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

282
  while (head != NULL) {
163,388,739✔
283
    uintptr_t  id = head->id;
10,625,567✔
284
    tmr_obj_t* next = head->next;
10,625,567✔
285
    tmrDebug(fmt, head->ctrl->label, id, head->fp, head->param);
10,625,567✔
286

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

295
    if (priority == 1) {
10,625,567✔
296
      if (taosScheduleTask(tmrQhandle, &schedMsg) != 0) {
10,574,836!
297
        tmrError("%s failed to add expired timer[id=%" PRIuPTR "] to queue.", head->ctrl->label, id);
×
298
      }
299
    } else if (priority == 2) {
50,731!
300
      if (taosScheduleTask(tmrQhandleHigh, &schedMsg) != 0) {
50,731!
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);
10,625,567✔
309
    head = next;
10,625,567✔
310
  }
311
}
152,763,172✔
312

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

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

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

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

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

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

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

358
static void taosTimerLoopFunc(int32_t signo) {
50,921,064✔
359
  int64_t now = taosGetMonotonicMs();
50,921,064✔
360

361
  for (int32_t i = 0; i < tListLen(wheels); i++) {
203,684,224✔
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;
152,763,170✔
367

368
    time_wheel_t* wheel = wheels + i;
152,763,170✔
369
    while (now >= wheel->nextScanAt) {
204,057,646✔
370
      (void)taosThreadMutexLock(&wheel->mutex);
51,294,481✔
371
      wheel->index = (wheel->index + 1) % wheel->size;
35,808,009✔
372
      tmr_obj_t* timer = wheel->slots[wheel->index];
35,808,009✔
373
      while (timer != NULL) {
46,433,576✔
374
        tmr_obj_t* next = timer->next;
10,625,567✔
375
        if (now < timer->expireAt) {
10,625,567!
376
          timer = next;
×
377
          continue;
×
378
        }
379

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

394
        // add to temporary expire list
395
        timer->next = expired;
10,625,567✔
396
        timer->prev = NULL;
10,625,567✔
397
        if (expired != NULL) {
10,625,567✔
398
          expired->prev = timer;
7,531,615✔
399
        }
400
        expired = timer;
10,625,567✔
401

402
        timer = next;
10,625,567✔
403
      }
404
      wheel->nextScanAt += wheel->resolution;
35,808,009✔
405
      (void)taosThreadMutexUnlock(&wheel->mutex);
35,808,009✔
406
    }
407

408
    addToExpired(expired);
152,763,165✔
409
  }
410
}
50,921,054✔
411

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

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

431
  if (timer->executedBy == taosGetSelfPthreadId()) {
10,547,253✔
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;
10,547,251✔
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.";
3✔
442
  tmrDebug(fmt, timer->ctrl->label, timer->id, timer->fp, timer->param);
3!
443
  return false;
3✔
444
}
445

446
bool taosTmrStop(tmr_h timerId) {
661,736✔
447
  uintptr_t id = (uintptr_t)timerId;
661,736✔
448

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

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

459
  return state == TIMER_STATE_WAITING;
538,727✔
460
}
461

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

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

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

489
  uintptr_t  id = (uintptr_t)*pTmrId;
11,062,821✔
490
  bool       stopped = false;
11,062,821✔
491
  tmr_obj_t* timer = findTimer(id);
11,062,821✔
492
  if (timer == NULL) {
11,062,825✔
493
    tmrDebug("%s timer[id=%" PRIuPTR "] does not exist", ctrl->label, id);
506,794✔
494
  } else {
495
    uint8_t state = atomic_val_compare_exchange_8(&timer->state, TIMER_STATE_WAITING, TIMER_STATE_CANCELED);
10,556,031✔
496
    if (!doStopTimer(timer, state)) {
10,556,032✔
497
      timerDecRef(timer);
10,547,251✔
498
      timer = NULL;
10,547,252✔
499
    }
500
    stopped = state == TIMER_STATE_WAITING;
10,556,033✔
501
  }
502

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

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

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

527
  return stopped;
8,781✔
528
}
529

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

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

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

543
  for (uint32_t i = 0; i < tsMaxTmrCtrl - 1; ++i) {
21,150,308✔
544
    tmr_ctrl_t* ctrl = tmrCtrls + i;
21,131,491✔
545
    ctrl->next = ctrl + 1;
21,131,491✔
546
  }
547
  (tmrCtrls + tsMaxTmrCtrl - 1)->next = NULL;
18,817✔
548
  unusedTmrCtrl = tmrCtrls;
18,817✔
549

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

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

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

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

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

584
  return 2;
18,817✔
585
}
586

587
static int32_t taosTmrInitModule(void) {
87,582✔
588
  if (atomic_load_32(&tmrModuleInit) == 2) {
87,582✔
589
    return 0;
68,764✔
590
  }
591

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

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

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

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

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

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

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

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

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

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

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

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

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

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

672
    for (size_t i = 0; i < timerMap.size; i++) {
13,678,770✔
673
      timer_list_t* list = timerMap.slots + i;
13,676,544✔
674
      tmr_obj_t*    t = list->timers;
13,676,544✔
675
      while (t != NULL) {
13,677,334✔
676
        tmr_obj_t* next = t->mnext;
790✔
677
        taosMemoryFree(t);
790!
678
        t = next;
790✔
679
      }
680
    }
681
    taosMemoryFree(timerMap.slots);
2,226!
682
    taosMemoryFree(tmrCtrls);
2,226!
683

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