Linux循環緩衝實現

內核中有很好的循環緩衝的實現 在kernel/kfifo.c中,以及include/linux/kfifo.h中。

我們可以根據內核的代碼,改爲用戶態的程序,實現如下。

fifo.h文件如下

  1. #ifndef _LINUX_FIFO_H
  2. #define _LINUX_FIFO_H
  3. #include "pthread.h"
  4. #define __u32 unsigned long
  5. #define __u64 unsigned long long
  6. #define BUG_ON(condition) do { if (condition) ; } while(0)
  7. #define min(x,y) ({ /
  8.         typeof(x) _x = (x);     /
  9.         typeof(y) _y = (y);     /
  10.         (void) (&_x == &_y);            /
  11.         _x < _y ? _x : _y; })
  12. #define max(x,y) ({ /
  13.         typeof(x) _x = (x);     /
  14.         typeof(y) _y = (y);     /
  15.         (void) (&_x == &_y);            /
  16.         _x > _y ? _x : _y; })
  17. static inline int fls(int x)
  18. {
  19.     int r;
  20.     __asm__("bsrl %1,%0/n/t"
  21.             "jnz 1f/n/t"
  22.             "movl $-1,%0/n"
  23.             "1:" : "=r" (r) : "rm" (x));
  24.     return r+1;
  25. }
  26. static inline int fls64(__u64 x)
  27. {
  28.     __u32 h = x >> 32;
  29.     if (h)
  30.         return fls(h) + 32;
  31.     return fls(x);
  32. }
  33. static inline unsigned fls_long(unsigned long l)
  34. {
  35.     if (sizeof(l) == 4)
  36.         return fls(l);
  37.     return fls64(l);
  38. }
  39. static inline unsigned long roundup_pow_of_two(unsigned long x)
  40. {
  41.     return 1UL << fls_long(x - 1);
  42. }
  43. struct fifo {
  44.     unsigned char *buffer;    /* the buffer holding the data */
  45.     unsigned int size;    /* the size of the allocated buffer */
  46.     unsigned int in;    /* data is added at offset (in % size) */
  47.     unsigned int out;    /* data is extracted from off. (out % size) */
  48.     pthread_mutex_t * mutex;
  49. };
  50. struct fifo *fifo_init(unsigned char *buffer, unsigned int size,pthread_mutex_t * mutex );
  51. struct fifo *fifo_alloc(unsigned int size,pthread_mutex_t * mutex);
  52. void fifo_free(struct fifo *fifo);
  53. unsigned int __fifo_put(struct fifo *fifo, unsigned char *buffer, unsigned int len);
  54. unsigned int __fifo_get(struct fifo *fifo, unsigned char *buffer, unsigned int len);
  55. static inline void __fifo_reset(struct fifo *fifo)
  56. {
  57.     fifo->in = fifo->out = 0;
  58. }
  59. static inline void fifo_reset(struct fifo *fifo)
  60. {
  61.     pthread_mutex_lock(fifo->mutex);
  62.     __fifo_reset(fifo);
  63.     pthread_mutex_unlock(fifo->mutex);
  64. }
  65. static inline unsigned int fifo_put(struct fifo *fifo,
  66.                      unsigned char *buffer, unsigned int len)
  67. {
  68.     unsigned int ret;
  69.     pthread_mutex_lock(fifo->mutex);
  70.     ret = __fifo_put(fifo, buffer, len);
  71.     pthread_mutex_unlock(fifo->mutex);
  72.     return ret;
  73. }
  74. static inline unsigned int fifo_get(struct fifo *fifo,
  75.                      unsigned char *buffer, unsigned int len)
  76. {
  77.     unsigned int ret;
  78.     pthread_mutex_lock(fifo->mutex);
  79.     ret = __fifo_get(fifo, buffer, len);
  80.     if (fifo->in == fifo->out)
  81.         fifo->in = fifo->out = 0;
  82.     pthread_mutex_unlock(fifo->mutex);
  83.     return ret;
  84. }
  85. static inline unsigned int __fifo_len(struct fifo *fifo)
  86. {
  87.     return fifo->in - fifo->out;
  88. }
  89. static inline unsigned int fifo_len(struct fifo *fifo)
  90. {
  91.     unsigned int ret;
  92.     pthread_mutex_lock(fifo->mutex);
  93.     ret = __fifo_len(fifo);
  94.     pthread_mutex_unlock(fifo->mutex);
  95.     return ret;
  96. }
  97. #endif
 
fifo.c文件如下
 
  1. #include "stdio.h"
  2. #include "stdlib.h"
  3. #include "string.h"
  4. #include "fifo.h"
  5. struct fifo *fifo_init(unsigned char *buffer, unsigned int size,pthread_mutex_t * mutex)
  6. {
  7.     struct fifo *fifo;
  8.     fifo = (struct fifo *)malloc(sizeof(struct fifo));
  9.     if (!fifo) {
  10.         printf ( "malloc error/n" );
  11.         return NULL;
  12.     }
  13.     BUG_ON(size & (size-1));
  14.     fifo->buffer = buffer;
  15.     fifo->size = size;
  16.     fifo->in = fifo->out = 0;
  17.     fifo->mutex=mutex;
  18.     return fifo;
  19. }
  20. struct fifo *fifo_alloc(unsigned int size,pthread_mutex_t * mutex)
  21. {
  22.     unsigned char *buffer;
  23.     struct fifo *ret;
  24.     if (size & (size - 1)) {
  25.         fprintf(stderr,"size > 0x80000000/n");
  26.         size = roundup_pow_of_two(size);
  27.     }
  28.     buffer =(unsigned char *) malloc(size);
  29.     if (!buffer){
  30.         printf ( "malloc error/n" );
  31.         return NULL;
  32.     }
  33.     ret = fifo_init(buffer, size, mutex);
  34.     if ((unsigned long)ret<=0)
  35.     {
  36.         free(buffer);
  37.     }
  38.     return ret;
  39. }
  40. void fifo_free(struct fifo *fifo)
  41. {
  42.     free(fifo->buffer);
  43.     free(fifo);
  44. }
  45. unsigned int __fifo_put(struct fifo *fifo, unsigned char *buffer, unsigned int len)
  46. {
  47.     unsigned int l;
  48.     len = min(len, fifo->size - fifo->in + fifo->out);
  49.     l = min(len, fifo->size - (fifo->in & (fifo->size - 1)));
  50.     memcpy(fifo->buffer + (fifo->in & (fifo->size - 1)), buffer, l);
  51.     memcpy(fifo->buffer, buffer + l, len - l);
  52.     fifo->in += len;
  53.     return len;
  54. }
  55. unsigned int __fifo_get(struct fifo *fifo,
  56.              unsigned char *buffer, unsigned int len)
  57. {
  58.     unsigned int l;
  59.     len = min(len, fifo->in - fifo->out);
  60.     l = min(len, fifo->size - (fifo->out & (fifo->size - 1)));
  61.     memcpy(buffer, fifo->buffer + (fifo->out & (fifo->size - 1)), l);
  62.     fifo->out += len;
  63.     return len;
測試程序main.c如下
  1. #include    <stdio.h>
  2. #include    <string.h>
  3. #include    <pthread.h>
  4. #include    "fifo.h"
  5. #define FIFO_LENGTH 4096
  6. struct ll_param
  7. {
  8.     struct fifo * fifo;
  9.     int msg_len;
  10. };
  11. static struct ll_param fifo;
  12. void thread_reader(void * param)
  13. {
  14.     int read_len=0;
  15.     unsigned int counter=0;
  16.     unsigned char buffer[FIFO_LENGTH]={0};
  17.     struct ll_param * p=(struct ll_param *)param;
  18.     
  19.     for(;;)
  20.     {
  21.         bzero(buffer,FIFO_LENGTH);
  22.         read_len=fifo_get(p->fifo,buffer,32);
  23.         if(read_len!=0)
  24.         {
  25.             printf("Read len:%d,buffer is:%s/n",read_len,buffer);
  26.         }
  27.         usleep(50000);
  28.     }
  29. }
  30. void thread_writer(void * param)
  31. {
  32.     unsigned int write_len=0;
  33.     unsigned int counter=0;
  34.     unsigned char buffer[32]={0};
  35.     unsigned int ac_write_len=0;
  36.     struct ll_param * p=(struct ll_param *)param;
  37.     for(counter=0;counter<1000;counter++)
  38.     {
  39.         bzero(buffer,32);
  40.         sprintf((char *)buffer,"This is %d message./n",counter);
  41.         do{
  42.             ac_write_len=0;
  43.             write_len=fifo_put(p->fifo,buffer+ac_write_len,sizeof(buffer));
  44.             ac_write_len+=write_len;
  45.         }while(ac_write_len != sizeof(buffer));
  46.         usleep(100);
  47.     }
  48. }
  49. int main(void)
  50. {
  51.     pthread_t pidr;
  52.     pthread_t pidw;
  53.     pthread_mutex_t mutex;
  54.     pthread_mutex_init(&mutex,NULL);
  55.     fifo.msg_len=10;
  56.     fifo.fifo=fifo_alloc(FIFO_LENGTH,&mutex);
  57.     pthread_create(&pidw,NULL,(void *)thread_writer,&fifo);
  58.     pthread_create(&pidr,NULL,(void *)thread_reader,&fifo);
  59.     pthread_join(pidr,NULL);
  60.     pthread_join(pidw,NULL);
  61.     fifo_free(fifo.fifo);
  62.   pthread_mutex_destroy(&mutex);
  63.     return 0;
do
:
    gcc -g -O2 -o main main.c fifo.c -lpthread
如果只有一個讀線程和一個寫線程,可以使用不加 __ (下劃線)的函數。這樣可以提高效率。
如果有多個讀寫的話,要使用不帶下劃線的函數。
附上kfifo.c 和kfifo.h作爲對比的參考。
 
 
  1. kfifo.c:/*
  2.  * A simple kernel FIFO implementation.
  3.  *
  4.  * Copyright (C) 2004 Stelian Pop <[email protected]>
  5.  *
  6.  * This program is free software; you can redistribute it and/or modify
  7.  * it under the terms of the GNU General Public License as published by
  8.  * the Free Software Foundation; either version 2 of the License, or
  9.  * (at your option) any later version.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program; if not, write to the Free Software
  18.  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  *
  20.  */
  21. #include <linux/kernel.h>
  22. #include <linux/module.h>
  23. #include <linux/slab.h>
  24. #include <linux/err.h>
  25. #include <linux/kfifo.h>
  26. /**
  27.  * kfifo_init - allocates a new FIFO using a preallocated buffer
  28.  * @buffer: the preallocated buffer to be used.
  29.  * @size: the size of the internal buffer, this have to be a power of 2.
  30.  * @gfp_mask: get_free_pages mask, passed to kmalloc()
  31.  * @lock: the lock to be used to protect the fifo buffer
  32.  *
  33.  * Do NOT pass the kfifo to kfifo_free() after use ! Simply free the
  34.  * struct kfifo with kfree().
  35.  */
  36. struct kfifo *kfifo_init(unsigned char *buffer, unsigned int size,
  37.              unsigned int __nocast gfp_mask, spinlock_t *lock)
  38. {
  39.     struct kfifo *fifo;
  40.     /* size must be a power of 2 */
  41.     BUG_ON(size & (size - 1));
  42.     fifo = kmalloc(sizeof(struct kfifo), gfp_mask);
  43.     if (!fifo)
  44.         return ERR_PTR(-ENOMEM);
  45.     fifo->buffer = buffer;
  46.     fifo->size = size;
  47.     fifo->in = fifo->out = 0;
  48.     fifo->lock = lock;
  49.     return fifo;
  50. }
  51. EXPORT_SYMBOL(kfifo_init);
  52. /**
  53.  * kfifo_alloc - allocates a new FIFO and its internal buffer
  54.  * @size: the size of the internal buffer to be allocated.
  55.  * @gfp_mask: get_free_pages mask, passed to kmalloc()
  56.  * @lock: the lock to be used to protect the fifo buffer
  57.  *
  58.  * The size will be rounded-up to a power of 2.
  59.  */
  60. struct kfifo *kfifo_alloc(unsigned int size, unsigned int __nocast gfp_mask, spinlock_t *lock)
  61. {
  62.     unsigned char *buffer;
  63.     struct kfifo *ret;
  64.     /*
  65.      * round up to the next power of 2, since our 'let the indices
  66.      * wrap' tachnique works only in this case.
  67.      */
  68.     if (size & (size - 1)) {
  69.         BUG_ON(size > 0x80000000);
  70.         size = roundup_pow_of_two(size);
  71.     }
  72.     buffer = kmalloc(size, gfp_mask);
  73.     if (!buffer)
  74.         return ERR_PTR(-ENOMEM);
  75.     ret = kfifo_init(buffer, size, gfp_mask, lock);
  76.     if (IS_ERR(ret))
  77.         kfree(buffer);
  78.     return ret;
  79. }
  80. EXPORT_SYMBOL(kfifo_alloc);
  81. /**
  82.  * kfifo_free - frees the FIFO
  83.  * @fifo: the fifo to be freed.
  84.  */
  85. void kfifo_free(struct kfifo *fifo)
  86. {
  87.     kfree(fifo->buffer);
  88.     kfree(fifo);
  89. }
  90. EXPORT_SYMBOL(kfifo_free);
  91. /**
  92.  * __kfifo_put - puts some data into the FIFO, no locking version
  93.  * @fifo: the fifo to be used.
  94.  * @buffer: the data to be added.
  95.  * @len: the length of the data to be added.
  96.  *
  97.  * This function copies at most 'len' bytes from the 'buffer' into
  98.  * the FIFO depending on the free space, and returns the number of
  99.  * bytes copied.
  100.  *
  101.  * Note that with only one concurrent reader and one concurrent
  102.  * writer, you don't need extra locking to use these functions.
  103.  */
  104. unsigned int __kfifo_put(struct kfifo *fifo,
  105.              unsigned char *buffer, unsigned int len)
  106. {
  107.     unsigned int l;
  108.     len = min(len, fifo->size - fifo->in + fifo->out);
  109.     /* first put the data starting from fifo->in to buffer end */
  110.     l = min(len, fifo->size - (fifo->in & (fifo->size - 1)));
  111.     memcpy(fifo->buffer + (fifo->in & (fifo->size - 1)), buffer, l);
  112.     /* then put the rest (if any) at the beginning of the buffer */
  113.     memcpy(fifo->buffer, buffer + l, len - l);
  114.     fifo->in += len;
  115.     return len;
  116. }
  117. EXPORT_SYMBOL(__kfifo_put);
  118. /**
  119.  * __kfifo_get - gets some data from the FIFO, no locking version
  120.  * @fifo: the fifo to be used.
  121.  * @buffer: where the data must be copied.
  122.  * @len: the size of the destination buffer.
  123.  *
  124.  * This function copies at most 'len' bytes from the FIFO into the
  125.  * 'buffer' and returns the number of copied bytes.
  126.  *
  127.  * Note that with only one concurrent reader and one concurrent
  128.  * writer, you don't need extra locking to use these functions.
  129.  */
  130. unsigned int __kfifo_get(struct kfifo *fifo,
  131.              unsigned char *buffer, unsigned int len)
  132. {
  133.     unsigned int l;
  134.     len = min(len, fifo->in - fifo->out);
  135.     /* first get the data from fifo->out until the end of the buffer */
  136.     l = min(len, fifo->size - (fifo->out & (fifo->size - 1)));
  137.     memcpy(buffer, fifo->buffer + (fifo->out & (fifo->size - 1)), l);
  138.     /* then get the rest (if any) from the beginning of the buffer */
  139.     memcpy(buffer + l, fifo->buffer, len - l);
  140.     fifo->out += len;
  141.     return len;
  142. }
  143. EXPORT_SYMBOL(__kfifo_get);
kfifo.h:
 
  1. /*
  2.  * A simple kernel FIFO implementation.
  3.  *
  4.  * Copyright (C) 2004 Stelian Pop <[email protected]>
  5.  *
  6.  * This program is free software; you can redistribute it and/or modify
  7.  * it under the terms of the GNU General Public License as published by
  8.  * the Free Software Foundation; either version 2 of the License, or
  9.  * (at your option) any later version.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program; if not, write to the Free Software
  18.  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  *
  20.  */
  21. #ifndef _LINUX_KFIFO_H
  22. #define _LINUX_KFIFO_H
  23. #ifdef __KERNEL__
  24. #include <linux/kernel.h>
  25. #include <linux/spinlock.h>
  26. struct kfifo {
  27.     unsigned char *buffer;  /* the buffer holding the data */
  28.     unsigned int size;  /* the size of the allocated buffer */
  29.     unsigned int in;    /* data is added at offset (in % size) */
  30.     unsigned int out;   /* data is extracted from off. (out % size) */
  31.     spinlock_t *lock;   /* protects concurrent modifications */
  32. };
  33. extern struct kfifo *kfifo_init(unsigned char *buffer, unsigned int size,
  34.                 unsigned int __nocast gfp_mask, spinlock_t *lock);
  35. extern struct kfifo *kfifo_alloc(unsigned int size, unsigned int __nocast gfp_mask,
  36.                  spinlock_t *lock);
  37. extern void kfifo_free(struct kfifo *fifo);
  38. extern unsigned int __kfifo_put(struct kfifo *fifo,
  39.                 unsigned char *buffer, unsigned int len);
  40. extern unsigned int __kfifo_get(struct kfifo *fifo,
  41.                 unsigned char *buffer, unsigned int len);
  42. /**
  43.  * __kfifo_reset - removes the entire FIFO contents, no locking version
  44.  * @fifo: the fifo to be emptied.
  45.  */
  46. static inline void __kfifo_reset(struct kfifo *fifo)
  47. {
  48.     fifo->in = fifo->out = 0;
  49. }
  50. /**
  51.  * kfifo_reset - removes the entire FIFO contents
  52.  * @fifo: the fifo to be emptied.
  53.  */
  54. static inline void kfifo_reset(struct kfifo *fifo)
  55. {
  56.     unsigned long flags;
  57.     spin_lock_irqsave(fifo->lock, flags);
  58.     __kfifo_reset(fifo);
  59.     spin_unlock_irqrestore(fifo->lock, flags);
  60. }
  61. /**
  62.  * kfifo_put - puts some data into the FIFO
  63.  * @fifo: the fifo to be used.
  64.  * @buffer: the data to be added.
  65.  * @len: the length of the data to be added.
  66.  *
  67.  * This function copies at most 'len' bytes from the 'buffer' into
  68.  * the FIFO depending on the free space, and returns the number of
  69.  * bytes copied.
  70.  */
  71. static inline unsigned int kfifo_put(struct kfifo *fifo,
  72.                      unsigned char *buffer, unsigned int len)
  73. {
  74.     unsigned long flags;
  75.     unsigned int ret;
  76.     spin_lock_irqsave(fifo->lock, flags);
  77.     ret = __kfifo_put(fifo, buffer, len);
  78.     spin_unlock_irqrestore(fifo->lock, flags);
  79.     return ret;
  80. }
  81. /**
  82.  * kfifo_get - gets some data from the FIFO
  83.  * @fifo: the fifo to be used.
  84.  * @buffer: where the data must be copied.
  85.  * @len: the size of the destination buffer.
  86.  *
  87.  * This function copies at most 'len' bytes from the FIFO into the
  88.  * 'buffer' and returns the number of copied bytes.
  89.  */
  90. static inline unsigned int kfifo_get(struct kfifo *fifo,
  91.                      unsigned char *buffer, unsigned int len)
  92. {
  93.     unsigned long flags;
  94.     unsigned int ret;
  95.     spin_lock_irqsave(fifo->lock, flags);
  96.     ret = __kfifo_get(fifo, buffer, len);
  97.     /*
  98.      * optimization: if the FIFO is empty, set the indices to 0
  99.      * so we don't wrap the next time
  100.      */
  101.     if (fifo->in == fifo->out)
  102.         fifo->in = fifo->out = 0;
  103.     spin_unlock_irqrestore(fifo->lock, flags);
  104.     return ret;
  105. }
  106. /**
  107.  * __kfifo_len - returns the number of bytes available in the FIFO, no locking version
  108.  * @fifo: the fifo to be used.
  109.  */
  110. static inline unsigned int __kfifo_len(struct kfifo *fifo)
  111. {
  112.     return fifo->in - fifo->out;
  113. }
  114. /**
  115.  * kfifo_len - returns the number of bytes available in the FIFO
  116.  * @fifo: the fifo to be used.
  117.  */
  118. static inline unsigned int kfifo_len(struct kfifo *fifo)
  119. {
  120.     unsigned long flags;
  121.     unsigned int ret;
  122.     spin_lock_irqsave(fifo->lock, flags);
  123.     ret = __kfifo_len(fifo);
  124.     spin_unlock_irqrestore(fifo->lock, flags);
  125.     return ret;
  126. }
  127. #else
  128. #warning "don't include kernel headers in userspace"
  129. #endif /* __KERNEL__ */
  130. #endif
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章