timer.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include <sys/types.h>
  4. #include "../common/cbasetypes.h"
  5. #include "../common/malloc.h"
  6. #include "../common/showmsg.h"
  7. #include "timer.h"
  8. #ifdef WIN32
  9. //#define __USE_W32_SOCKETS
  10. // Well, this won't last another 30++ years (where conversion will truncate).
  11. //#define _USE_32BIT_TIME_T // use 32 bit time variables on 64bit windows
  12. //#include <windows.h>
  13. #include <winsock2.h>
  14. #else
  15. #include <sys/socket.h>
  16. #include <sys/time.h>
  17. #endif
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <time.h>
  22. // タイマー間隔の最小値。モンスターの大量召還時、多数のクライアント接続時に
  23. // サーバーが反応しなくなる場合は、TIMER_MIN_INTERVAL を増やしてください。
  24. // If the server shows no reaction when processing thousands of monsters
  25. // or connected by many clients, please increase TIMER_MIN_INTERVAL.
  26. #define TIMER_MIN_INTERVAL 50
  27. // timers
  28. static struct TimerData* timer_data = NULL;
  29. static int timer_data_max = 0;
  30. static int timer_data_num = 0;
  31. // free timers
  32. static int* free_timer_list = NULL;
  33. static int free_timer_list_max = 0;
  34. static int free_timer_list_pos = 0;
  35. //NOTE: using a binary heap should improve performance [FlavioJS]
  36. // timer heap (ordered array of tid's)
  37. static int timer_heap_num = 0;
  38. static int timer_heap_max = 0;
  39. static int* timer_heap = NULL;
  40. // searches for the target tick's position and stores it in pos (binary search)
  41. #define HEAP_SEARCH(target,from,to,pos) \
  42. do { \
  43. int max,pivot; \
  44. pos = from; \
  45. max = to; \
  46. while (pos < max) { \
  47. pivot = (pos + max) / 2; \
  48. if (DIFF_TICK(target, timer_data[timer_heap[pivot]].tick) < 0) \
  49. pos = pivot + 1; \
  50. else \
  51. max = pivot; \
  52. } \
  53. } while(0)
  54. // for debug
  55. struct timer_func_list {
  56. struct timer_func_list* next;
  57. TimerFunc func;
  58. char* name;
  59. };
  60. static struct timer_func_list* tfl_root = NULL;
  61. time_t start_time;
  62. /// Sets the name of a timer function.
  63. int add_timer_func_list(TimerFunc func, char* name)
  64. {
  65. struct timer_func_list* tfl;
  66. if (name) {
  67. for( tfl=tfl_root; tfl != NULL; tfl=tfl->next )
  68. {// check suspicious cases
  69. if( func == tfl->func )
  70. ShowWarning("add_timer_func_list: duplicating function %08x(%s) as %s.\n",(int)tfl->func,tfl->name,name);
  71. else if( strcmp(name,tfl->name) == 0 )
  72. ShowWarning("add_timer_func_list: function %08X has the same name as %08X(%s)\n",(int)func,(int)tfl->func,tfl->name);
  73. }
  74. CREATE(tfl,struct timer_func_list,1);
  75. tfl->next = tfl_root;
  76. tfl->func = func;
  77. tfl->name = aStrdup(name);
  78. tfl_root = tfl;
  79. }
  80. return 0;
  81. }
  82. /// Returns the name of the timer function.
  83. char* search_timer_func_list(TimerFunc func)
  84. {
  85. struct timer_func_list* tfl;
  86. for( tfl=tfl_root; tfl != NULL; tfl=tfl->next )
  87. if (func == tfl->func)
  88. return tfl->name;
  89. return "unknown timer function";
  90. }
  91. /*----------------------------
  92. * Get tick time
  93. *----------------------------*/
  94. static unsigned int gettick_cache;
  95. static int gettick_count;
  96. unsigned int gettick_nocache(void)
  97. {
  98. #ifdef _WIN32
  99. gettick_count = 256;
  100. return gettick_cache = GetTickCount();
  101. #else
  102. struct timeval tval;
  103. gettimeofday(&tval, NULL);
  104. gettick_count = 256;
  105. return gettick_cache = tval.tv_sec * 1000 + tval.tv_usec / 1000;
  106. #endif
  107. }
  108. unsigned int gettick(void)
  109. {
  110. if (--gettick_count < 0)
  111. return gettick_nocache();
  112. return gettick_cache;
  113. }
  114. /*======================================
  115. * CORE : Timer Heap
  116. *--------------------------------------*/
  117. /// Adds a timer to the timer_heap
  118. static void push_timer_heap(int tid)
  119. {
  120. unsigned int tick;
  121. int pos;
  122. int i;
  123. // check number of element
  124. if (timer_heap_num >= timer_heap_max) {
  125. if (timer_heap_max == 0) {
  126. timer_heap_max = 256;
  127. CREATE(timer_heap, int, 256);
  128. } else {
  129. timer_heap_max += 256;
  130. RECREATE(timer_heap, int, timer_heap_max);
  131. memset(timer_heap + (timer_heap_max - 256), 0, sizeof(int) * 256);
  132. }
  133. }
  134. // do a sorting from higher to lower
  135. tick = timer_data[tid].tick; // speed up
  136. // with less than 4 values, it's speeder to use simple loop
  137. if (timer_heap_num < 4) {
  138. for(i = timer_heap_num; i > 0; i--)
  139. {
  140. // if (j < timer_data[timer_heap[i - 1]].tick) //Plain comparisons break on bound looping timers. [Skotlex]
  141. if (DIFF_TICK(tick, timer_data[timer_heap[i - 1]].tick) < 0)
  142. break;
  143. else
  144. timer_heap[i] = timer_heap[i - 1];
  145. }
  146. timer_heap[i] = tid;
  147. // searching by dichotomy (binary search)
  148. } else {
  149. // if lower actual item is higher than new
  150. // if (j < timer_data[timer_heap[timer_heap_num - 1]].tick) //Plain comparisons break on bound looping timers. [Skotlex]
  151. if (DIFF_TICK(tick, timer_data[timer_heap[timer_heap_num - 1]].tick) < 0)
  152. timer_heap[timer_heap_num] = tid;
  153. else {
  154. // searching position
  155. HEAP_SEARCH(tick,0,timer_heap_num-1,pos);
  156. // move elements - do loop if there are a little number of elements to move
  157. if (timer_heap_num - pos < 5) {
  158. for(i = timer_heap_num; i > pos; i--)
  159. timer_heap[i] = timer_heap[i - 1];
  160. // move elements - else use memmove (speeder for a lot of elements)
  161. } else
  162. memmove(&timer_heap[pos + 1], &timer_heap[pos], sizeof(int) * (timer_heap_num - pos));
  163. // save new element
  164. timer_heap[pos] = tid;
  165. }
  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. if (free_timer_list_pos) {
  177. do {
  178. tid = free_timer_list[--free_timer_list_pos];
  179. } while(tid >= timer_data_num && free_timer_list_pos > 0);
  180. } else
  181. tid = timer_data_num;
  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. if (timer_data_max == 0)
  187. {// create timer data (1st time)
  188. timer_data_max = 256;
  189. CREATE(timer_data, struct TimerData, timer_data_max);
  190. } else
  191. {// add more timers
  192. timer_data_max += 256;
  193. RECREATE(timer_data, struct TimerData, timer_data_max);
  194. memset(timer_data + (timer_data_max - 256), 0, sizeof(struct TimerData) * 256);
  195. }
  196. }
  197. if (tid >= timer_data_num)
  198. timer_data_num = tid + 1;
  199. return tid;
  200. }
  201. int add_timer(unsigned int tick,TimerFunc func, int id, int data)
  202. {
  203. int tid = acquire_timer();
  204. timer_data[tid].tick = tick;
  205. timer_data[tid].func = func;
  206. timer_data[tid].id = id;
  207. timer_data[tid].data = data;
  208. timer_data[tid].type = TIMER_ONCE_AUTODEL;
  209. timer_data[tid].interval = 1000;
  210. push_timer_heap(tid);
  211. return tid;
  212. }
  213. int add_timer_interval(unsigned int tick, TimerFunc func, int id, int data, int interval)
  214. {
  215. int tid;
  216. if (interval < 1) {
  217. ShowError("add_timer_interval : function %08x(%s) has invalid interval %d!\n",
  218. (int)func, search_timer_func_list(func), interval);
  219. return -1;
  220. }
  221. tid = acquire_timer();
  222. timer_data[tid].tick = tick;
  223. timer_data[tid].func = func;
  224. timer_data[tid].id = id;
  225. timer_data[tid].data = data;
  226. timer_data[tid].type = TIMER_INTERVAL;
  227. timer_data[tid].interval = interval;
  228. push_timer_heap(tid);
  229. return tid;
  230. }
  231. //int delete_timer(int id, TimerFunc func)
  232. int delete_timer_sub(int id, TimerFunc func, const char* file, int line)
  233. {
  234. if (id <= 0 || id >= timer_data_num) {
  235. //ShowError("delete_timer error : no such timer %d (%08x(%s))\n", id, (int)func, search_timer_func_list(func));
  236. ShowError("delete_timer error : no such timer %d (%08x(%s)), invoked from %s:%d\n", id, (int)func, search_timer_func_list(func), file, line);
  237. return -1;
  238. }
  239. if (timer_data[id].func != func) {
  240. ShowError("delete_timer error : function mismatch %08x(%s) != %08x(%s)\n",
  241. (int)timer_data[id].func, search_timer_func_list(timer_data[id].func),
  242. (int)func, search_timer_func_list(func));
  243. return -2;
  244. }
  245. // そのうち消えるにまかせる
  246. timer_data[id].func = NULL;
  247. timer_data[id].type = TIMER_ONCE_AUTODEL;
  248. return 0;
  249. }
  250. int addtick_timer(int tid, unsigned int tick)
  251. {
  252. // Doesn't adjust the timer position. Might be the root of the FIXME in settick_timer. [FlavioJS]
  253. //return timer_data[tid].tick += tick;
  254. return settick_timer(tid, timer_data[tid].tick+tick);
  255. }
  256. //Sets the tick at which the timer triggers directly (meant as a replacement of delete_timer + add_timer) [Skotlex]
  257. //FIXME: DON'T use this function yet, it is not correctly reorganizing the timer stack causing unexpected problems later on!
  258. int settick_timer(int tid, unsigned int tick)
  259. {
  260. int old_pos,pos;
  261. unsigned int old_tick;
  262. old_tick = timer_data[tid].tick;
  263. if( old_tick == tick )
  264. return tick;
  265. //FIXME: This search is not all that effective... there doesn't seems to be a better way to locate an element in the heap.
  266. //for(i = timer_heap_num-1; i >= 0 && timer_heap[i] != tid; i--);
  267. // search old_tick position
  268. HEAP_SEARCH(old_tick,0,timer_heap_num-1,old_pos);
  269. while( timer_heap[old_pos] != tid )
  270. {// skip timers with the same tick
  271. if( DIFF_TICK(old_tick,timer_data[timer_heap[old_pos]].tick) != 0 )
  272. {
  273. ShowError("settick_timer: no such timer %d (%08x(%s))\n", tid, (int)timer_data[tid].func, search_timer_func_list(timer_data[tid].func));
  274. return -1;
  275. }
  276. ++old_pos;
  277. }
  278. if( DIFF_TICK(tick,timer_data[tid].tick) < 0 )
  279. {// Timer is accelerated, shift timer near the end of the heap.
  280. if (old_pos == timer_heap_num-1) //Nothing to shift.
  281. pos = old_pos;
  282. else {
  283. HEAP_SEARCH(tick,old_pos+1,timer_heap_num-1,pos);
  284. --pos;
  285. if (pos != old_pos)
  286. memmove(&timer_heap[old_pos], &timer_heap[old_pos+1], (pos-old_pos)*sizeof(int));
  287. }
  288. } else
  289. {// Timer is delayed, shift timer near the beginning of the heap.
  290. if (old_pos == 0) //Nothing to shift.
  291. pos = old_pos;
  292. else {
  293. HEAP_SEARCH(tick,0,old_pos-1,pos);
  294. ++pos;
  295. if (pos != old_pos)
  296. memmove(&timer_heap[pos+1], &timer_heap[pos], (old_pos-pos)*sizeof(int));
  297. }
  298. }
  299. timer_heap[pos] = tid;
  300. timer_data[tid].tick = tick;
  301. return tick;
  302. }
  303. struct TimerData* get_timer(int tid)
  304. {
  305. return &timer_data[tid];
  306. }
  307. //Correcting the heap when the tick overflows is an idea taken from jA to
  308. //prevent timer problems. Thanks to [End of Exam] for providing the required data. [Skotlex]
  309. //This funtion will rearrange the heap and assign new tick values.
  310. static void fix_timer_heap(unsigned int tick)
  311. {
  312. if (timer_heap_num >= 0 && tick < 0x00010000 && timer_data[timer_heap[0]].tick > 0xf0000000)
  313. { //The last timer is way too far into the future, and the current tick is too close to 0, overflow was very likely
  314. //(not perfect, but will work as long as the timer is not expected to happen 50 or so days into the future)
  315. int i;
  316. int *tmp_heap;
  317. for (i=0; i < timer_heap_num && timer_data[timer_heap[i]].tick > 0xf0000000; i++)
  318. { //All functions with high tick value should had been executed already...
  319. timer_data[timer_heap[i]].tick = 0;
  320. }
  321. //Move elements to readjust the heap.
  322. tmp_heap = aCalloc(sizeof(int), i);
  323. memcpy(tmp_heap, timer_heap, i*sizeof(int));
  324. memmove(timer_heap, &timer_heap[i], (timer_heap_num-i)*sizeof(int));
  325. memmove(&timer_heap[timer_heap_num-i], tmp_heap, i*sizeof(int));
  326. aFree(tmp_heap);
  327. }
  328. }
  329. int do_timer(unsigned int tick)
  330. {
  331. static int fix_heap_flag = 0; //Flag for fixing the stack only once per tick loop. May not be the best way, but it's all I can think of currently :X [Skotlex]
  332. int i, nextmin = 1000;
  333. if (tick < 0x010000 && fix_heap_flag)
  334. {
  335. fix_timer_heap(tick);
  336. fix_heap_flag = 0;
  337. }
  338. while(timer_heap_num) {
  339. i = timer_heap[timer_heap_num - 1]; // next shorter element
  340. if ((nextmin = DIFF_TICK(timer_data[i].tick, tick)) > 0)
  341. break;
  342. --timer_heap_num; // suppress the actual element from the table
  343. timer_data[i].type |= TIMER_REMOVE_HEAP;
  344. if (timer_data[i].func) {
  345. if (nextmin < -1000) {
  346. // 1秒以上の大幅な遅延が発生しているので、
  347. // timer処理タイミングを現在値とする事で
  348. // 呼び出し時タイミング(引数のtick)相対で処理してる
  349. // timer関数の次回処理タイミングを遅らせる
  350. timer_data[i].func(i, tick, timer_data[i].id, timer_data[i].data);
  351. } else {
  352. timer_data[i].func(i, timer_data[i].tick, timer_data[i].id, timer_data[i].data);
  353. }
  354. }
  355. if (timer_data[i].type & TIMER_REMOVE_HEAP) {
  356. switch(timer_data[i].type & ~TIMER_REMOVE_HEAP) {
  357. case TIMER_ONCE_AUTODEL:
  358. timer_data[i].type = 0;
  359. if (free_timer_list_pos >= free_timer_list_max) {
  360. free_timer_list_max += 256;
  361. RECREATE(free_timer_list,int,free_timer_list_max);
  362. memset(free_timer_list + (free_timer_list_max - 256), 0, 256 * sizeof(int));
  363. }
  364. free_timer_list[free_timer_list_pos++] = i;
  365. break;
  366. case TIMER_INTERVAL:
  367. if (DIFF_TICK(timer_data[i].tick , tick) < -1000) {
  368. timer_data[i].tick = tick + timer_data[i].interval;
  369. } else {
  370. timer_data[i].tick += timer_data[i].interval;
  371. }
  372. timer_data[i].type &= ~TIMER_REMOVE_HEAP;
  373. push_timer_heap(i);
  374. break;
  375. }
  376. }
  377. }
  378. if (nextmin < TIMER_MIN_INTERVAL)
  379. nextmin = TIMER_MIN_INTERVAL;
  380. if (UINT_MAX - nextmin < tick) //Tick will loop, rearrange the heap on the next iteration.
  381. fix_heap_flag = 1;
  382. return nextmin;
  383. }
  384. unsigned long get_uptime(void)
  385. {
  386. return (unsigned long)difftime(time(NULL), start_time);
  387. }
  388. void timer_init(void)
  389. {
  390. time(&start_time);
  391. }
  392. void timer_final(void)
  393. {
  394. struct timer_func_list *tfl;
  395. struct timer_func_list *next;
  396. for( tfl=tfl_root; tfl != NULL; tfl = next ) {
  397. next = tfl->next; // copy next pointer
  398. aFree(tfl->name); // free structures
  399. aFree(tfl);
  400. }
  401. if (timer_data) aFree(timer_data);
  402. if (timer_heap) aFree(timer_heap);
  403. if (free_timer_list) aFree(free_timer_list);
  404. }