timer.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. #define WIN32_LEAN_AND_MEAN
  15. #include <windows.h> // GetTickCount()
  16. #else
  17. #include <unistd.h>
  18. #include <sys/time.h> // struct timeval, gettimeofday()
  19. #endif
  20. // If the server can't handle processing thousands of monsters
  21. // or many connected clients, please increase TIMER_MIN_INTERVAL.
  22. #define TIMER_MIN_INTERVAL 50
  23. #define TIMER_MAX_INTERVAL 1000
  24. // timers (array)
  25. static struct TimerData* timer_data = NULL;
  26. static int timer_data_max = 0;
  27. static int timer_data_num = 0;
  28. // free timers (array)
  29. static int* free_timer_list = NULL;
  30. static int free_timer_list_max = 0;
  31. static int free_timer_list_pos = 0;
  32. // timer heap (ordered array of tid's)
  33. static int timer_heap_num = 0;
  34. static int timer_heap_max = 0;
  35. static int* timer_heap = NULL;
  36. // server startup time
  37. time_t start_time;
  38. /*----------------------------
  39. * Timer debugging
  40. *----------------------------*/
  41. struct timer_func_list {
  42. struct timer_func_list* next;
  43. TimerFunc func;
  44. char* name;
  45. } *tfl_root = NULL;
  46. /// Sets the name of a timer function.
  47. int add_timer_func_list(TimerFunc func, char* name)
  48. {
  49. struct timer_func_list* tfl;
  50. if (name) {
  51. for( tfl=tfl_root; tfl != NULL; tfl=tfl->next )
  52. {// check suspicious cases
  53. if( func == tfl->func )
  54. ShowWarning("add_timer_func_list: duplicating function %08x(%s) as %s.\n",(int)tfl->func,tfl->name,name);
  55. else if( strcmp(name,tfl->name) == 0 )
  56. ShowWarning("add_timer_func_list: function %08X has the same name as %08X(%s)\n",(int)func,(int)tfl->func,tfl->name);
  57. }
  58. CREATE(tfl,struct timer_func_list,1);
  59. tfl->next = tfl_root;
  60. tfl->func = func;
  61. tfl->name = aStrdup(name);
  62. tfl_root = tfl;
  63. }
  64. return 0;
  65. }
  66. /// Returns the name of the timer function.
  67. char* search_timer_func_list(TimerFunc func)
  68. {
  69. struct timer_func_list* tfl;
  70. for( tfl=tfl_root; tfl != NULL; tfl=tfl->next )
  71. if (func == tfl->func)
  72. return tfl->name;
  73. return "unknown timer function";
  74. }
  75. /*----------------------------
  76. * Get tick time
  77. *----------------------------*/
  78. /// platform-abstracted tick retrieval
  79. static unsigned int tick(void)
  80. {
  81. #if defined(WIN32)
  82. return GetTickCount();
  83. #elif (defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 && defined(_POSIX_MONOTONIC_CLOCK) /* posix compliant */) || (defined(__FreeBSD_cc_version) && __FreeBSD_cc_version >= 500005 /* FreeBSD >= 5.1.0 */)
  84. struct timespec tval;
  85. clock_gettime(CLOCK_MONOTONIC, &tval);
  86. return tval.tv_sec * 1000 + tval.tv_nsec / 1000000;
  87. #else
  88. struct timeval tval;
  89. gettimeofday(&tval, NULL);
  90. return tval.tv_sec * 1000 + tval.tv_usec / 1000;
  91. #endif
  92. }
  93. //////////////////////////////////////////////////////////////////////////
  94. #if defined(TICK_CACHE) && TICK_CACHE > 1
  95. //////////////////////////////////////////////////////////////////////////
  96. // tick is cached for TICK_CACHE calls
  97. static unsigned int gettick_cache;
  98. static int gettick_count = 1;
  99. unsigned int gettick_nocache(void)
  100. {
  101. gettick_count = TICK_CACHE;
  102. gettick_cache = tick();
  103. return gettick_cache;
  104. }
  105. unsigned int gettick(void)
  106. {
  107. return ( --gettick_count == 0 ) ? gettick_nocache() : gettick_cache;
  108. }
  109. //////////////////////////////
  110. #else
  111. //////////////////////////////
  112. // tick doesn't get cached
  113. unsigned int gettick_nocache(void)
  114. {
  115. return tick();
  116. }
  117. unsigned int gettick(void)
  118. {
  119. return tick();
  120. }
  121. //////////////////////////////////////////////////////////////////////////
  122. #endif
  123. //////////////////////////////////////////////////////////////////////////
  124. /*======================================
  125. * CORE : Timer Heap
  126. *--------------------------------------*/
  127. // searches for the target tick's position and stores it in pos (binary search)
  128. #define HEAP_SEARCH(target,from,to,pos) \
  129. do { \
  130. int max,pivot; \
  131. max = to; \
  132. pos = from; \
  133. while (pos < max) { \
  134. pivot = (pos + max) / 2; \
  135. if (DIFF_TICK(target, timer_data[timer_heap[pivot]].tick) < 0) \
  136. pos = pivot + 1; \
  137. else \
  138. max = pivot; \
  139. } \
  140. } while(0)
  141. /// Adds a timer to the timer_heap
  142. static void push_timer_heap(int tid)
  143. {
  144. int pos;
  145. // check available space
  146. if( timer_heap_num >= timer_heap_max )
  147. {
  148. timer_heap_max += 256;
  149. if( timer_heap )
  150. RECREATE(timer_heap, int, timer_heap_max);
  151. else
  152. CREATE(timer_heap, int, timer_heap_max);
  153. memset(timer_heap + (timer_heap_max - 256), 0, sizeof(int)*256);
  154. }
  155. // do a sorting from higher to lower
  156. if( timer_heap_num == 0 || DIFF_TICK(timer_data[tid].tick, timer_data[timer_heap[timer_heap_num - 1]].tick) < 0 )
  157. timer_heap[timer_heap_num] = tid; // if lower actual item is higher than new
  158. else
  159. {
  160. // searching position
  161. HEAP_SEARCH(timer_data[tid].tick,0,timer_heap_num-1,pos);
  162. // move elements
  163. memmove(&timer_heap[pos + 1], &timer_heap[pos], sizeof(int) * (timer_heap_num - pos));
  164. // save new element
  165. timer_heap[pos] = tid;
  166. }
  167. timer_heap_num++;
  168. }
  169. /*==========================
  170. * Timer Management
  171. *--------------------------*/
  172. /// Returns a free timer id.
  173. static int acquire_timer(void)
  174. {
  175. int tid;
  176. // select a free timer
  177. if (free_timer_list_pos) {
  178. do {
  179. tid = free_timer_list[--free_timer_list_pos];
  180. } while(tid >= timer_data_num && free_timer_list_pos > 0);
  181. } else
  182. tid = timer_data_num;
  183. // check available space
  184. if( tid >= timer_data_num )
  185. for (tid = timer_data_num; tid < timer_data_max && timer_data[tid].type; tid++);
  186. if (tid >= timer_data_num && tid >= timer_data_max)
  187. {// expand timer array
  188. timer_data_max += 256;
  189. if( timer_data )
  190. RECREATE(timer_data, struct TimerData, timer_data_max);
  191. else
  192. CREATE(timer_data, struct TimerData, timer_data_max);
  193. memset(timer_data + (timer_data_max - 256), 0, sizeof(struct TimerData)*256);
  194. }
  195. if( tid >= timer_data_num )
  196. timer_data_num = tid + 1;
  197. return tid;
  198. }
  199. /// Starts a new timer that is deleted once it expires (single-use).
  200. /// Returns the timer's id.
  201. int add_timer(unsigned int tick, TimerFunc func, int id, intptr data)
  202. {
  203. int tid;
  204. tid = acquire_timer();
  205. timer_data[tid].tick = tick;
  206. timer_data[tid].func = func;
  207. timer_data[tid].id = id;
  208. timer_data[tid].data = data;
  209. timer_data[tid].type = TIMER_ONCE_AUTODEL;
  210. timer_data[tid].interval = 1000;
  211. push_timer_heap(tid);
  212. return tid;
  213. }
  214. /// Starts a new timer that automatically restarts itself (infinite loop until manually removed).
  215. /// Returns the timer's id, or INVALID_TIMER if it fails.
  216. int add_timer_interval(unsigned int tick, TimerFunc func, int id, intptr data, int interval)
  217. {
  218. int tid;
  219. if( interval < 1 )
  220. {
  221. ShowError("add_timer_interval: invalid interval (tick=%u %08x[%s] id=%d data=%d diff_tick=%d)\n", tick, (int)func, search_timer_func_list(func), id, data, DIFF_TICK(tick, gettick()));
  222. return INVALID_TIMER;
  223. }
  224. tid = acquire_timer();
  225. timer_data[tid].tick = tick;
  226. timer_data[tid].func = func;
  227. timer_data[tid].id = id;
  228. timer_data[tid].data = data;
  229. timer_data[tid].type = TIMER_INTERVAL;
  230. timer_data[tid].interval = interval;
  231. push_timer_heap(tid);
  232. return tid;
  233. }
  234. /// Retrieves internal timer data
  235. const struct TimerData* get_timer(int tid)
  236. {
  237. return ( tid >= 0 && tid < timer_data_num ) ? &timer_data[tid] : NULL;
  238. }
  239. /// Marks a timer specified by 'id' for immediate deletion once it expires.
  240. /// Param 'func' is used for debug/verification purposes.
  241. /// Returns 0 on success, < 0 on failure.
  242. int delete_timer(int tid, TimerFunc func)
  243. {
  244. if( tid < 0 || tid >= timer_data_num )
  245. {
  246. ShowError("delete_timer error : no such timer %d (%08x(%s))\n", tid, (int)func, search_timer_func_list(func));
  247. return -1;
  248. }
  249. if( timer_data[tid].func != func )
  250. {
  251. ShowError("delete_timer error : function mismatch %08x(%s) != %08x(%s)\n", (int)timer_data[tid].func, search_timer_func_list(timer_data[tid].func), (int)func, search_timer_func_list(func));
  252. return -2;
  253. }
  254. timer_data[tid].func = NULL;
  255. timer_data[tid].type = TIMER_ONCE_AUTODEL;
  256. return 0;
  257. }
  258. /// Adjusts a timer's expiration time.
  259. /// Returns the new tick value, or -1 if it fails.
  260. int addtick_timer(int tid, unsigned int tick)
  261. {
  262. return settick_timer(tid, timer_data[tid].tick+tick);
  263. }
  264. /// Modifies a timer's expiration time (an alternative to deleting a timer and starting a new one).
  265. /// Returns the new tick value, or -1 if it fails.
  266. int settick_timer(int tid, unsigned int tick)
  267. {
  268. int old_pos,pos;
  269. unsigned int old_tick;
  270. old_tick = timer_data[tid].tick;
  271. if( old_tick == tick )
  272. return tick;
  273. // search old_tick position
  274. HEAP_SEARCH(old_tick,0,timer_heap_num-1,old_pos);
  275. while( timer_heap[old_pos] != tid )
  276. {// skip timers with the same tick
  277. if( old_tick != timer_data[timer_heap[old_pos]].tick )
  278. {
  279. ShowError("settick_timer: no such timer %d (%08x(%s))\n", tid, (int)timer_data[tid].func, search_timer_func_list(timer_data[tid].func));
  280. return -1;
  281. }
  282. ++old_pos;
  283. }
  284. if( DIFF_TICK(tick,timer_data[tid].tick) < 0 )
  285. {// Timer is accelerated, shift timer near the end of the heap.
  286. if (old_pos == timer_heap_num-1) //Nothing to shift.
  287. pos = old_pos;
  288. else {
  289. HEAP_SEARCH(tick,old_pos+1,timer_heap_num-1,pos);
  290. --pos;
  291. if (pos != old_pos)
  292. memmove(&timer_heap[old_pos], &timer_heap[old_pos+1], (pos-old_pos)*sizeof(int));
  293. }
  294. } else
  295. {// Timer is delayed, shift timer near the beginning of the heap.
  296. if (old_pos == 0) //Nothing to shift.
  297. pos = old_pos;
  298. else {
  299. HEAP_SEARCH(tick,0,old_pos-1,pos);
  300. ++pos;
  301. if (pos != old_pos)
  302. memmove(&timer_heap[pos+1], &timer_heap[pos], (old_pos-pos)*sizeof(int));
  303. }
  304. }
  305. timer_heap[pos] = tid;
  306. timer_data[tid].tick = tick;
  307. return tick;
  308. }
  309. /// Executes all expired timers.
  310. /// Returns the value of the smallest non-expired timer (or 1 second if there aren't any).
  311. int do_timer(unsigned int tick)
  312. {
  313. int diff = 1000; // return value
  314. // process all timers one by one
  315. while( timer_heap_num )
  316. {
  317. int tid = timer_heap[timer_heap_num - 1]; // last element in heap (smallest tick)
  318. diff = DIFF_TICK(timer_data[tid].tick, tick);
  319. if( diff > 0 )
  320. break; // no more expired timers to process
  321. --timer_heap_num; // suppress the actual element from the table
  322. // mark timer as 'to be removed'
  323. timer_data[tid].type |= TIMER_REMOVE_HEAP;
  324. if( timer_data[tid].func )
  325. {
  326. if( diff < -1000 )
  327. // 1秒以上の大幅な遅延が発生しているので、
  328. // timer処理タイミングを現在値とする事で
  329. // 呼び出し時タイミング(引数のtick)相対で処理してる
  330. // timer関数の次回処理タイミングを遅らせる
  331. timer_data[tid].func(tid, tick, timer_data[tid].id, timer_data[tid].data);
  332. else
  333. timer_data[tid].func(tid, timer_data[tid].tick, timer_data[tid].id, timer_data[tid].data);
  334. }
  335. // in the case the function didn't change anything...
  336. if( timer_data[tid].type & TIMER_REMOVE_HEAP )
  337. {
  338. timer_data[tid].type &= ~TIMER_REMOVE_HEAP;
  339. switch( timer_data[tid].type )
  340. {
  341. case TIMER_ONCE_AUTODEL:
  342. timer_data[tid].type = 0;
  343. if (free_timer_list_pos >= free_timer_list_max) {
  344. free_timer_list_max += 256;
  345. RECREATE(free_timer_list,int,free_timer_list_max);
  346. memset(free_timer_list + (free_timer_list_max - 256), 0, 256 * sizeof(int));
  347. }
  348. free_timer_list[free_timer_list_pos++] = tid;
  349. break;
  350. case TIMER_INTERVAL:
  351. if( DIFF_TICK(timer_data[tid].tick, tick) < -1000 )
  352. timer_data[tid].tick = tick + timer_data[tid].interval;
  353. else
  354. timer_data[tid].tick += timer_data[tid].interval;
  355. timer_data[tid].type &= ~TIMER_REMOVE_HEAP;
  356. push_timer_heap(tid);
  357. break;
  358. }
  359. }
  360. }
  361. return cap_value(diff, TIMER_MIN_INTERVAL, TIMER_MAX_INTERVAL);
  362. }
  363. unsigned long get_uptime(void)
  364. {
  365. return (unsigned long)difftime(time(NULL), start_time);
  366. }
  367. void timer_init(void)
  368. {
  369. time(&start_time);
  370. }
  371. void timer_final(void)
  372. {
  373. struct timer_func_list *tfl;
  374. struct timer_func_list *next;
  375. for( tfl=tfl_root; tfl != NULL; tfl = next ) {
  376. next = tfl->next; // copy next pointer
  377. aFree(tfl->name); // free structures
  378. aFree(tfl);
  379. }
  380. if (timer_data) aFree(timer_data);
  381. if (timer_heap) aFree(timer_heap);
  382. if (free_timer_list) aFree(free_timer_list);
  383. }