rtlinux 高精度定时 转载的文章

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



其实现在有关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