timer.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "cbasetypes.h"
  4. #include "db.h"
  5. #include "malloc.h"
  6. #include "showmsg.h"
  7. #include "utils.h"
  8. #include "nullpo.h"
  9. #include "timer.h"
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #ifdef WIN32
  13. #include "winapi.hpp" // GetTickCount()
  14. #else
  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. #define TIMER_MIN_INTERVAL 20
  21. #define TIMER_MAX_INTERVAL 1000
  22. // timers (array)
  23. static struct TimerData* timer_data = NULL;
  24. static int timer_data_max = 0;
  25. static int timer_data_num = 0;
  26. // free timers (array)
  27. static int* free_timer_list = NULL;
  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 = NULL;
  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 != NULL; 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. char* search_timer_func_list(TimerFunc func)
  71. {
  72. struct timer_func_list* tfl;
  73. for( tfl=tfl_root; tfl != NULL; 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 unsigned int tick(void)
  109. {
  110. #if defined(WIN32)
  111. return GetTickCount();
  112. #elif defined(ENABLE_RDTSC)
  113. //
  114. return (unsigned int)((_rdtsc() - RDTSC_BEGINTICK) / RDTSC_CLOCK);
  115. //
  116. #elif defined(HAVE_MONOTONIC_CLOCK)
  117. struct timespec tval;
  118. clock_gettime(CLOCK_MONOTONIC, &tval);
  119. return tval.tv_sec * 1000 + tval.tv_nsec / 1000000;
  120. #else
  121. struct timeval tval;
  122. gettimeofday(&tval, NULL);
  123. return tval.tv_sec * 1000 + tval.tv_usec / 1000;
  124. #endif
  125. }
  126. //////////////////////////////////////////////////////////////////////////
  127. #if defined(TICK_CACHE) && TICK_CACHE > 1
  128. //////////////////////////////////////////////////////////////////////////
  129. // tick is cached for TICK_CACHE calls
  130. static unsigned int gettick_cache;
  131. static int gettick_count = 1;
  132. unsigned int gettick_nocache(void)
  133. {
  134. gettick_count = TICK_CACHE;
  135. gettick_cache = tick();
  136. return gettick_cache;
  137. }
  138. unsigned int gettick(void)
  139. {
  140. return ( --gettick_count == 0 ) ? gettick_nocache() : gettick_cache;
  141. }
  142. //////////////////////////////
  143. #else
  144. //////////////////////////////
  145. // tick doesn't get cached
  146. unsigned int gettick_nocache(void)
  147. {
  148. return tick();
  149. }
  150. unsigned int gettick(void)
  151. {
  152. return tick();
  153. }
  154. //////////////////////////////////////////////////////////////////////////
  155. #endif
  156. //////////////////////////////////////////////////////////////////////////
  157. /*======================================
  158. * CORE : Timer Heap
  159. *--------------------------------------*/
  160. /// Adds a timer to the timer_heap
  161. static void push_timer_heap(int tid)
  162. {
  163. BHEAP_ENSURE(timer_heap, 1, 256);
  164. BHEAP_PUSH(timer_heap, tid, DIFFTICK_MINTOPCMP, SWAP);
  165. }
  166. /*==========================
  167. * Timer Management
  168. *--------------------------*/
  169. /// Returns a free timer id.
  170. static int acquire_timer(void)
  171. {
  172. int tid;
  173. // select a free timer
  174. if (free_timer_list_pos) {
  175. do {
  176. tid = free_timer_list[--free_timer_list_pos];
  177. } while(tid >= timer_data_num && free_timer_list_pos > 0);
  178. } else
  179. tid = timer_data_num;
  180. // check available space
  181. if( tid >= timer_data_num )
  182. for (tid = timer_data_num; tid < timer_data_max && timer_data[tid].type; tid++);
  183. if (tid >= timer_data_num && tid >= timer_data_max)
  184. {// expand timer array
  185. timer_data_max += 256;
  186. if( timer_data )
  187. RECREATE(timer_data, struct TimerData, timer_data_max);
  188. else
  189. CREATE(timer_data, struct TimerData, timer_data_max);
  190. memset(timer_data + (timer_data_max - 256), 0, sizeof(struct TimerData)*256);
  191. }
  192. if( tid >= timer_data_num )
  193. timer_data_num = tid + 1;
  194. return tid;
  195. }
  196. /// Starts a new timer that is deleted once it expires (single-use).
  197. /// Returns the timer's id.
  198. int add_timer(unsigned int tick, TimerFunc func, int id, intptr_t data)
  199. {
  200. int tid;
  201. tid = acquire_timer();
  202. timer_data[tid].tick = tick;
  203. timer_data[tid].func = func;
  204. timer_data[tid].id = id;
  205. timer_data[tid].data = data;
  206. timer_data[tid].type = TIMER_ONCE_AUTODEL;
  207. timer_data[tid].interval = 1000;
  208. push_timer_heap(tid);
  209. return tid;
  210. }
  211. /// Starts a new timer that automatically restarts itself (infinite loop until manually removed).
  212. /// Returns the timer's id, or INVALID_TIMER if it fails.
  213. int add_timer_interval(unsigned int tick, TimerFunc func, int id, intptr_t data, int interval)
  214. {
  215. int tid;
  216. if( interval < 1 )
  217. {
  218. 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()));
  219. return INVALID_TIMER;
  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. /// Retrieves internal timer data
  232. const struct TimerData* get_timer(int tid)
  233. {
  234. return ( tid >= 0 && tid < timer_data_num ) ? &timer_data[tid] : NULL;
  235. }
  236. /// Marks a timer specified by 'id' for immediate deletion once it expires.
  237. /// Param 'func' is used for debug/verification purposes.
  238. /// Returns 0 on success, < 0 on failure.
  239. int delete_timer(int tid, TimerFunc func)
  240. {
  241. if( tid < 0 || tid >= timer_data_num )
  242. {
  243. ShowError("delete_timer error : no such timer %d (%p(%s))\n", tid, func, search_timer_func_list(func));
  244. return -1;
  245. }
  246. if( timer_data[tid].func != func )
  247. {
  248. 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));
  249. return -2;
  250. }
  251. timer_data[tid].func = NULL;
  252. timer_data[tid].type = TIMER_ONCE_AUTODEL;
  253. return 0;
  254. }
  255. /// Adjusts a timer's expiration time.
  256. /// Returns the new tick value, or -1 if it fails.
  257. int addtick_timer(int tid, unsigned int tick)
  258. {
  259. return settick_timer(tid, timer_data[tid].tick+tick);
  260. }
  261. /// Modifies a timer's expiration time (an alternative to deleting a timer and starting a new one).
  262. /// Returns the new tick value, or -1 if it fails.
  263. int settick_timer(int tid, unsigned int tick)
  264. {
  265. size_t i;
  266. // search timer position
  267. ARR_FIND(0, BHEAP_LENGTH(timer_heap), i, BHEAP_DATA(timer_heap)[i] == tid);
  268. if( i == BHEAP_LENGTH(timer_heap) )
  269. {
  270. ShowError("settick_timer: no such timer %d (%p(%s))\n", tid, timer_data[tid].func, search_timer_func_list(timer_data[tid].func));
  271. return -1;
  272. }
  273. if( (int)tick == -1 )
  274. tick = 0;// add 1ms to avoid the error value -1
  275. if( timer_data[tid].tick == tick )
  276. return (int)tick;// nothing to do, already in propper position
  277. // pop and push adjusted timer
  278. BHEAP_POPINDEX(timer_heap, i, DIFFTICK_MINTOPCMP, SWAP);
  279. timer_data[tid].tick = tick;
  280. BHEAP_PUSH(timer_heap, tid, DIFFTICK_MINTOPCMP, SWAP);
  281. return (int)tick;
  282. }
  283. /// Executes all expired timers.
  284. /// Returns the value of the smallest non-expired timer (or 1 second if there aren't any).
  285. int do_timer(unsigned int tick)
  286. {
  287. int diff = TIMER_MAX_INTERVAL; // return value
  288. // process all timers one by one
  289. while( BHEAP_LENGTH(timer_heap) )
  290. {
  291. int tid = BHEAP_PEEK(timer_heap);// top element in heap (smallest tick)
  292. diff = DIFF_TICK(timer_data[tid].tick, tick);
  293. if( diff > 0 )
  294. break; // no more expired timers to process
  295. // remove timer
  296. BHEAP_POP(timer_heap, DIFFTICK_MINTOPCMP, SWAP);
  297. timer_data[tid].type |= TIMER_REMOVE_HEAP;
  298. if( timer_data[tid].func )
  299. {
  300. if( diff < -1000 )
  301. // timer was delayed for more than 1 second, use current tick instead
  302. timer_data[tid].func(tid, tick, timer_data[tid].id, timer_data[tid].data);
  303. else
  304. timer_data[tid].func(tid, timer_data[tid].tick, timer_data[tid].id, timer_data[tid].data);
  305. }
  306. // in the case the function didn't change anything...
  307. if( timer_data[tid].type & TIMER_REMOVE_HEAP )
  308. {
  309. timer_data[tid].type &= ~TIMER_REMOVE_HEAP;
  310. switch( timer_data[tid].type )
  311. {
  312. default:
  313. case TIMER_ONCE_AUTODEL:
  314. timer_data[tid].type = 0;
  315. if (free_timer_list_pos >= free_timer_list_max) {
  316. free_timer_list_max += 256;
  317. RECREATE(free_timer_list,int,free_timer_list_max);
  318. memset(free_timer_list + (free_timer_list_max - 256), 0, 256 * sizeof(int));
  319. }
  320. free_timer_list[free_timer_list_pos++] = tid;
  321. break;
  322. case TIMER_INTERVAL:
  323. if( DIFF_TICK(timer_data[tid].tick, tick) < -1000 )
  324. timer_data[tid].tick = tick + timer_data[tid].interval;
  325. else
  326. timer_data[tid].tick += timer_data[tid].interval;
  327. push_timer_heap(tid);
  328. break;
  329. }
  330. }
  331. }
  332. return cap_value(diff, TIMER_MIN_INTERVAL, TIMER_MAX_INTERVAL);
  333. }
  334. unsigned long get_uptime(void)
  335. {
  336. return (unsigned long)difftime(time(NULL), start_time);
  337. }
  338. /**
  339. * Converting a timestamp is a srintf according to format
  340. * safefr then strftime as it ensure \0 at end of string
  341. * @param str, pointer to the destination string
  342. * @param size, max length of the string
  343. * @param timestamp, see unix epoch
  344. * @param format, format to convert timestamp on, see strftime format
  345. * @return the string of timestamp
  346. */
  347. const char* timestamp2string(char* str, size_t size, time_t timestamp, const char* format){
  348. size_t len = strftime(str, size, format, localtime(&timestamp));
  349. memset(str + len, '\0', size - len);
  350. return str;
  351. }
  352. /*
  353. * Split given timein into year, month, day, hour, minute, second
  354. */
  355. void split_time(int timein, int* year, int* month, int* day, int* hour, int* minute, int *second) {
  356. const int factor_min = 60;
  357. const int factor_hour = factor_min*60;
  358. const int factor_day = factor_hour*24;
  359. const int factor_month = 2629743; // Approx (30.44 days)
  360. const int factor_year = 31556926; // Approx (365.24 days)
  361. *year = timein/factor_year;
  362. timein -= *year*factor_year;
  363. *month = timein/factor_month;
  364. timein -= *month*factor_month;
  365. *day = timein/factor_day;
  366. timein -= *day*factor_day;
  367. *hour = timein/factor_hour;
  368. timein -= *hour*factor_hour;
  369. *minute = timein/factor_min;
  370. timein -= *minute*factor_min;
  371. *second = timein;
  372. *year = max(0,*year);
  373. *month = max(0,*month);
  374. *day = max(0,*day);
  375. *hour = max(0,*hour);
  376. *minute = max(0,*minute);
  377. *second = max(0,*second);
  378. }
  379. /*
  380. * Create a "timestamp" with the given argument
  381. */
  382. double solve_time(char* modif_p) {
  383. double totaltime = 0;
  384. struct tm then_tm;
  385. time_t now = time(NULL);
  386. time_t then = now;
  387. then_tm = *localtime(&then);
  388. nullpo_retr(0,modif_p);
  389. while (modif_p[0] != '\0') {
  390. int value = atoi(modif_p);
  391. if (value == 0)
  392. modif_p++;
  393. else {
  394. if (modif_p[0] == '-' || modif_p[0] == '+')
  395. modif_p++;
  396. while (modif_p[0] >= '0' && modif_p[0] <= '9')
  397. modif_p++;
  398. if (modif_p[0] == 's') {
  399. then_tm.tm_sec += value;
  400. modif_p++;
  401. } else if (modif_p[0] == 'n') {
  402. then_tm.tm_min += value;
  403. modif_p++;
  404. } else if (modif_p[0] == 'm' && modif_p[1] == 'n') {
  405. then_tm.tm_min += value;
  406. modif_p = modif_p + 2;
  407. } else if (modif_p[0] == 'h') {
  408. then_tm.tm_hour += value;
  409. modif_p++;
  410. } else if (modif_p[0] == 'd' || modif_p[0] == 'j') {
  411. then_tm.tm_mday += value;
  412. modif_p++;
  413. } else if (modif_p[0] == 'm') {
  414. then_tm.tm_mon += value;
  415. modif_p++;
  416. } else if (modif_p[0] == 'y' || modif_p[0] == 'a') {
  417. then_tm.tm_year += value;
  418. modif_p++;
  419. } else if (modif_p[0] != '\0') {
  420. modif_p++;
  421. }
  422. }
  423. }
  424. then = mktime(&then_tm);
  425. totaltime = difftime(then,now);
  426. return totaltime;
  427. }
  428. void timer_init(void)
  429. {
  430. #if defined(ENABLE_RDTSC)
  431. rdtsc_calibrate();
  432. #endif
  433. time(&start_time);
  434. }
  435. void timer_final(void)
  436. {
  437. struct timer_func_list *tfl;
  438. struct timer_func_list *next;
  439. for( tfl=tfl_root; tfl != NULL; tfl = next ) {
  440. next = tfl->next; // copy next pointer
  441. aFree(tfl->name); // free structures
  442. aFree(tfl);
  443. }
  444. if (timer_data) aFree(timer_data);
  445. BHEAP_CLEAR(timer_heap);
  446. if (free_timer_list) aFree(free_timer_list);
  447. }