timer.c 14 KB

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