timer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "timer.hpp"
  4. #include <cstdlib>
  5. #include <cstring>
  6. #include <utility>
  7. #include "cbasetypes.hpp"
  8. #include "db.hpp"
  9. #include "malloc.hpp"
  10. #include "nullpo.hpp"
  11. #include "showmsg.hpp"
  12. #include "utils.hpp"
  13. #ifdef WIN32
  14. #include "winapi.hpp" // GetTickCount()
  15. #endif
  16. // If the server can't handle processing thousands of monsters
  17. // or many connected clients, please increase TIMER_MIN_INTERVAL.
  18. // The official interval of 20ms is however strongly recommended,
  19. // as it is needed for perfect server-client syncing.
  20. const t_tick TIMER_MIN_INTERVAL = 20;
  21. const t_tick TIMER_MAX_INTERVAL = 1000;
  22. // timers (array)
  23. static struct TimerData* timer_data = nullptr;
  24. static int timer_data_max = 0;
  25. static int timer_data_num = 0;
  26. // free timers (array)
  27. static int* free_timer_list = nullptr;
  28. static int free_timer_list_max = 0;
  29. static int free_timer_list_pos = 0;
  30. /// Comparator for the timer heap. (minimum tick at top)
  31. /// Returns negative if tid1's tick is smaller, positive if tid2's tick is smaller, 0 if equal.
  32. ///
  33. /// @param tid1 First timer
  34. /// @param tid2 Second timer
  35. /// @return negative if tid1 is top, positive if tid2 is top, 0 if equal
  36. #define DIFFTICK_MINTOPCMP(tid1,tid2) DIFF_TICK(timer_data[tid1].tick,timer_data[tid2].tick)
  37. // timer heap (binary heap of tid's)
  38. static BHEAP_VAR(int, timer_heap);
  39. // server startup time
  40. time_t start_time;
  41. /*----------------------------
  42. * Timer debugging
  43. *----------------------------*/
  44. struct timer_func_list {
  45. struct timer_func_list* next;
  46. TimerFunc func;
  47. char* name;
  48. } *tfl_root = nullptr;
  49. /// Sets the name of a timer function.
  50. int add_timer_func_list(TimerFunc func, const char* name)
  51. {
  52. struct timer_func_list* tfl;
  53. if (name) {
  54. for( tfl=tfl_root; tfl != nullptr; tfl=tfl->next )
  55. {// check suspicious cases
  56. if( func == tfl->func )
  57. ShowWarning("add_timer_func_list: duplicating function %p(%s) as %s.\n",tfl->func,tfl->name,name);
  58. else if( strcmp(name,tfl->name) == 0 )
  59. ShowWarning("add_timer_func_list: function %p has the same name as %p(%s)\n",func,tfl->func,tfl->name);
  60. }
  61. CREATE(tfl,struct timer_func_list,1);
  62. tfl->next = tfl_root;
  63. tfl->func = func;
  64. tfl->name = aStrdup(name);
  65. tfl_root = tfl;
  66. }
  67. return 0;
  68. }
  69. /// Returns the name of the timer function.
  70. const char* search_timer_func_list(TimerFunc func)
  71. {
  72. struct timer_func_list* tfl;
  73. for( tfl=tfl_root; tfl != nullptr; tfl=tfl->next )
  74. if (func == tfl->func)
  75. return tfl->name;
  76. return "unknown timer function";
  77. }
  78. /*----------------------------
  79. * Get tick time
  80. *----------------------------*/
  81. #if defined(ENABLE_RDTSC)
  82. static uint64 RDTSC_BEGINTICK = 0, RDTSC_CLOCK = 0;
  83. static __inline uint64 _rdtsc(){
  84. register union{
  85. uint64 qw;
  86. uint32 dw[2];
  87. } t;
  88. asm volatile("rdtsc":"=a"(t.dw[0]), "=d"(t.dw[1]) );
  89. return t.qw;
  90. }
  91. static void rdtsc_calibrate(){
  92. uint64 t1, t2;
  93. int32 i;
  94. ShowStatus("Calibrating Timer Source, please wait... ");
  95. RDTSC_CLOCK = 0;
  96. for(i = 0; i < 5; i++){
  97. t1 = _rdtsc();
  98. usleep(1000000); //1000 MS
  99. t2 = _rdtsc();
  100. RDTSC_CLOCK += (t2 - t1) / 1000;
  101. }
  102. RDTSC_CLOCK /= 5;
  103. RDTSC_BEGINTICK = _rdtsc();
  104. ShowMessage(" done. (Frequency: %u Mhz)\n", (uint32)(RDTSC_CLOCK/1000) );
  105. }
  106. #endif
  107. /// platform-abstracted tick retrieval
  108. static t_tick tick(void)
  109. {
  110. #if defined(WIN32)
  111. #ifdef DEPRECATED_WINDOWS_SUPPORT
  112. return GetTickCount();
  113. #else
  114. return GetTickCount64();
  115. #endif
  116. #elif defined(ENABLE_RDTSC)
  117. //
  118. return (unsigned int)((_rdtsc() - RDTSC_BEGINTICK) / RDTSC_CLOCK);
  119. //
  120. #elif defined(HAVE_MONOTONIC_CLOCK)
  121. struct timespec tval;
  122. clock_gettime(CLOCK_MONOTONIC, &tval);
  123. return tval.tv_sec * 1000 + tval.tv_nsec / 1000000;
  124. #else
  125. struct timeval tval;
  126. gettimeofday(&tval, nullptr);
  127. return tval.tv_sec * 1000 + tval.tv_usec / 1000;
  128. #endif
  129. }
  130. //////////////////////////////////////////////////////////////////////////
  131. #if defined(TICK_CACHE) && TICK_CACHE > 1
  132. //////////////////////////////////////////////////////////////////////////
  133. // tick is cached for TICK_CACHE calls
  134. static t_tick gettick_cache;
  135. static int gettick_count = 1;
  136. t_tick gettick_nocache(void)
  137. {
  138. gettick_count = TICK_CACHE;
  139. gettick_cache = tick();
  140. return gettick_cache;
  141. }
  142. t_tick gettick(void)
  143. {
  144. return ( --gettick_count == 0 ) ? gettick_nocache() : gettick_cache;
  145. }
  146. //////////////////////////////
  147. #else
  148. //////////////////////////////
  149. // tick doesn't get cached
  150. t_tick gettick_nocache(void)
  151. {
  152. return tick();
  153. }
  154. t_tick gettick(void)
  155. {
  156. return tick();
  157. }
  158. //////////////////////////////////////////////////////////////////////////
  159. #endif
  160. //////////////////////////////////////////////////////////////////////////
  161. /*======================================
  162. * CORE : Timer Heap
  163. *--------------------------------------*/
  164. /// Adds a timer to the timer_heap
  165. static void push_timer_heap(int tid)
  166. {
  167. BHEAP_ENSURE(timer_heap, 1, 256);
  168. BHEAP_PUSH(timer_heap, tid, DIFFTICK_MINTOPCMP);
  169. }
  170. /*==========================
  171. * Timer Management
  172. *--------------------------*/
  173. /// Returns a free timer id.
  174. static int acquire_timer(void)
  175. {
  176. int tid;
  177. // select a free timer
  178. if (free_timer_list_pos) {
  179. do {
  180. tid = free_timer_list[--free_timer_list_pos];
  181. } while(tid >= timer_data_num && free_timer_list_pos > 0);
  182. } else
  183. tid = timer_data_num;
  184. // check available space
  185. if( tid >= timer_data_num )
  186. for (tid = timer_data_num; tid < timer_data_max && timer_data[tid].type; tid++);
  187. if (tid >= timer_data_num && tid >= timer_data_max)
  188. {// expand timer array
  189. timer_data_max += 256;
  190. if( timer_data )
  191. RECREATE(timer_data, struct TimerData, timer_data_max);
  192. else
  193. CREATE(timer_data, struct TimerData, timer_data_max);
  194. memset(timer_data + (timer_data_max - 256), 0, sizeof(struct TimerData)*256);
  195. }
  196. if( tid >= timer_data_num )
  197. timer_data_num = tid + 1;
  198. return tid;
  199. }
  200. /// Starts a new timer that is deleted once it expires (single-use).
  201. /// Returns the timer's id.
  202. int add_timer(t_tick tick, TimerFunc func, int id, intptr_t data)
  203. {
  204. int tid;
  205. tid = acquire_timer();
  206. timer_data[tid].tick = tick;
  207. timer_data[tid].func = func;
  208. timer_data[tid].id = id;
  209. timer_data[tid].data = data;
  210. timer_data[tid].type = TIMER_ONCE_AUTODEL;
  211. timer_data[tid].interval = 1000;
  212. push_timer_heap(tid);
  213. return tid;
  214. }
  215. /// Starts a new timer that automatically restarts itself (infinite loop until manually removed).
  216. /// Returns the timer's id, or INVALID_TIMER if it fails.
  217. int add_timer_interval(t_tick tick, TimerFunc func, int id, intptr_t data, int interval)
  218. {
  219. int tid;
  220. if( interval < 1 )
  221. {
  222. ShowError("add_timer_interval: invalid interval (tick=%" PRtf " %p[%s] id=%d data=%" PRIdPTR " diff_tick=%d)\n", tick, func, search_timer_func_list(func), id, data, DIFF_TICK(tick, gettick()));
  223. return INVALID_TIMER;
  224. }
  225. tid = acquire_timer();
  226. timer_data[tid].tick = tick;
  227. timer_data[tid].func = func;
  228. timer_data[tid].id = id;
  229. timer_data[tid].data = data;
  230. timer_data[tid].type = TIMER_INTERVAL;
  231. timer_data[tid].interval = interval;
  232. push_timer_heap(tid);
  233. return tid;
  234. }
  235. /// Retrieves internal timer data
  236. const struct TimerData* get_timer(int tid)
  237. {
  238. return ( tid >= 0 && tid < timer_data_num ) ? &timer_data[tid] : nullptr;
  239. }
  240. /// Marks a timer specified by 'id' for immediate deletion once it expires.
  241. /// Param 'func' is used for debug/verification purposes.
  242. /// Returns 0 on success, < 0 on failure.
  243. int delete_timer(int tid, TimerFunc func)
  244. {
  245. if( tid < 0 || tid >= timer_data_num )
  246. {
  247. ShowError("delete_timer error : no such timer %d (%p(%s))\n", tid, func, search_timer_func_list(func));
  248. return -1;
  249. }
  250. if( timer_data[tid].func != func )
  251. {
  252. ShowError("delete_timer error : function mismatch %p(%s) != %p(%s)\n", timer_data[tid].func, search_timer_func_list(timer_data[tid].func), func, search_timer_func_list(func));
  253. return -2;
  254. }
  255. timer_data[tid].func = nullptr;
  256. timer_data[tid].type = TIMER_ONCE_AUTODEL;
  257. return 0;
  258. }
  259. /// Adjusts a timer's expiration time.
  260. /// Returns the new tick value, or -1 if it fails.
  261. t_tick addtick_timer(int tid, t_tick tick)
  262. {
  263. return settick_timer(tid, timer_data[tid].tick+tick);
  264. }
  265. /// Modifies a timer's expiration time (an alternative to deleting a timer and starting a new one).
  266. /// Returns the new tick value, or -1 if it fails.
  267. t_tick settick_timer(int tid, t_tick tick)
  268. {
  269. size_t i;
  270. // search timer position
  271. ARR_FIND(0, BHEAP_LENGTH(timer_heap), i, BHEAP_DATA(timer_heap)[i] == tid);
  272. if( i == BHEAP_LENGTH(timer_heap) )
  273. {
  274. ShowError("settick_timer: no such timer %d (%p(%s))\n", tid, timer_data[tid].func, search_timer_func_list(timer_data[tid].func));
  275. return -1;
  276. }
  277. if( tick == -1 )
  278. tick = 0;// add 1ms to avoid the error value -1
  279. if( timer_data[tid].tick == tick )
  280. return tick;// nothing to do, already in propper position
  281. // pop and push adjusted timer
  282. BHEAP_POPINDEX(timer_heap, i, DIFFTICK_MINTOPCMP);
  283. timer_data[tid].tick = tick;
  284. BHEAP_PUSH(timer_heap, tid, DIFFTICK_MINTOPCMP);
  285. return tick;
  286. }
  287. /// Executes all expired timers.
  288. /// Returns the value of the smallest non-expired timer (or 1 second if there aren't any).
  289. t_tick do_timer(t_tick tick)
  290. {
  291. t_tick diff = TIMER_MAX_INTERVAL; // return value
  292. // process all timers one by one
  293. while( BHEAP_LENGTH(timer_heap) )
  294. {
  295. int tid = BHEAP_PEEK(timer_heap);// top element in heap (smallest tick)
  296. diff = DIFF_TICK(timer_data[tid].tick, tick);
  297. if( diff > 0 )
  298. break; // no more expired timers to process
  299. // remove timer
  300. BHEAP_POP(timer_heap, DIFFTICK_MINTOPCMP);
  301. timer_data[tid].type |= TIMER_REMOVE_HEAP;
  302. if( timer_data[tid].func )
  303. {
  304. if( diff < -1000 )
  305. // timer was delayed for more than 1 second, use current tick instead
  306. timer_data[tid].func(tid, tick, timer_data[tid].id, timer_data[tid].data);
  307. else
  308. timer_data[tid].func(tid, timer_data[tid].tick, timer_data[tid].id, timer_data[tid].data);
  309. }
  310. // in the case the function didn't change anything...
  311. if( timer_data[tid].type & TIMER_REMOVE_HEAP )
  312. {
  313. timer_data[tid].type &= ~TIMER_REMOVE_HEAP;
  314. switch( timer_data[tid].type )
  315. {
  316. default:
  317. case TIMER_ONCE_AUTODEL:
  318. timer_data[tid].type = 0;
  319. if (free_timer_list_pos >= free_timer_list_max) {
  320. free_timer_list_max += 256;
  321. RECREATE(free_timer_list,int,free_timer_list_max);
  322. memset(free_timer_list + (free_timer_list_max - 256), 0, 256 * sizeof(int));
  323. }
  324. free_timer_list[free_timer_list_pos++] = tid;
  325. break;
  326. case TIMER_INTERVAL:
  327. if( DIFF_TICK(timer_data[tid].tick, tick) < -1000 )
  328. timer_data[tid].tick = tick + timer_data[tid].interval;
  329. else
  330. timer_data[tid].tick += timer_data[tid].interval;
  331. push_timer_heap(tid);
  332. break;
  333. }
  334. }
  335. }
  336. return cap_value(diff, TIMER_MIN_INTERVAL, TIMER_MAX_INTERVAL);
  337. }
  338. unsigned long get_uptime(void)
  339. {
  340. return (unsigned long)difftime(time(nullptr), start_time);
  341. }
  342. /**
  343. * Converting a timestamp is a srintf according to format
  344. * safefr then strftime as it ensure \0 at end of string
  345. * @param str, pointer to the destination string
  346. * @param size, max length of the string
  347. * @param timestamp, see unix epoch
  348. * @param format, format to convert timestamp on, see strftime format
  349. * @return the string of timestamp
  350. */
  351. const char* timestamp2string(char* str, size_t size, time_t timestamp, const char* format){
  352. size_t len = strftime(str, size, format, localtime(&timestamp));
  353. memset(str + len, '\0', size - len);
  354. return str;
  355. }
  356. /*
  357. * Split given timein into year, month, day, hour, minute, second
  358. */
  359. void split_time(int timein, int* year, int* month, int* day, int* hour, int* minute, int *second) {
  360. const int factor_min = 60;
  361. const int factor_hour = factor_min*60;
  362. const int factor_day = factor_hour*24;
  363. const int factor_month = 2629743; // Approx (30.44 days)
  364. const int factor_year = 31556926; // Approx (365.24 days)
  365. *year = timein/factor_year;
  366. timein -= *year*factor_year;
  367. *month = timein/factor_month;
  368. timein -= *month*factor_month;
  369. *day = timein/factor_day;
  370. timein -= *day*factor_day;
  371. *hour = timein/factor_hour;
  372. timein -= *hour*factor_hour;
  373. *minute = timein/factor_min;
  374. timein -= *minute*factor_min;
  375. *second = timein;
  376. *year = max(0,*year);
  377. *month = max(0,*month);
  378. *day = max(0,*day);
  379. *hour = max(0,*hour);
  380. *minute = max(0,*minute);
  381. *second = max(0,*second);
  382. }
  383. /*
  384. * Create a "timestamp" with the given argument
  385. */
  386. double solve_time(char* modif_p) {
  387. double totaltime = 0;
  388. struct tm then_tm;
  389. time_t now = time(nullptr);
  390. time_t then = now;
  391. then_tm = *localtime(&then);
  392. nullpo_retr(0,modif_p);
  393. while (modif_p[0] != '\0') {
  394. int value = atoi(modif_p);
  395. if (value == 0)
  396. modif_p++;
  397. else {
  398. if (modif_p[0] == '-' || modif_p[0] == '+')
  399. modif_p++;
  400. while (modif_p[0] >= '0' && modif_p[0] <= '9')
  401. modif_p++;
  402. if (modif_p[0] == 's') {
  403. then_tm.tm_sec += value;
  404. modif_p++;
  405. } else if (modif_p[0] == 'n') {
  406. then_tm.tm_min += value;
  407. modif_p++;
  408. } else if (modif_p[0] == 'm' && modif_p[1] == 'n') {
  409. then_tm.tm_min += value;
  410. modif_p = modif_p + 2;
  411. } else if (modif_p[0] == 'h') {
  412. then_tm.tm_hour += value;
  413. modif_p++;
  414. } else if (modif_p[0] == 'd' || modif_p[0] == 'j') {
  415. then_tm.tm_mday += value;
  416. modif_p++;
  417. } else if (modif_p[0] == 'm') {
  418. then_tm.tm_mon += value;
  419. modif_p++;
  420. } else if (modif_p[0] == 'y' || modif_p[0] == 'a') {
  421. then_tm.tm_year += value;
  422. modif_p++;
  423. } else if (modif_p[0] != '\0') {
  424. modif_p++;
  425. }
  426. }
  427. }
  428. then = mktime(&then_tm);
  429. totaltime = difftime(then,now);
  430. return totaltime;
  431. }
  432. void timer_init(void)
  433. {
  434. #if defined(ENABLE_RDTSC)
  435. rdtsc_calibrate();
  436. #endif
  437. time(&start_time);
  438. }
  439. void timer_final(void)
  440. {
  441. struct timer_func_list *tfl;
  442. struct timer_func_list *next;
  443. for( tfl=tfl_root; tfl != nullptr; tfl = next ) {
  444. next = tfl->next; // copy next pointer
  445. aFree(tfl->name); // free structures
  446. aFree(tfl);
  447. }
  448. if (timer_data) aFree(timer_data);
  449. BHEAP_CLEAR(timer_heap);
  450. if (free_timer_list) aFree(free_timer_list);
  451. }