Newer
Older
SCADA / plc / GRFICS_Workstation_Docs / Documents / attack / build / plc_main.c
root on 8 May 2022 24 KB playing with modbus day #1
  1. /**
  2. * Head of code common to all C targets
  3. **/
  4.  
  5. #include "beremiz.h"
  6. #include <string.h>
  7. /*
  8. * Prototypes of functions provided by generated C softPLC
  9. **/
  10. void config_run__(unsigned long tick);
  11. void config_init__(void);
  12.  
  13. /*
  14. * Prototypes of functions provided by generated target C code
  15. * */
  16. long long AtomicCompareExchange64(long long*, long long, long long);
  17. void __init_debug(void);
  18. void __cleanup_debug(void);
  19. /*void __retrieve_debug(void);*/
  20. void __publish_debug(void);
  21.  
  22. /*
  23. * Variables used by generated C softPLC and plugins
  24. **/
  25. IEC_TIME __CURRENT_TIME;
  26. IEC_BOOL __DEBUG = 0;
  27. unsigned long __tick = 0;
  28. char *PLC_ID = NULL;
  29.  
  30. /*
  31. * Variable generated by C softPLC and plugins
  32. **/
  33. extern unsigned long greatest_tick_count__;
  34.  
  35. /* Help to quit cleanly when init fail at a certain level */
  36. static int init_level = 0;
  37.  
  38. /*
  39. * Prototypes of functions exported by plugins
  40. **/
  41. int __init_py_ext(int argc,char **argv);
  42. void __cleanup_py_ext(void);
  43. void __retrieve_py_ext(void);
  44. void __publish_py_ext(void);
  45.  
  46. /*
  47. * Retrieve input variables, run PLC and publish output variables
  48. **/
  49. void __run(void)
  50. {
  51. __tick++;
  52. if (greatest_tick_count__)
  53. __tick %= greatest_tick_count__;
  54.  
  55. __retrieve_py_ext();
  56.  
  57. /*__retrieve_debug();*/
  58.  
  59. config_run__(__tick);
  60.  
  61. __publish_debug();
  62.  
  63. __publish_py_ext();
  64.  
  65. }
  66.  
  67. /*
  68. * Initialize variables according to PLC's default values,
  69. * and then init plugins with that values
  70. **/
  71. int __init(int argc,char **argv)
  72. {
  73. int res = 0;
  74. init_level = 0;
  75. /* Effective tick time with 1ms default value */
  76. if(!common_ticktime__)
  77. common_ticktime__ = 1000000;
  78.  
  79. config_init__();
  80. __init_debug();
  81. init_level=1; if((res = __init_py_ext(argc,argv))){return res;}
  82. return res;
  83. }
  84. /*
  85. * Calls plugin cleanup proc.
  86. **/
  87. void __cleanup(void)
  88. {
  89. if(init_level >= 1) __cleanup_py_ext();
  90. __cleanup_debug();
  91. }
  92.  
  93. void PLC_GetTime(IEC_TIME *CURRENT_TIME);
  94. void PLC_SetTimer(unsigned long long next, unsigned long long period);
  95.  
  96.  
  97.  
  98. /**
  99. * Linux specific code
  100. **/
  101.  
  102. #include <stdio.h>
  103. #include <string.h>
  104. #include <time.h>
  105. #include <signal.h>
  106. #include <stdlib.h>
  107. #include <pthread.h>
  108. #include <locale.h>
  109. #include <semaphore.h>
  110.  
  111. static sem_t Run_PLC;
  112.  
  113. long AtomicCompareExchange(long* atomicvar,long compared, long exchange)
  114. {
  115. return __sync_val_compare_and_swap(atomicvar, compared, exchange);
  116. }
  117. long long AtomicCompareExchange64(long long* atomicvar, long long compared, long long exchange)
  118. {
  119. return __sync_val_compare_and_swap(atomicvar, compared, exchange);
  120. }
  121.  
  122. void PLC_GetTime(IEC_TIME *CURRENT_TIME)
  123. {
  124. struct timespec tmp;
  125. clock_gettime(CLOCK_REALTIME, &tmp);
  126. CURRENT_TIME->tv_sec = tmp.tv_sec;
  127. CURRENT_TIME->tv_nsec = tmp.tv_nsec;
  128. }
  129.  
  130. void PLC_timer_notify(sigval_t val)
  131. {
  132. PLC_GetTime(&__CURRENT_TIME);
  133. sem_post(&Run_PLC);
  134. }
  135.  
  136. timer_t PLC_timer;
  137.  
  138. void PLC_SetTimer(unsigned long long next, unsigned long long period)
  139. {
  140. struct itimerspec timerValues;
  141. /*
  142. printf("SetTimer(%lld,%lld)\n",next, period);
  143. */
  144. memset (&timerValues, 0, sizeof (struct itimerspec));
  145. {
  146. #ifdef __lldiv_t_defined
  147. lldiv_t nxt_div = lldiv(next, 1000000000);
  148. lldiv_t period_div = lldiv(period, 1000000000);
  149. timerValues.it_value.tv_sec = nxt_div.quot;
  150. timerValues.it_value.tv_nsec = nxt_div.rem;
  151. timerValues.it_interval.tv_sec = period_div.quot;
  152. timerValues.it_interval.tv_nsec = period_div.rem;
  153. #else
  154. timerValues.it_value.tv_sec = next / 1000000000;
  155. timerValues.it_value.tv_nsec = next % 1000000000;
  156. timerValues.it_interval.tv_sec = period / 1000000000;
  157. timerValues.it_interval.tv_nsec = period % 1000000000;
  158. #endif
  159. }
  160. timer_settime (PLC_timer, 0, &timerValues, NULL);
  161. }
  162. //
  163. void catch_signal(int sig)
  164. {
  165. // signal(SIGTERM, catch_signal);
  166. signal(SIGINT, catch_signal);
  167. printf("Got Signal %d\n",sig);
  168. exit(0);
  169. }
  170.  
  171.  
  172. static unsigned long __debug_tick;
  173.  
  174. pthread_t PLC_thread;
  175. static pthread_mutex_t python_wait_mutex = PTHREAD_MUTEX_INITIALIZER;
  176. static pthread_mutex_t python_mutex = PTHREAD_MUTEX_INITIALIZER;
  177. static pthread_mutex_t debug_wait_mutex = PTHREAD_MUTEX_INITIALIZER;
  178. static pthread_mutex_t debug_mutex = PTHREAD_MUTEX_INITIALIZER;
  179.  
  180. int PLC_shutdown = 0;
  181.  
  182. int ForceSaveRetainReq(void) {
  183. return PLC_shutdown;
  184. }
  185.  
  186. void PLC_thread_proc(void *arg)
  187. {
  188. while (!PLC_shutdown) {
  189. sem_wait(&Run_PLC);
  190. __run();
  191. }
  192. pthread_exit(0);
  193. }
  194.  
  195. #define maxval(a,b) ((a>b)?a:b)
  196. int startPLC(int argc,char **argv)
  197. {
  198. struct sigevent sigev;
  199. setlocale(LC_NUMERIC, "C");
  200.  
  201. PLC_shutdown = 0;
  202.  
  203. sem_init(&Run_PLC, 0, 0);
  204.  
  205. pthread_create(&PLC_thread, NULL, (void*) &PLC_thread_proc, NULL);
  206.  
  207. memset (&sigev, 0, sizeof (struct sigevent));
  208. sigev.sigev_value.sival_int = 0;
  209. sigev.sigev_notify = SIGEV_THREAD;
  210. sigev.sigev_notify_attributes = NULL;
  211. sigev.sigev_notify_function = PLC_timer_notify;
  212.  
  213. pthread_mutex_init(&debug_wait_mutex, NULL);
  214. pthread_mutex_init(&debug_mutex, NULL);
  215. pthread_mutex_init(&python_wait_mutex, NULL);
  216. pthread_mutex_init(&python_mutex, NULL);
  217.  
  218. pthread_mutex_lock(&debug_wait_mutex);
  219. pthread_mutex_lock(&python_wait_mutex);
  220.  
  221. timer_create (CLOCK_MONOTONIC, &sigev, &PLC_timer);
  222. if( __init(argc,argv) == 0 ){
  223. PLC_SetTimer(common_ticktime__,common_ticktime__);
  224.  
  225. /* install signal handler for manual break */
  226. signal(SIGINT, catch_signal);
  227. }else{
  228. return 1;
  229. }
  230. return 0;
  231. }
  232.  
  233. int TryEnterDebugSection(void)
  234. {
  235. if (pthread_mutex_trylock(&debug_mutex) == 0){
  236. /* Only enter if debug active */
  237. if(__DEBUG){
  238. return 1;
  239. }
  240. pthread_mutex_unlock(&debug_mutex);
  241. }
  242. return 0;
  243. }
  244.  
  245. void LeaveDebugSection(void)
  246. {
  247. pthread_mutex_unlock(&debug_mutex);
  248. }
  249.  
  250. int stopPLC()
  251. {
  252. /* Stop the PLC */
  253. PLC_shutdown = 1;
  254. sem_post(&Run_PLC);
  255. PLC_SetTimer(0,0);
  256. pthread_join(PLC_thread, NULL);
  257. sem_destroy(&Run_PLC);
  258. timer_delete (PLC_timer);
  259. __cleanup();
  260. pthread_mutex_destroy(&debug_wait_mutex);
  261. pthread_mutex_destroy(&debug_mutex);
  262. pthread_mutex_destroy(&python_wait_mutex);
  263. pthread_mutex_destroy(&python_mutex);
  264. return 0;
  265. }
  266.  
  267. extern unsigned long __tick;
  268.  
  269. int WaitDebugData(unsigned long *tick)
  270. {
  271. int res;
  272. if (PLC_shutdown) return 1;
  273. /* Wait signal from PLC thread */
  274. res = pthread_mutex_lock(&debug_wait_mutex);
  275. *tick = __debug_tick;
  276. return res;
  277. }
  278.  
  279. /* Called by PLC thread when debug_publish finished
  280. * This is supposed to unlock debugger thread in WaitDebugData*/
  281. void InitiateDebugTransfer()
  282. {
  283. /* remember tick */
  284. __debug_tick = __tick;
  285. /* signal debugger thread it can read data */
  286. pthread_mutex_unlock(&debug_wait_mutex);
  287. }
  288.  
  289. int suspendDebug(int disable)
  290. {
  291. /* Prevent PLC to enter debug code */
  292. pthread_mutex_lock(&debug_mutex);
  293. /*__DEBUG is protected by this mutex */
  294. __DEBUG = !disable;
  295. if (disable)
  296. pthread_mutex_unlock(&debug_mutex);
  297. return 0;
  298. }
  299.  
  300. void resumeDebug(void)
  301. {
  302. __DEBUG = 1;
  303. /* Let PLC enter debug code */
  304. pthread_mutex_unlock(&debug_mutex);
  305. }
  306.  
  307. /* from plc_python.c */
  308. int WaitPythonCommands(void)
  309. {
  310. /* Wait signal from PLC thread */
  311. return pthread_mutex_lock(&python_wait_mutex);
  312. }
  313.  
  314. /* Called by PLC thread on each new python command*/
  315. void UnBlockPythonCommands(void)
  316. {
  317. /* signal debugger thread it can read data */
  318. pthread_mutex_unlock(&python_wait_mutex);
  319. }
  320.  
  321. int TryLockPython(void)
  322. {
  323. return pthread_mutex_trylock(&python_mutex) == 0;
  324. }
  325.  
  326. void UnLockPython(void)
  327. {
  328. pthread_mutex_unlock(&python_mutex);
  329. }
  330.  
  331. void LockPython(void)
  332. {
  333. pthread_mutex_lock(&python_mutex);
  334. }
  335.  
  336. /*
  337. This file is part of Beremiz, a Integrated Development Environment for
  338. programming IEC 61131-3 automates supporting plcopen standard and CanFestival.
  339.  
  340. See COPYING.runtime
  341.  
  342. Copyright (C) 2018: Sergey Surkov <surkov.sv@summatechnology.ru>
  343. Copyright (C) 2018: Andrey Skvortsov <andrej.skvortzov@gmail.com>
  344.  
  345. */
  346.  
  347. #ifndef HAVE_RETAIN
  348. #include <stdio.h>
  349. #include <stdint.h>
  350. #include <unistd.h>
  351. #include "iec_types.h"
  352.  
  353. int GetRetainSize(void);
  354.  
  355. /* Retain buffer. */
  356. FILE *retain_buffer;
  357. const char rb_file[] = "retain_buffer_file";
  358. const char rb_file_bckp[] = "retain_buffer_file.bak";
  359.  
  360.  
  361. /* Retain header struct. */
  362. struct retain_info_t {
  363. uint32_t retain_size;
  364. uint32_t hash_size;
  365. uint8_t* hash;
  366. uint32_t header_offset;
  367. uint32_t header_crc;
  368. };
  369.  
  370. /* Init retain info structure. */
  371. struct retain_info_t retain_info;
  372.  
  373. /* CRC lookup table and initial state. */
  374. static const uint32_t crc32_table[256] = {
  375. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  376. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  377. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  378. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  379. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  380. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  381. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  382. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  383. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  384. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  385. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  386. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  387. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  388. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  389. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  390. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  391. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  392. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  393. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  394. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  395. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  396. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  397. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  398. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  399. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  400. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  401. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  402. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  403. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  404. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  405. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  406. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D,
  407. };
  408. uint32_t retain_crc;
  409.  
  410.  
  411. /* Calculate CRC32 for len bytes from pointer buf with init starting value. */
  412. uint32_t GenerateCRC32Sum(const void* buf, unsigned int len, uint32_t init)
  413. {
  414. uint32_t crc = ~init;
  415. unsigned char* current = (unsigned char*) buf;
  416. while (len--)
  417. crc = crc32_table[(crc ^ *current++) & 0xFF] ^ (crc >> 8);
  418. return ~crc;
  419. }
  420.  
  421. /* Calc CRC32 for retain file byte by byte. */
  422. int CheckFileCRC(FILE* file_buffer)
  423. {
  424. /* Set the magic constant for one-pass CRC calc according to ZIP CRC32. */
  425. const uint32_t magic_number = 0x2144df1c;
  426.  
  427. /* CRC initial state. */
  428. uint32_t calc_crc32 = 0;
  429. char data_block = 0;
  430.  
  431. while(!feof(file_buffer)){
  432. if (fread(&data_block, sizeof(data_block), 1, file_buffer))
  433. calc_crc32 = GenerateCRC32Sum(&data_block, sizeof(char), calc_crc32);
  434. }
  435.  
  436. /* Compare crc result with a magic number. */
  437. return (calc_crc32 == magic_number) ? 1 : 0;
  438. }
  439.  
  440. /* Compare current hash with hash from file byte by byte. */
  441. int CheckFilehash(void)
  442. {
  443. int k;
  444. int offset = sizeof(retain_info.retain_size);
  445.  
  446. rewind(retain_buffer);
  447. fseek(retain_buffer, offset , SEEK_SET);
  448.  
  449. uint32_t size;
  450. fread(&size, sizeof(size), 1, retain_buffer);
  451. if (size != retain_info.hash_size)
  452. return 0;
  453.  
  454. for(k = 0; k < retain_info.hash_size; k++){
  455. uint8_t file_digit;
  456. fread(&file_digit, sizeof(char), 1, retain_buffer);
  457. if (file_digit != *(retain_info.hash+k))
  458. return 0;
  459. }
  460.  
  461. return 1;
  462. }
  463.  
  464. void InitRetain(void)
  465. {
  466. int i;
  467.  
  468. /* Get retain size in bytes */
  469. retain_info.retain_size = GetRetainSize();
  470.  
  471. /* Hash stored in retain file as array of char in hex digits
  472. (that's why we divide strlen in two). */
  473. retain_info.hash_size = PLC_ID ? strlen(PLC_ID)/2 : 0;
  474. //retain_info.hash_size = 0;
  475. retain_info.hash = malloc(retain_info.hash_size);
  476.  
  477. /* Transform hash string into byte sequence. */
  478. for (i = 0; i < retain_info.hash_size; i++) {
  479. int byte = 0;
  480. sscanf((PLC_ID + i*2), "%02X", &byte);
  481. retain_info.hash[i] = byte;
  482. }
  483.  
  484. /* Calc header offset. */
  485. retain_info.header_offset = sizeof(retain_info.retain_size) + \
  486. sizeof(retain_info.hash_size) + \
  487. retain_info.hash_size;
  488.  
  489. /* Set header CRC initial state. */
  490. retain_info.header_crc = 0;
  491.  
  492. /* Calc crc for header. */
  493. retain_info.header_crc = GenerateCRC32Sum(
  494. &retain_info.retain_size,
  495. sizeof(retain_info.retain_size),
  496. retain_info.header_crc);
  497.  
  498. retain_info.header_crc = GenerateCRC32Sum(
  499. &retain_info.hash_size,
  500. sizeof(retain_info.hash_size),
  501. retain_info.header_crc);
  502.  
  503. retain_info.header_crc = GenerateCRC32Sum(
  504. retain_info.hash,
  505. retain_info.hash_size,
  506. retain_info.header_crc);
  507. }
  508.  
  509. void CleanupRetain(void)
  510. {
  511. /* Free hash memory. */
  512. free(retain_info.hash);
  513. }
  514.  
  515. int CheckRetainFile(const char * file)
  516. {
  517. retain_buffer = fopen(file, "rb");
  518. if (retain_buffer) {
  519. /* Check CRC32 and hash. */
  520. if (CheckFileCRC(retain_buffer))
  521. if (CheckFilehash())
  522. return 1;
  523. fclose(retain_buffer);
  524. retain_buffer = NULL;
  525. }
  526. return 0;
  527. }
  528.  
  529. int CheckRetainBuffer(void)
  530. {
  531. retain_buffer = NULL;
  532. if (!retain_info.retain_size)
  533. return 1;
  534.  
  535. /* Check latest retain file. */
  536. if (CheckRetainFile(rb_file))
  537. return 1;
  538.  
  539. /* Check if we have backup. */
  540. if (CheckRetainFile(rb_file_bckp))
  541. return 1;
  542.  
  543. /* We don't have any valid retain buffer - nothing to remind. */
  544. return 0;
  545. }
  546.  
  547. #ifndef FILE_RETAIN_SAVE_PERIOD_S
  548. #define FILE_RETAIN_SAVE_PERIOD_S 1.0
  549. #endif
  550.  
  551. static double CalcDiffSeconds(IEC_TIME* t1, IEC_TIME *t2)
  552. {
  553. IEC_TIME dt ={
  554. t1->tv_sec - t2->tv_sec,
  555. t1->tv_nsec - t2->tv_nsec
  556. };
  557.  
  558. if ((dt.tv_nsec < -1000000000) || ((dt.tv_sec > 0) && (dt.tv_nsec < 0))){
  559. dt.tv_sec--;
  560. dt.tv_nsec += 1000000000;
  561. }
  562. if ((dt.tv_nsec > +1000000000) || ((dt.tv_sec < 0) && (dt.tv_nsec > 0))){
  563. dt.tv_sec++;
  564. dt.tv_nsec -= 1000000000;
  565. }
  566. return dt.tv_sec + 1e-9*dt.tv_nsec;
  567. }
  568.  
  569.  
  570. int RetainSaveNeeded(void)
  571. {
  572. int ret = 0;
  573. static IEC_TIME last_save;
  574. IEC_TIME now;
  575. double diff_s;
  576.  
  577. /* no retain */
  578. if (!retain_info.retain_size)
  579. return 0;
  580.  
  581. /* periodic retain flush to avoid high I/O load */
  582. PLC_GetTime(&now);
  583.  
  584. diff_s = CalcDiffSeconds(&now, &last_save);
  585.  
  586. if ((diff_s > FILE_RETAIN_SAVE_PERIOD_S) || ForceSaveRetainReq()) {
  587. ret = 1;
  588. last_save = now;
  589. }
  590. return ret;
  591. }
  592.  
  593. void ValidateRetainBuffer(void)
  594. {
  595. if (!retain_buffer)
  596. return;
  597.  
  598. /* Add retain data CRC to the end of buffer file. */
  599. fseek(retain_buffer, 0, SEEK_END);
  600. fwrite(&retain_crc, sizeof(uint32_t), 1, retain_buffer);
  601.  
  602. /* Sync file buffer and close file. */
  603. #ifdef __WIN32
  604. fflush(retain_buffer);
  605. #else
  606. fsync(fileno(retain_buffer));
  607. #endif
  608.  
  609. fclose(retain_buffer);
  610. retain_buffer = NULL;
  611. }
  612.  
  613. void InValidateRetainBuffer(void)
  614. {
  615. if (!RetainSaveNeeded())
  616. return;
  617.  
  618. /* Rename old retain file into *.bak if it exists. */
  619. rename(rb_file, rb_file_bckp);
  620.  
  621. /* Set file CRC initial value. */
  622. retain_crc = retain_info.header_crc;
  623.  
  624. /* Create new retain file. */
  625. retain_buffer = fopen(rb_file, "wb+");
  626. if (!retain_buffer) {
  627. fprintf(stderr, "Failed to create retain file : %s\n", rb_file);
  628. return;
  629. }
  630.  
  631. /* Write header to the new file. */
  632. fwrite(&retain_info.retain_size,
  633. sizeof(retain_info.retain_size), 1, retain_buffer);
  634. fwrite(&retain_info.hash_size,
  635. sizeof(retain_info.hash_size), 1, retain_buffer);
  636. fwrite(retain_info.hash ,
  637. sizeof(char), retain_info.hash_size, retain_buffer);
  638. }
  639.  
  640. void Retain(unsigned int offset, unsigned int count, void *p)
  641. {
  642. if (!retain_buffer)
  643. return;
  644.  
  645. /* Generate CRC 32 for each data block. */
  646. retain_crc = GenerateCRC32Sum(p, count, retain_crc);
  647.  
  648. /* Save current var in file. */
  649. fseek(retain_buffer, retain_info.header_offset+offset, SEEK_SET);
  650. fwrite(p, count, 1, retain_buffer);
  651. }
  652.  
  653. void Remind(unsigned int offset, unsigned int count, void *p)
  654. {
  655. /* Remind variable from file. */
  656. fseek(retain_buffer, retain_info.header_offset+offset, SEEK_SET);
  657. fread((void *)p, count, 1, retain_buffer);
  658. }
  659. #endif // !HAVE_RETAIN
  660. /**
  661. * Tail of code common to all C targets
  662. **/
  663.  
  664. /**
  665. * LOGGING
  666. **/
  667. #ifndef TARGET_LOGGING_DISABLE
  668.  
  669. #ifndef LOG_BUFFER_SIZE
  670. #define LOG_BUFFER_SIZE (1<<14) /*16Ko*/
  671. #endif
  672. #ifndef LOG_BUFFER_ATTRS
  673. #define LOG_BUFFER_ATTRS
  674. #endif
  675.  
  676. #define LOG_BUFFER_MASK (LOG_BUFFER_SIZE-1)
  677.  
  678. static char LogBuff[LOG_LEVELS][LOG_BUFFER_SIZE] LOG_BUFFER_ATTRS;
  679. static void inline copy_to_log(uint8_t level, uint32_t buffpos, void* buf, uint32_t size){
  680. if(buffpos + size < LOG_BUFFER_SIZE){
  681. memcpy(&LogBuff[level][buffpos], buf, size);
  682. }else{
  683. uint32_t remaining = LOG_BUFFER_SIZE - buffpos;
  684. memcpy(&LogBuff[level][buffpos], buf, remaining);
  685. memcpy(LogBuff[level], (char*)buf + remaining, size - remaining);
  686. }
  687. }
  688. static void inline copy_from_log(uint8_t level, uint32_t buffpos, void* buf, uint32_t size){
  689. if(buffpos + size < LOG_BUFFER_SIZE){
  690. memcpy(buf, &LogBuff[level][buffpos], size);
  691. }else{
  692. uint32_t remaining = LOG_BUFFER_SIZE - buffpos;
  693. memcpy(buf, &LogBuff[level][buffpos], remaining);
  694. memcpy((char*)buf + remaining, LogBuff[level], size - remaining);
  695. }
  696. }
  697.  
  698. /* Log buffer structure
  699.  
  700. |<-Tail1.msgsize->|<-sizeof(mTail)->|<--Tail2.msgsize-->|<-sizeof(mTail)->|...
  701. | Message1 Body | Tail1 | Message2 Body | Tail2 |
  702.  
  703. */
  704. typedef struct {
  705. uint32_t msgidx;
  706. uint32_t msgsize;
  707. unsigned long tick;
  708. IEC_TIME time;
  709. } mTail;
  710.  
  711. /* Log cursor : 64b
  712. |63 ... 32|31 ... 0|
  713. | Message | Buffer |
  714. | counter | Index | */
  715. static uint64_t LogCursor[LOG_LEVELS] LOG_BUFFER_ATTRS = {0x0,0x0,0x0,0x0};
  716.  
  717. void ResetLogCount(void) {
  718. uint8_t level;
  719. for(level=0;level<LOG_LEVELS;level++){
  720. LogCursor[level] = 0;
  721. }
  722. }
  723.  
  724. /* Store one log message of give size */
  725. int LogMessage(uint8_t level, char* buf, uint32_t size){
  726. if(size < LOG_BUFFER_SIZE - sizeof(mTail)){
  727. uint32_t buffpos;
  728. uint64_t new_cursor, old_cursor;
  729.  
  730. mTail tail;
  731. tail.msgsize = size;
  732. tail.tick = __tick;
  733. PLC_GetTime(&tail.time);
  734.  
  735. /* We cannot increment both msg index and string pointer
  736. in a single atomic operation but we can detect having been interrupted.
  737. So we can try with atomic compare and swap in a loop until operation
  738. succeeds non interrupted */
  739. do{
  740. old_cursor = LogCursor[level];
  741. buffpos = (uint32_t)old_cursor;
  742. tail.msgidx = (old_cursor >> 32);
  743. new_cursor = ((uint64_t)(tail.msgidx + 1)<<32)
  744. | (uint64_t)((buffpos + size + sizeof(mTail)) & LOG_BUFFER_MASK);
  745. }while(AtomicCompareExchange64(
  746. (long long*)&LogCursor[level],
  747. (long long)old_cursor,
  748. (long long)new_cursor)!=(long long)old_cursor);
  749.  
  750. copy_to_log(level, buffpos, buf, size);
  751. copy_to_log(level, (buffpos + size) & LOG_BUFFER_MASK, &tail, sizeof(mTail));
  752.  
  753. return 1; /* Success */
  754. }else{
  755. char mstr[] = "Logging error : message too big";
  756. LogMessage(LOG_CRITICAL, mstr, sizeof(mstr));
  757. }
  758. return 0;
  759. }
  760.  
  761. uint32_t GetLogCount(uint8_t level){
  762. return (uint64_t)LogCursor[level] >> 32;
  763. }
  764.  
  765. /* Return message size and content */
  766. uint32_t GetLogMessage(uint8_t level, uint32_t msgidx, char* buf, uint32_t max_size, uint32_t* tick, uint32_t* tv_sec, uint32_t* tv_nsec){
  767. uint64_t cursor = LogCursor[level];
  768. if(cursor){
  769. /* seach cursor */
  770. uint32_t stailpos = (uint32_t)cursor;
  771. uint32_t smsgidx;
  772. mTail tail;
  773. tail.msgidx = cursor >> 32;
  774. tail.msgsize = 0;
  775.  
  776. /* Message search loop */
  777. do {
  778. smsgidx = tail.msgidx;
  779. stailpos = (stailpos - sizeof(mTail) - tail.msgsize ) & LOG_BUFFER_MASK;
  780. copy_from_log(level, stailpos, &tail, sizeof(mTail));
  781. }while((tail.msgidx == smsgidx - 1) && (tail.msgidx > msgidx));
  782.  
  783. if(tail.msgidx == msgidx){
  784. uint32_t sbuffpos = (stailpos - tail.msgsize ) & LOG_BUFFER_MASK;
  785. uint32_t totalsize = tail.msgsize;
  786. *tick = tail.tick;
  787. *tv_sec = tail.time.tv_sec;
  788. *tv_nsec = tail.time.tv_nsec;
  789. copy_from_log(level, sbuffpos, buf,
  790. totalsize > max_size ? max_size : totalsize);
  791. return totalsize;
  792. }
  793. }
  794. return 0;
  795. }
  796.  
  797. #endif
  798.  
  799. #ifndef TARGET_EXT_SYNC_DISABLE
  800.  
  801. #define CALIBRATED -2
  802. #define NOT_CALIBRATED -1
  803. static int calibration_count = NOT_CALIBRATED;
  804. static IEC_TIME cal_begin;
  805. static long long Tsync = 0;
  806. static long long FreqCorr = 0;
  807. static int Nticks = 0;
  808. static unsigned long last_tick = 0;
  809.  
  810. /*
  811. * Called on each external periodic sync event
  812. * make PLC tick synchronous with external sync
  813. * ratio defines when PLC tick occurs between two external sync
  814. * @param sync_align_ratio
  815. * 0->100 : align ratio
  816. * < 0 : no align, calibrate period
  817. **/
  818. void align_tick(int sync_align_ratio)
  819. {
  820. /*
  821. printf("align_tick(%d)\n", calibrate);
  822. */
  823. if(sync_align_ratio < 0){ /* Calibration */
  824. if(calibration_count == CALIBRATED)
  825. /* Re-calibration*/
  826. calibration_count = NOT_CALIBRATED;
  827. if(calibration_count == NOT_CALIBRATED)
  828. /* Calibration start, get time*/
  829. PLC_GetTime(&cal_begin);
  830. calibration_count++;
  831. }else{ /* do alignment (if possible) */
  832. if(calibration_count >= 0){
  833. /* End of calibration */
  834. /* Get final time */
  835. IEC_TIME cal_end;
  836. PLC_GetTime(&cal_end);
  837. /*adjust calibration_count*/
  838. calibration_count++;
  839. /* compute mean of Tsync, over calibration period */
  840. Tsync = ((long long)(cal_end.tv_sec - cal_begin.tv_sec) * (long long)1000000000 +
  841. (cal_end.tv_nsec - cal_begin.tv_nsec)) / calibration_count;
  842. if( (Nticks = (Tsync / common_ticktime__)) > 0){
  843. FreqCorr = (Tsync % common_ticktime__); /* to be divided by Nticks */
  844. }else{
  845. FreqCorr = Tsync - (common_ticktime__ % Tsync);
  846. }
  847. /*
  848. printf("Tsync = %ld\n", Tsync);
  849. printf("calibration_count = %d\n", calibration_count);
  850. printf("Nticks = %d\n", Nticks);
  851. */
  852. calibration_count = CALIBRATED;
  853. }
  854. if(calibration_count == CALIBRATED){
  855. /* Get Elapsed time since last PLC tick (__CURRENT_TIME) */
  856. IEC_TIME now;
  857. long long elapsed;
  858. long long Tcorr;
  859. long long PhaseCorr;
  860. long long PeriodicTcorr;
  861. PLC_GetTime(&now);
  862. elapsed = (now.tv_sec - __CURRENT_TIME.tv_sec) * 1000000000 + now.tv_nsec - __CURRENT_TIME.tv_nsec;
  863. if(Nticks > 0){
  864. PhaseCorr = elapsed - (common_ticktime__ + FreqCorr/Nticks)*sync_align_ratio/100; /* to be divided by Nticks */
  865. Tcorr = common_ticktime__ + (PhaseCorr + FreqCorr) / Nticks;
  866. if(Nticks < 2){
  867. /* When Sync source period is near Tick time */
  868. /* PhaseCorr may not be applied to Periodic time given to timer */
  869. PeriodicTcorr = common_ticktime__ + FreqCorr / Nticks;
  870. }else{
  871. PeriodicTcorr = Tcorr;
  872. }
  873. }else if(__tick > last_tick){
  874. last_tick = __tick;
  875. PhaseCorr = elapsed - (Tsync*sync_align_ratio/100);
  876. PeriodicTcorr = Tcorr = common_ticktime__ + PhaseCorr + FreqCorr;
  877. }else{
  878. /*PLC did not run meanwhile. Nothing to do*/
  879. return;
  880. }
  881. /* DO ALIGNEMENT */
  882. PLC_SetTimer(Tcorr - elapsed, PeriodicTcorr);
  883. }
  884. }
  885. }
  886.  
  887. #endif
Buy Me A Coffee