閱讀818 返回首頁    go 阿裏雲 go 技術社區[雲棲]


RTLinux編程總結

做過一個有關RTLinux的項目,時間一長,差不多忘光了,現在盡量把原來做過的東西總結一下,以備後用,同時正在做類似項目的一個借鑒
平台
主機:redhat 8.0
目標機:PC104模塊、ISA總線脈衝輸出、實時串口通信
         linux-2.4.18.tar.bz2 +rtlinux-3.2-pre1.tar.bz2
簡述
Linux是典型的分時應用係統,對於實時性要求很高的應用,必須對內核本身動手術。而RTLinux則采取了一種比較聰明也比較折中的辦法:他們實現一個最底層的精簡的調度器,用於調度實時線程,原來的內核本身則成為實時調度器的一個優先級最低的任務。這樣,當有實時任務時,普通內核已經建立於其上的普通進程被強製中斷,實時線程被強製執行;隻有當若有實時線程都讓出cpu之後,普通內核才被運行,再由普通內核去調度執行普通的應用程序……
實例

  1. #include <rtl_fifo.h>
  2. #include <rtl.h>
  3. #include <rtl_sched.h>
  4. #include <time.h>
  5. #include <pthread.h>
  6. #include <rtl_time.h>
  7. #include <signal.h>
  8. #include "rt_com.h"
  9. #include <linux/kernel.h>
  10. #include <linux/module.h>
  11. MODULE_LICENSE("GPL v2");
  12. MODULE_AUTHOR("Wind-Son");
  13. MODULE_DESCRIPTION("Pulse-Control system");
  14. typedef unsigned short __u16;
  15. void io_bit_on(__u16 port, unsigned int pos, __u16 *status)
  16. {
  17.         __asm__ __volatile__(
  18.                 "movl %1,%?x\n\t"
  19.                 "movl %0,%?x\n\t"
  20.                 "btsl %2,(%?x)\n\t"
  21.                 "mov (%?x),%%al\n\t"
  22.         "out %%al,(%%dx)\n\t"
  23.         "out %%al,$0x80\n\t"
  24.                 :
  25.                 :"m"(status), "rm"(port), "Ir"(pos)
  26.         );
  27. }
  28. void io_bit_off(__u16 port, unsigned int pos, __u16 *status)
  29. {
  30.         __asm__ __volatile__(      
  31.                 "movl %1,%?x\n\t"
  32.                 "movl %0,%?x\n\t"
  33.                 "btrl %2,(%?x)\n\t"
  34.                 "mov (%?x),%%al\n\t"
  35.         "out %%al,(%%dx)\n\t"
  36.         "out %%al,$0x80\n\t"
  37.                 :
  38.                 :"m"(status), "rm"(port), "Ir"(pos)
  39.         );
  40. }
  41. #define dbg_print rtl_printf
  42. #define MIN_TIME              5000
  43. static void get_time_interval(void)
  44. {
  45. }
  46. void* pulse_generate_thread(void *arg)
  47. {
  48.         static __u16 io_status = 0;
  49.         struct sched_param p;
  50.         hrtime_t current_time;
  51.         REAL_TIME_GET_ENABLE;
  52.         int intrrupt_sched_period = 180000;
  53.         p.sched_priority = 1;
  54.         struct timespec resolution;
  55.        
  56.         rtl_setclockmode(CLOCK_REALTIME, RTL_CLOCK_MODE_PERIODIC,
  57.                         intrrupt_sched_period);
  58.         clock_getres(rtl_getschedclock(), &resolution);
  59.         intrrupt_sched_period = timespec_to_ns(&resolution);
  60.        
  61.         pthread_make_periodic_np(pthread_self(), clock_gethrtime(rtl_getschedclock()),
  62.                 intrrupt_sched_period);
  63.         pthread_setschedparam (pthread_self(), SCHED_FIFO, &p);
  64.         for (;;) {
  65.                 dbg_print("debug entry\n");
  66.                 while (!ready)
  67.                     pthread_wait_np();
  68.                 dbg_print("debug exit\n");
  69.                 if (!init_rt_clock) {
  70.                        
  71.                         init_rt_clock = 1;
  72.                         pthread_wait_np();
  73.                         current_time = clock_gethrtime(CLOCK_REALTIME);
  74.                 } else {
  75.                     if (intrrupt_sched_period < MIN_TIME)
  76.                                 intrrupt_sched_period = MIN_TIME;
  77.                     current_time += intrrupt_sched_period;
  78.                        
  79.                     clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, hrt2ts(current_time), NULL);
  80.                 }
  81.                
  82.                 io_bit_on(IO_PORT_OUT, XPULSE, &io_status);
  83.                
  84.             intrrupt_sched_period = get_time_interval();
  85.         }
  86.         return 0;
  87. }
  88. static void init_for_rt_mm(void)
  89. {
  90. }
  91. static void rt_alloc_mm(void)
  92. {
  93.         thread_wait_np();
  94.         buf = kmalloc(size, GFP_ATOMIC);
  95. }
  96. static int kmalloc_thread(void * kthread_arg)
  97. {
  98.         unsigned long timeout = HZ;
  99.         init_for_rt_mm();
  100.         for (;;) {
  101.                 while (!get_flag(MM_ALLOC_FLAG)) {
  102.                        
  103.                         if( signal_pending(current))
  104.                                 return 0;
  105.                         timeout = interruptible_sleep_on_timeout(&wq, timeout);
  106.                 }
  107.                 rt_alloc_mm();
  108.                 clear_flag(MM_ALLOC_FLAG);
  109.         }
  110.         return -1;
  111. }
  112. wait_queue_head_t wq;
  113. static pid_t kmalloc_kthread_id;
  114. static int kmalloc_kthread_state = 1;
  115. static int pulse_generate_thread_created = 0;
  116. static int main_ctrl_thread_created = 0;
  117. static pthread_t pulse_generate_pthread;      
  118. static pthread_t main_ctrl_pthread;
  119. static pthread_mutex_t cache_mutex;
  120. void rt_mm_request(void)
  121. {
  122.         set_flag(MM_ALLOC_FLAG);
  123.        
  124.         while(get_flag(MM_ALLOC_FLAG))      
  125.                 pthread_wait_np();
  126. }
  127. void* main_ctrl_thread(void *arg)
  128. {
  129.         int work_sched_period = 160000;
  130.         struct timespec resolution;
  131.         int ret1 = rtl_setclockmode(rtl_getschedclock(), RTL_CLOCK_MODE_PERIODIC,
  132.                 work_sched_period);              
  133.         if (ret1) {
  134.                 dbg_print("seting periodic mode failed\n");
  135.                 clear_flag(WORK_SCHED_MODE);
  136.         }
  137.         clock_getres(rtl_getschedclock(), &resolution);
  138.         work_sched_period = timespec_to_ns(&resolution);
  139.         pthread_make_periodic_np(pthread_self(), clock_gethrtime(rtl_getschedclock()),
  140.             work_sched_period);
  141.         init_task();      
  142.         for (;;) {
  143.                 if (work) {
  144.                         dbg_print("work\n");
  145.                         rt_mm_request();
  146.                         calc_time_interval();
  147.                         if (exit)
  148.                             break;
  149.                 } else
  150.                         pthread_wait_np();
  151.         }
  152.         exit_task();
  153.     return 0;
  154. }
  155. int init_module(void)
  156. {
  157.         pthread_attr_t attr;
  158.         struct sched_param p;
  159.         int ret;
  160.         rtf_destroy(0);
  161.         rtf_destroy(1);
  162.         rt_com_clr_in(0);
  163.         rt_com_clr_out(0);
  164.        
  165.         int fifo_status = rtf_create(0,100);
  166.         if(fifo_status)
  167.                 dbg_print("FIFO Create failed!");
  168.         fifo_status = rtf_create(1, 4000);
  169.         if(fifo_status)
  170.                 dbg_print("FIFO Create failed!");
  171.        
  172.         rt_com_setup(0, 9600, RT_COM_PARITY_NONE, 1, 8);
  173.         hrtime_t now = gethrtime();
  174.         pthread_attr_init(&attr);
  175.         pthread_mutex_init(&cache_mutex, NULL);
  176.         pthread_attr_setfp_np(&attr, 1);
  177.        
  178.         ret = pthread_create(&pulse_generate_pthread, &attr,
  179.                 pulse_generate_thread, (void *)0);
  180.         if (!ret)
  181.                 pulse_generate_thread_created = 1;
  182.         pthread_make_periodic_np (pulse_generate_pthread, now + 2 * 240000, 80000);
  183.         p . sched_priority = 1;
  184.         pthread_setschedparam (pulse_generate_pthread, SCHED_FIFO, &p);
  185.        
  186.         ret = pthread_create(&main_ctrl_pthread, &attr, main_ctrl_thread, (void *)1);
  187.         if (!ret)
  188.                 main_ctrl_thread_created=1;
  189.         pthread_make_periodic_np (main_ctrl_pthread, now + 2 * 160000, 30000);
  190.         p . sched_priority = 2;
  191.         pthread_setschedparam (main_ctrl_pthread, SCHED_FIFO, &p);
  192.         init_waitqueue_head(&wq);
  193.         kmalloc_kthread_id = kernel_thread(kmalloc_thread, NULL, 0);
  194.         if (kmalloc_kthread_id < 0) {
  195.                 printk(KERN_ERR "fork failed, errno %d\n", -kmalloc_kthread_id);
  196.                 return kmalloc_kthread_id;
  197.         }
  198.         return ret;
  199. }
  200. void cleanup_module(void)
  201. {
  202.        
  203.         int ret = kill_proc(kmalloc_kthread_id, SIGKILL, 1);
  204.         if (!ret) {
  205.                 int count = 10 * HZ;
  206.                
  207.                 while (kmalloc_kthread_state && --count) {
  208.                         current->state = TASK_INTERRUPTIBLE;
  209.                         schedule_timeout(1);
  210.                 }
  211.         }
  212.         if (main_ctrl_thread_created) {
  213.                 pthread_cancel(main_ctrl_pthread);
  214.                 pthread_join(main_ctrl_pthread, NULL);
  215.                 pthread_delete_np(main_ctrl_pthread);
  216.         }
  217.         if (pulse_generate_thread_created) {
  218.                 pthread_cancel(pulse_generate_pthread);
  219.                 pthread_join(pulse_generate_pthread, NULL);
  220.                 pthread_delete_np(pulse_generate_pthread);
  221.         }
  222.         rt_com_setup(0, -1, 0, 0, 0);
  223.         rtf_destroy(0);
  224.         rtf_destroy(1);
  225.         pthread_mutex_destroy (&cache_mutex);
  226. }

複製代碼

其實現在有關Linux實時應用的原理和應用方麵的介紹已經不少,所以我主要是想從自己的親身實踐中的經驗教訓出發總結一下。
我遇到的主要問題主要有以下幾個:
1、硬實時調度精度不夠的問題。剛開始產生脈衝驅動的線程我按照例子程序采樣如下方式
   pthread_make_periodic_np();  //設置調度方式和周期等參數
    pthread_setschedparam (pthread_self(), SCHED_FIFO, &p);
    pthread_wait_np(); //讓出cpu進入睡眠
  可實際情況總是不理想,輸出波形不夠穩定,離預想的效果也很遠。試著將調度策略SCHED_FIFO改其他幾種方式,也一樣。最後嚐試用clock_nanosleep()才達到了比較理想的效果。理論上clock_nanosleep()應該達到ns級別的精度,當然實際精度還要取決於硬件。
2、實時線程所能到達的實時效果和精度極限也就是定時器本身的精度了。有過在51上做開發經驗的都有這樣一個意識:定時器中斷處理例程裏盡量隻做最簡單、最必須的工作,但畢竟還是有開銷的。如果你對精度還有更高的要求,可在main_ctrl_thread()即負責計算脈衝間隔時間的例程中加入補償值,以抵消脈衝輸出例程中的時間開銷。
3、實時線程中頻繁的動態申請內存時常宕機。後來經過實驗摸索才采取了上麵代碼中所述的拐彎抹角的辦法。如果誰碰到過類似問題有更好的辦法,還望指出。
4、應用程序直接向串口輸出時總出錯。
   開始方法是system("/bin/ls ./data/ >> /dev/ttyS0";在沒有實時線程的影響的情況下,這樣是沒有問題。開啟實時線程後就老出錯。
後改成如下方式就好了:由實時模塊通過實時調用rt_com_write()和rt_com_read()讀寫串口;再通過實時管道rtl_fifo轉發到應用程序
另外,純粹經驗談,實時線程如果不主動讓出cpu,任何用戶程序無法運行,包括你的鍵盤響應!如果你的某個環節可能陷入循環,你能做的就隻有poweroff了;被迫重啟後在ext2文件係統上隨之而來的是漫長的fscheck……所以我在調試階段,基本上是隻要有循環的的方,就加上pthread_wait_np();以後再慢慢把不必要的去掉。

最後更新:2017-04-03 16:48:39

  上一篇:go DOS下串口通信程序來傳送文件的源代碼
  下一篇:go VC6安裝錯誤——Error Launching acmboot.exe