timer.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "../common/cbasetypes.h"
  4. #include "../common/db.h"
  5. #include "../common/malloc.h"
  6. #include "../common/showmsg.h"
  7. #include "../common/utils.h"
  8. #include "timer.h"
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <time.h>
  13. #ifdef WIN32
  14. #include "../common/winapi.h" // GetTickCount()
  15. #else
  16. #include <unistd.h>
  17. #include <sys/time.h> // struct timeval, gettimeofday()
  18. #endif
  19. // If the server can't handle processing thousands of monsters
  20. // or many connected clients, please increase TIMER_MIN_INTERVAL.
  21. #define TIMER_MIN_INTERVAL 50
  22. #define TIMER_MAX_INTERVAL 1000
  23. // timers (array)
  24. static struct TimerData* timer_data = NULL;
  25. static int timer_data_max = 0;
  26. static int timer_data_num = 0;
  27. // free timers (array)
  28. static int* free_timer_list = NULL;
  29. static int free_timer_list_max = 0;
  30. static int free_timer_list_pos = 0;
  31. /// Comparator for the timer heap. (minimum tick at top)
  32. /// Returns negative if tid1's tick is smaller, positive if tid2's tick is smaller, 0 if equal.
  33. ///
  34. /// @param tid1 First timer
  35. /// @param tid2 Second timer
  36. /// @return negative if tid1 is top, positive if tid2 is top, 0 if equal
  37. #define DIFFTICK_MINTOPCMP(tid1,tid2) DIFF_TICK(timer_data[tid1].tick,timer_data[tid2].tick)
  38. // timer heap (binary heap of tid's)
  39. static BHEAP_VAR(int, timer_heap);
  40. // server startup time
  41. time_t start_time;
  42. /*----------------------------
  43. * Timer debugging
  44. *----------------------------*/
  45. struct timer_func_list {
  46. struct timer_func_list* next;
  47. TimerFunc func;
  48. char* name;
  49. } *tfl_root = NULL;
  50. /// Sets the name of a timer function.
  51. int add_timer_func_list(TimerFunc func, char* name)
  52. {
  53. struct timer_func_list* tfl;
  54. if (name) {
  55. for( tfl=tfl_root; tfl != NULL; tfl=tfl->next )
  56. {// check suspicious cases
  57. if( func == tfl->func )
  58. ShowWarning("add_timer_func_list: duplicating function %p(%s) as %s.\n",tfl->func,tfl->name,name);
  59. else if( strcmp(name,tfl->name) == 0 )
  60. ShowWarning("add_timer_func_list: function %p has the same name as %p(%s)\n",func,tfl->func,tfl->name);
  61. }
  62. CREATE(tfl,struct timer_func_list,1);
  63. tfl->next = tfl_root;
  64. tfl->func = func;
  65. tfl->name = aStrdup(name);
  66. tfl_root = tfl;
  67. }
  68. return 0;
  69. }
  70. /// Returns the name of the timer function.
  71. char* search_timer_func_list(TimerFunc func)
  72. {
  73. struct timer_func_list* tfl;
  74. for( tfl=tfl_root; tfl != NULL; tfl=tfl->next )
  75. if (func == tfl->func)
  76. return tfl->name;
  77. return "unknown timer function";
  78. }
  79. /*----------------------------
  80. * Get tick time
  81. *----------------------------*/
  82. #if defined(ENABLE_RDTSC)
  83. static uint64 RDTSC_BEGINTICK = 0, RDTSC_CLOCK = 0;
  84. static __inline uint64 _rdtsc(){
  85. register union{
  86. uint64 qw;
  87. uint32 dw[2];
  88. } t;
  89. asm volatile("rdtsc":"=a"(t.dw[0]), "=d"(t.dw[1]) );
  90. return t.qw;
  91. }
  92. static void rdtsc_calibrate(){
  93. uint64 t1, t2;
  94. int32 i;
  95. ShowStatus("Calibrating Timer Source, please wait... ");
  96. RDTSC_CLOCK = 0;
  97. for(i = 0; i < 5; i++){
  98. t1 = _rdtsc();
  99. usleep(1000000); //1000 MS
  100. t2 = _rdtsc();
  101. RDTSC_CLOCK += (t2 - t1) / 1000;
  102. }
  103. RDTSC_CLOCK /= 5;
  104. RDTSC_BEGINTICK = _rdtsc();
  105. ShowMessage(" done. (Frequency: %u Mhz)\n", (uint32)(RDTSC_CLOCK/1000) );
  106. }
  107. #endif
  108. /// platform-abstracted tick retrieval
  109. static unsigned int tick(void)
  110. {
  111. #if defined(WIN32)
  112. return GetTickCount();
  113. #elif defined(ENABLE_RDTSC)
  114. //
  115. return (unsigned int)((_rdtsc() - RDTSC_BEGINTICK) / RDTSC_CLOCK);
  116. //
  117. #elif defined(HAVE_MONOTONIC_CLOCK)
  118. struct timespec tval;
  119. clock_gettime(CLOCK_MONOTONIC, &tval);
  120. return tval.tv_sec * 1000 + tval.tv_nsec / 1000000;
  121. #else
  122. struct timeval tval;
  123. gettimeofday(&tval, NULL);
  124. return tval.tv_sec * 1000 + tval.tv_usec / 1000;
  125. #endif
  126. }
  127. //////////////////////////////////////////////////////////////////////////
  128. #if defined(TICK_CACHE) && TICK_CACHE > 1
  129. //////////////////////////////////////////////////////////////////////////
  130. // tick is cached for TICK_CACHE calls
  131. static unsigned int gettick_cache;
  132. static int gettick_count = 1;
  133. unsigned int gettick_nocache(void)
  134. {
  135. gettick_count = TICK_CACHE;
  136. gettick_cache = tick();
  137. return gettick_cache;
  138. }
  139. unsigned int gettick(void)
  140. {
  141. return ( --gettick_count == 0 ) ? gettick_nocache() : gettick_cache;
  142. }
  143. //////////////////////////////
  144. #else
  145. //////////////////////////////
  146. // tick doesn't get cached
  147. unsigned int gettick_nocache(void)
  148. {
  149. return tick();
  150. }
  151. unsigned int gettick(void)
  152. {
  153. return tick();
  154. }
  155. //////////////////////////////////////////////////////////////////////////
  156. #endif
  157. //////////////////////////////////////////////////////////////////////////
  158. /*======================================
  159. * CORE : Timer Heap
  160. *--------------------------------------*/
  161. /// Adds a timer to the timer_heap
  162. static void push_timer_heap(int tid)
  163. {
  164. BHEAP_ENSURE(timer_heap, 1, 256);
  165. BHEAP_PUSH(timer_heap, tid, DIFFTICK_MINTOPCMP);
  166. }
  167. /*==========================
  168. * Timer Management
  169. *--------------------------*/
  170. /// Returns a free timer id.
  171. static int acquire_timer(void)
  172. {
  173. int tid;
  174. // select a free timer
  175. if (free_timer_list_pos) {
  176. do {
  177. tid = free_timer_list[--free_timer_list_pos];
  178. } while(tid >= timer_data_num && free_timer_list_pos > 0);
  179. } else
  180. tid = timer_data_num;
  181. // check available space
  182. if( tid >= timer_data_num )
  183. for (tid = timer_data_num; tid < timer_data_max && timer_data[tid].type; tid++);
  184. if (tid >= timer_data_num && tid >= timer_data_max)
  185. {// expand timer array
  186. timer_data_max += 256;
  187. if( timer_data )
  188. RECREATE(timer_data, struct TimerData, timer_data_max);
  189. else
  190. CREATE(timer_data, struct TimerData, timer_data_max);
  191. memset(timer_data + (timer_data_max - 256), 0, sizeof(struct TimerData)*256);
  192. }
  193. if( tid >= timer_data_num )
  194. timer_data_num = tid + 1;
  195. return tid;
  196. }
  197. /// Starts a new timer that is deleted once it expires (single-use).
  198. /// Returns the timer's id.
  199. int add_timer(unsigned int tick, TimerFunc func, int id, intptr_t data)
  200. {
  201. int tid;
  202. tid = acquire_timer();
  203. timer_data[tid].tick = tick;
  204. timer_data[tid].func = func;
  205. timer_data[tid].id = id;
  206. timer_data[tid].data = data;
  207. timer_data[tid].type = TIMER_ONCE_AUTODEL;
  208. timer_data[tid].interval = 1000;
  209. push_timer_heap(tid);
  210. return tid;
  211. }
  212. /// Starts a new timer that automatically restarts itself (infinite loop until manually removed).
  213. /// Returns the timer's id, or INVALID_TIMER if it fails.
  214. int add_timer_interval(unsigned int tick, TimerFunc func, int id, intptr_t data, int interval)
  215. {
  216. int tid;
  217. if( interval < 1 )
  218. {
  219. ShowError("add_timer_interval: invalid interval (tick=%u %p[%s] id=%d data=%d diff_tick=%d)\n", tick, func, search_timer_func_list(func), id, data, DIFF_TICK(tick, gettick()));
  220. return INVALID_TIMER;
  221. }
  222. tid = acquire_timer();
  223. timer_data[tid].tick = tick;
  224. timer_data[tid].func = func;
  225. timer_data[tid].id = id;
  226. timer_data[tid].data = data;
  227. timer_data[tid].type = TIMER_INTERVAL;
  228. timer_data[tid].interval = interval;
  229. push_timer_heap(tid);
  230. return tid;
  231. }
  232. /// Retrieves internal timer data
  233. const struct TimerData* get_timer(int tid)
  234. {
  235. return ( tid >= 0 && tid < timer_data_num ) ? &timer_data[tid] : NULL;
  236. }
  237. /// Marks a timer specified by 'id' for immediate deletion once it expires.
  238. /// Param 'func' is used for debug/verification purposes.
  239. /// Returns 0 on success, < 0 on failure.
  240. int delete_timer(int tid, TimerFunc func)
  241. {
  242. if( tid < 0 || tid >= timer_data_num )
  243. {
  244. ShowError("delete_timer error : no such timer %d (%p(%s))\n", tid, func, search_timer_func_list(func));
  245. return -1;
  246. }
  247. if( timer_data[tid].func != func )
  248. {
  249. 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));
  250. return -2;
  251. }
  252. timer_data[tid].func = NULL;
  253. timer_data[tid].type = TIMER_ONCE_AUTODEL;
  254. return 0;
  255. }
  256. /// Adjusts a timer's expiration time.
  257. /// Returns the new tick value, or -1 if it fails.
  258. int addtick_timer(int tid, unsigned int tick)
  259. {
  260. return settick_timer(tid, timer_data[tid].tick+tick);
  261. }
  262. /// Modifies a timer's expiration time (an alternative to deleting a timer and starting a new one).
  263. /// Returns the new tick value, or -1 if it fails.
  264. int settick_timer(int tid, unsigned int tick)
  265. {
  266. size_t i;
  267. // search timer position
  268. ARR_FIND(0, BHEAP_LENGTH(timer_heap), i, BHEAP_DATA(timer_heap)[i] == tid);
  269. if( i == BHEAP_LENGTH(timer_heap) )
  270. {
  271. ShowError("settick_timer: no such timer %d (%p(%s))\n", tid, timer_data[tid].func, search_timer_func_list(timer_data[tid].func));
  272. return -1;
  273. }
  274. if( (int)tick == -1 )
  275. tick = 0;// add 1ms to avoid the error value -1
  276. if( timer_data[tid].tick == tick )
  277. return (int)tick;// nothing to do, already in propper position
  278. // pop and push adjusted timer
  279. BHEAP_POPINDEX(timer_heap, i, DIFFTICK_MINTOPCMP);
  280. timer_data[tid].tick = tick;
  281. BHEAP_PUSH(timer_heap, tid, DIFFTICK_MINTOPCMP);
  282. return (int)tick;
  283. }
  284. /// Executes all expired timers.
  285. /// Returns the value of the smallest non-expired timer (or 1 second if there aren't any).
  286. int do_timer(unsigned int tick)
  287. {
  288. int diff = TIMER_MAX_INTERVAL; // return value
  289. // process all timers one by one
  290. while( BHEAP_LENGTH(timer_heap) )
  291. {
  292. int tid = BHEAP_PEEK(timer_heap);// top element in heap (smallest tick)
  293. diff = DIFF_TICK(timer_data[tid].tick, tick);
  294. if( diff > 0 )
  295. break; // no more expired timers to process
  296. // remove timer
  297. BHEAP_POP(timer_heap, DIFFTICK_MINTOPCMP);
  298. timer_data[tid].type |= TIMER_REMOVE_HEAP;
  299. if( timer_data[tid].func )
  300. {
  301. if( diff < -1000 )
  302. // timer was delayed for more than 1 second, use current tick instead
  303. timer_data[tid].func(tid, tick, timer_data[tid].id, timer_data[tid].data);
  304. else
  305. timer_data[tid].func(tid, timer_data[tid].tick, timer_data[tid].id, timer_data[tid].data);
  306. }
  307. // in the case the function didn't change anything...
  308. if( timer_data[tid].type & TIMER_REMOVE_HEAP )
  309. {
  310. timer_data[tid].type &= ~TIMER_REMOVE_HEAP;
  311. switch( timer_data[tid].type )
  312. {
  313. default:
  314. case TIMER_ONCE_AUTODEL:
  315. timer_data[tid].type = 0;
  316. if (free_timer_list_pos >= free_timer_list_max) {
  317. free_timer_list_max += 256;
  318. RECREATE(free_timer_list,int,free_timer_list_max);
  319. memset(free_timer_list + (free_timer_list_max - 256), 0, 256 * sizeof(int));
  320. }
  321. free_timer_list[free_timer_list_pos++] = tid;
  322. break;
  323. case TIMER_INTERVAL:
  324. if( DIFF_TICK(timer_data[tid].tick, tick) < -1000 )
  325. timer_data[tid].tick = tick + timer_data[tid].interval;
  326. else
  327. timer_data[tid].tick += timer_data[tid].interval;
  328. push_timer_heap(tid);
  329. break;
  330. }
  331. }
  332. }
  333. return cap_value(diff, TIMER_MIN_INTERVAL, TIMER_MAX_INTERVAL);
  334. }
  335. unsigned long get_uptime(void)
  336. {
  337. return (unsigned long)difftime(time(NULL), start_time);
  338. }
  339. void timer_init(void)
  340. {
  341. #if defined(ENABLE_RDTSC)
  342. rdtsc_calibrate();
  343. #endif
  344. time(&start_time);
  345. }
  346. void timer_final(void)
  347. {
  348. struct timer_func_list *tfl;
  349. struct timer_func_list *next;
  350. for( tfl=tfl_root; tfl != NULL; tfl = next ) {
  351. next = tfl->next; // copy next pointer
  352. aFree(tfl->name); // free structures
  353. aFree(tfl);
  354. }
  355. if (timer_data) aFree(timer_data);
  356. BHEAP_CLEAR(timer_heap);
  357. if (free_timer_list) aFree(free_timer_list);
  358. }