rtlinux 高精度定时 转载的文章

主要是RTLinux环境下编程总结,在嵌入版发过,没几个人响应。

做过一个有关RTLinux的项目,时间一长,差不多忘光了,现在尽量把原来做过的东西总结一下,以备后用,同时正在做类似项目的一个借鉴

平台
主机:redhat 8.0 
目标机:PC104模块、ISA总线脉冲输出、实时串口通信
         linux-2.4.18.tar.bz2 +rtlinux-3.2-pre1.tar.bz2 
简述
Linux是典型的分时应用系统,对于实时性要求很高的应用,必须对内核本身动手术。而RTLinux则采取了一种比较聪明也比较折中的办法:他们实现一个最底层的精简的调度器,用于调度实时线程,原来的内核本身则成为实时调度器的一个优先级最低的任务。这样,当有实时任务时,普通内核已经建立于其上的普通进程被强制中断,实时线程被强制执行;只有当若有实时线程都让出cpu之后,普通内核才被运行,再由普通内核去调度执行普通的应用程序……

实例
  1. /*
  2. * Copyright(C) Wind-Son.
  3. * 2006-2007
  4. *
  5. * 实时应用:RT-Linux用于高精度脉冲控制
  6. * 利用实时线程模拟定时器时钟产生连续的脉冲控制信号,
  7. * 用于对实时性有较高要求的运动控制系统等。
  8. * 
  9. */
  10. /*
  11. *  安装和添加实时补丁
  12. *        1. RedHat Linux Installation
  13. *                If you have not done it before, make a separate disk partition and install
  14. *                RedHat linux on the partition. RedHat 8.0 (Psyche) is recommended since 
  15. *                it is most compatible with the RT-Linux we will use in this course. Also,
  16. *                make sure to install kernel development tools, gcc compiler, and utilities 
  17. *                such as patch, depmod, make, and bzip2.
  18. *        2. Get linux kernel
  19. *                Download \linux-2.4.18.tar.bz2" from the course website.
  20. *        3. Get rtlinux kernel and patches
  21. *                Download \rtlinux-3.2-pre1.tar.bz2" from the course website.
  22. *        4. Put a fresh copy of the rtlinux kernel in /usr/src/rtlinux-3.2-pre1
  23. *                Use the following commands.
  24. *                        cd /usr/src
  25. *                        tar xjf rtlinux-3.2-pre1.tar.bz2
  26. *                This will create \rtlinux-3.2-pre1" directory under /usr/src.
  27. *        5. Put a fresh copy of the linux kernel in /usr/src/rtlinux-3.2-pre1/linux
  28. *                Use the following commands.
  29. *                        cd /usr/src/rtlinux-3.2-pre1
  30. *                        tar xjf linux-2.4.18.tar.bz2
  31. *                This will create \linux" directory under /usr/src/rtlinux-3.2-pre1.
  32. *        6. Patch the linux kernel with the rtlinux patch
  33. *                        cd /usr/src/rtlinux-3.2-pre1/patches
  34. *                        bzip2 -d kernel patch-2.4.18-rtl3.2-pre1.bz2
  35. *                        cd /usr/src/rtlinux-3.2-pre1/linux
  36. *                        patch -p1 < /usr/src/rtlinux-3.2-pre1/patches/kernel patch-2.4.18
  37. *        7. Clean all "\.o" files and stale dependencies
  38. *                        cd /usr/src/rtlinux-3.2-pre1/linux
  39. *                        make mrproper
  40. *        8. Configure the linux kernel
  41. *                        cd /usr/src/rtlinux-3.2-pre1/linux
  42. *                        make config (text mode) or
  43. *                        make xconfig (X mode)
  44. *        9. Build a new linux kernel
  45. *                Use the following commands in order.
  46. *                        cd /usr/src/rtlinux-3.2-pre1/linux
  47. *                        make dep 
  48. *                        make bzImage 
  49. *                        make modules 
  50. *                        su 
  51. *                        make modules install 
  52. *                        cp arch/i386/boot/bzImage /boot/rtzImage
  53. *        10. Configure your boot loader
  54. *                In the following explanation, we assume that the root file system \/" is 
  55. *                mapped to /dev/hda3 and the boot file system \/boot" is mapped to /dev/hda2. 
  56. *                You can check out your mapping using \df" command. If you are using LILO 
  57. *                as your boot manager, add the following lines to the file \/etc/lilo.conf".
  58. *                        image = /boot/rtzImage
  59. *                        label = rtlinux
  60. *                        read-only
  61. *                        root = /dev/hda3
  62. *                The /dev/hda3 should be the device on which your root file system has been
  63. *                installed. Then, use the following command.
  64. *                        /sbin/lilo
  65. *                For more details for your specific setting, 
  66. *                see [url]http://www.freeos.com/articles/2701/[/url] and
  67. *                [url]http://www.linuxheadquarters.com/howto/basic/lilo.shtml.[/url]
  68. *                If your are using GRUB as your boot manager, add the following lines to the file \/etc/grub.conf".
  69. *                        title rtlinux
  70. *                        root (hd0, 1)
  71. *                        kernel /rtzImage ro root = /dev/hda3
  72. *                The /dev/hda3 should be the device on which your root file system has been 
  73. *                installed. (hd0,1) corresponds to the first (0) physical disk derive's 
  74. *                second (1) partition, which is /dev/hda2. It should be the partition where 
  75. *                the boot file system \/boot" resides. For more details for
  76. *                your specific setting, see [url]http://www.gnu.org/software/grub/.[/url]
  77. *        11. Reboot and select rtlinux from boot image options
  78. *                RTLinux should boot.
  79. *        12. Configure RTLinux
  80. *                        cd /usr/src/rtlinux-3.2-pre1
  81. *                        make xconfig (accept default)
  82. *        13. Compile RTLinux Use the following commands in order.
  83. *                        cd /usr/src/rtlinux-3.2-pre1
  84. *                        make
  85. *                        su (become the root to do the followings)
  86. *                        make devices
  87. *                        make install
  88. *        14. Reboot and select rtlinux from boot image options
  89. */
  90. /*
  91. * 运行实时内核
  92. *        First of all, you should be the root to do the followings.
  93. *        In order to run rtlinux applications given in \examples" directory, 
  94. *        you first insert dynamic rtlinux kernel modules like mbuff, rtl_fifo, 
  95. *        rtl, rtl posixio, rtl sched, and rtl time. You can insert each module 
  96. *        with \insmod modulename.o". Fortunately, the script \rtlinux" can do this 
  97. *        for you at a single step. Try
  98. *                rtlinux status ( look at which module has been loaded )
  99. *                rtlinux start ( insert all rtlinux modules )
  100. *                rtlinux status ( check whether all rtlinux modules are loaded successfully )
  101. *        If you can see all the modules loaded, you are done. Otherwise, you might see 
  102. *        error messages while you were doing \rtlinux start". This may be due to incorrect 
  103. *        configuration of linux kernel.
  104. * 运行实时内核模块
  105. *        insmod hello.o 载入模块
  106. *        lsmod 查看已经载入的模块
  107. */
  108. #include <rtl_fifo.h>
  109. #include <rtl.h>
  110. #include <rtl_sched.h>
  111. #include <time.h>
  112. #include <pthread.h>
  113. #include <rtl_time.h>
  114. #include <signal.h>
  115. #include "rt_com.h"
  116. #include <linux/kernel.h> /* printk level */
  117. #include <linux/module.h> /* kernel version etc. */
  118. MODULE_LICENSE("GPL v2");
  119. MODULE_AUTHOR("Wind-Son");
  120. MODULE_DESCRIPTION("Pulse-Control system");
  121. typedef unsigned short __u16;
  122. /* 实时应用-IO输出控制部分 */
  123. void io_bit_on(__u16 port, unsigned int pos, __u16 *status)
  124. {
  125.         __asm__ __volatile__(
  126.                 "movl %1,%%edx\n\t"
  127.                 "movl %0,%%ecx\n\t"
  128.                 "btsl %2,(%%ecx)\n\t"
  129.                 "mov (%%ecx),%%al\n\t"
  130.         "out %%al,(%%dx)\n\t"
  131.         "out %%al,$0x80\n\t"
  132.                 :
  133.                 :"m"(status), "rm"(port), "Ir"(pos)
  134.         );
  135. }
  136. void io_bit_off(__u16 port, unsigned int pos, __u16 *status)
  137. {
  138.         __asm__ __volatile__(        
  139.                 "movl %1,%%edx\n\t"
  140.                 "movl %0,%%ecx\n\t"
  141.                 "btrl %2,(%%ecx)\n\t"
  142.                 "mov (%%ecx),%%al\n\t"
  143.         "out %%al,(%%dx)\n\t"
  144.         "out %%al,$0x80\n\t"
  145.                 :
  146.                 :"m"(status), "rm"(port), "Ir"(pos)
  147.         );
  148. }
  149. /* 
  150. * 实时应用-以实时线程模拟定时器产生脉冲输出部分 
  151. */
  152. #define dbg_print rtl_printf
  153. #define MIN_TIME              5000
  154. static void get_time_interval(void)
  155. {
  156. }
  157. void* pulse_generate_thread(void *arg) 
  158. {
  159.         static __u16 io_status = 0;
  160.         struct sched_param p;
  161.         hrtime_t current_time;
  162.         REAL_TIME_GET_ENABLE;
  163.         int intrrupt_sched_period = 180000;
  164.         p.sched_priority = 1; /* 设置实时线程的优先级 */
  165.         struct timespec resolution;
  166.         /* RT时钟设置 */
  167.         rtl_setclockmode(CLOCK_REALTIME, RTL_CLOCK_MODE_PERIODIC, 
  168.                         intrrupt_sched_period);
  169.         clock_getres(rtl_getschedclock(), &resolution);
  170.         intrrupt_sched_period = timespec_to_ns(&resolution);
  171.         
  172.         /* 设置RT-调度参数 */
  173.         pthread_make_periodic_np(pthread_self(), clock_gethrtime(rtl_getschedclock()), 
  174.                 intrrupt_sched_period);
  175.         pthread_setschedparam (pthread_self(), SCHED_FIFO, &p);
  176.         for (;;) {
  177.                 dbg_print("debug entry\n");
  178.                 while (!ready) /* 空闲等待 */
  179.                     pthread_wait_np(); /* 空闲状态一定调用该函数让出对cpu的控制,否则死机!*/
  180.                 dbg_print("debug exit\n");
  181.                 if (!init_rt_clock) {
  182.                         /* 初始化或重新设置RT时钟 */
  183.                         init_rt_clock = 1;
  184.                         pthread_wait_np();
  185.                         current_time = clock_gethrtime(CLOCK_REALTIME);
  186.                 } else {
  187.                     if (intrrupt_sched_period < MIN_TIME)
  188.                                 intrrupt_sched_period = MIN_TIME;
  189.                     current_time += intrrupt_sched_period;
  190.                         /*
  191.                          * 这一步很关键!clock_nanosleep()使本线程直接睡眠在定时器上,
  192.                          * 睡眠时间current_time(ns),然后被唤醒。实验结果,这种方式
  193.                          * 不但保证实时性且基本上接近于硬件定时器精度了。
  194.                          * 而通过pthread_wait_np()实时调度虽然在实时性上也是有保证的,
  195.                          * 但在精度上是有限的。
  196.                          */
  197.                     clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, hrt2ts(current_time), NULL);
  198.                 }
  199.         
  200.                 /* 脉冲输出控制…… */
  201.                 io_bit_on(IO_PORT_OUT, XPULSE, &io_status);
  202.                 /* 
  203.                  * 获取下一个脉冲间隔,从而产生精确的脉冲控制序列
  204.                  * Note! 该实时线程用于模拟定时器输出,因此不能有太复杂的计算。
  205.                  * 一般情况下将脉冲间隔时间的计算以及其他控制部分放到另外一个独立的线程。
  206.                  * 在本系统中time_interval_calc_thread即用于该目的。
  207.                  */
  208.             intrrupt_sched_period = get_time_interval();
  209.         }
  210.         return 0;
  211. }
  212. /*
  213. * 实时应用-动态内存申请部分。
  214. * 直接在RT-thread中申请内存实际结果证明很不稳定,时不时的crash,
  215. * 大概是因为alloc过程被高优先级RT-thread强制中断产生异常。
  216. * 因此需要动态申请内存时开辟独立的内核线程专门负责内存申请。
  217. */
  218. static void init_for_rt_mm(void)
  219. {
  220. }
  221. static void rt_alloc_mm(void)
  222. {
  223.         thread_wait_np();
  224.         buf = kmalloc(size, GFP_ATOMIC);
  225. }
  226. static int kmalloc_thread(void * kthread_arg)
  227. {
  228.         unsigned long timeout = HZ;
  229.         init_for_rt_mm();
  230.         
  231.         for (;;) {
  232.                 while (!get_flag(MM_ALLOC_FLAG)) {
  233.                         /* 没有内存申请任务则睡眠 */
  234.                         if( signal_pending(current)) 
  235.                                 return 0;
  236.                         timeout = interruptible_sleep_on_timeout(&wq, timeout);
  237.                 }
  238.                 rt_alloc_mm();
  239.                 clear_flag(MM_ALLOC_FLAG);
  240.         }
  241.         return -1;
  242. }
  243. /* 实时应用-主程序-脉冲控制部分 */
  244. wait_queue_head_t wq;
  245. static pid_t kmalloc_kthread_id;
  246. static int kmalloc_kthread_state = 1;
  247. static int pulse_generate_thread_created = 0;
  248. static int main_ctrl_thread_created = 0;
  249. static pthread_t pulse_generate_pthread;        
  250. static pthread_t main_ctrl_pthread;
  251. static pthread_mutex_t cache_mutex;
  252. void rt_mm_request(void)
  253. {
  254.         set_flag(MM_ALLOC_FLAG);
  255.         /*
  256.          *        通过设置标志位通知kmalloc_thread内核线程申请内存
  257.          */
  258.         while(get_flag(MM_ALLOC_FLAG))        
  259.                 pthread_wait_np();
  260. }
  261. void* main_ctrl_thread(void *arg)
  262. {
  263.         int work_sched_period = 160000;
  264.         struct timespec resolution;
  265.                 
  266.         int ret1 = rtl_setclockmode(rtl_getschedclock(), RTL_CLOCK_MODE_PERIODIC, 
  267.                 work_sched_period);                
  268.         if (ret1) {
  269.                 dbg_print("seting periodic mode failed\n");
  270.                 clear_flag(WORK_SCHED_MODE);
  271.         }
  272.         clock_getres(rtl_getschedclock(), &resolution);
  273.         work_sched_period = timespec_to_ns(&resolution);
  274.         
  275.         pthread_make_periodic_np(pthread_self(), clock_gethrtime(rtl_getschedclock()),
  276.             work_sched_period);
  277.         init_task();        
  278.         for (;;) {
  279.                 if (work) {
  280.                         dbg_print("work\n");
  281.                         rt_mm_request();
  282.                         calc_time_interval();
  283.                         if (exit)
  284.                             break;
  285.                 } else
  286.                         pthread_wait_np();
  287.         }
  288.         exit_task();
  289.         
  290.     return 0;
  291. }
  292. int init_module(void)
  293. {
  294.         pthread_attr_t attr;
  295.         struct sched_param p;
  296.         int ret;
  297.         
  298.         rtf_destroy(0); 
  299.         rtf_destroy(1);
  300.         rt_com_clr_in(0);
  301.         rt_com_clr_out(0);
  302.         
  303.         /* 创建实时管道,用于RT模块和普通应用程序之间的通信 */
  304.         int fifo_status = rtf_create(0,100);
  305.         if(fifo_status)
  306.                 dbg_print("FIFO Create failed!");
  307.         
  308.         fifo_status = rtf_create(1, 4000);
  309.         if(fifo_status)
  310.                 dbg_print("FIFO Create failed!");
  311.         
  312.         /* 设置实时串口,用于RT模块控制串口输出 */
  313.         rt_com_setup(0, 9600, RT_COM_PARITY_NONE, 1, 8);
  314.         
  315.         hrtime_t now = gethrtime();
  316.         pthread_attr_init(&attr);
  317.         pthread_mutex_init(&cache_mutex, NULL);
  318.         pthread_attr_setfp_np(&attr, 1);
  319.         /* pulse_generate_thread */
  320.         ret = pthread_create(&pulse_generate_pthread, &attr, 
  321.                 pulse_generate_thread, (void *)0);
  322.         if (!ret)
  323.                 pulse_generate_thread_created = 1;
  324.         pthread_make_periodic_np (pulse_generate_pthread, now + 2 * 240000, 80000);
  325.         p . sched_priority = 1;
  326.         pthread_setschedparam (pulse_generate_pthread, SCHED_FIFO, &p);
  327.         
  328.         /* main_ctrl_thread */
  329.         ret = pthread_create(&main_ctrl_pthread, &attr, main_ctrl_thread, (void *)1);
  330.         if (!ret) 
  331.                 main_ctrl_thread_created=1;
  332.         pthread_make_periodic_np (main_ctrl_pthread, now + 2 * 160000, 30000);
  333.         p . sched_priority = 2;
  334.         pthread_setschedparam (main_ctrl_pthread, SCHED_FIFO, &p);
  335.         
  336.         init_waitqueue_head(&wq);
  337.         kmalloc_kthread_id = kernel_thread(kmalloc_thread, NULL, 0);
  338.         if (kmalloc_kthread_id < 0) {
  339.                 printk(KERN_ERR "fork failed, errno %d\n", -kmalloc_kthread_id);
  340.                 return kmalloc_kthread_id;
  341.         }
  342.         
  343.         return ret;
  344. }
  345. void cleanup_module(void)
  346. {
  347.         /* send a term signal to the kthread */
  348.         int ret = kill_proc(kmalloc_kthread_id, SIGKILL, 1);
  349.         if (!ret) {
  350.                 int count = 10 * HZ;
  351.                 /* wait for the kthread to exit befor terminating */
  352.                 while (kmalloc_kthread_state && --count) {
  353.                         current->state = TASK_INTERRUPTIBLE;
  354.                         schedule_timeout(1);
  355.                 }
  356.         }
  357.         if (main_ctrl_thread_created) {
  358.                 pthread_cancel(main_ctrl_pthread);
  359.                 pthread_join(main_ctrl_pthread, NULL);
  360.                 pthread_delete_np(main_ctrl_pthread);
  361.         }
  362.         if (pulse_generate_thread_created) {
  363.                 pthread_cancel(pulse_generate_pthread);
  364.                 pthread_join(pulse_generate_pthread, NULL);
  365.                 pthread_delete_np(pulse_generate_pthread);
  366.         }
  367.         rt_com_setup(0, -1, 0, 0, 0);
  368.         rtf_destroy(0);
  369.         rtf_destroy(1);
  370.         pthread_mutex_destroy (&cache_mutex);
  371. }
复制代码



其实现在有关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();以后再慢慢把不必要的去掉。

 

https://blog.csdn.net/cpq37/article/details/51375763

posted @ 2023-09-13 09:10  eastgeneral  阅读(217)  评论(0)    收藏  举报