• linux同步机制-completion


    一、completion

    1.1 什么是completion

    linux内核中,完成量completion是一种代码同步机制。如果有一个或多个线程必须等待某个内核活动操作达到某个点或某个特定状态,那么completion完成量可以提供一个无竞争的解决方案。

    1.2 completion的使用
    1.2.1 定义并初始化完成量
    1. // 方式一
    2. struct completion mycompletion;
    3. init_completion(&mycompletion)
    4. // 方式二
    5. DECLARE_COMPLETION(mycompletion);

    以下两种方式是等效的,都实现了定义和初始化完成量mycompletion的功能。

    1.2.2 等待完成量
    1. wait_for_completion(&mycompletion);
    2. wait_for_completion_interruptible(&mycompletion);
    3. wait_for_completion_timeout(&mycompletion,timeout);
    1.2.3 唤醒完成量
    complete(&mycompletion);

    二、completion实现源码

    2.1 struct completion结构体

    struct completion结构体定义位于include/linux/completion.h文件中:

    1. /*
    2. * struct completion - structure used to maintain state for a "completion"
    3. *
    4. * This is the opaque structure used to maintain the state for a "completion".
    5. * Completions currently use a FIFO to queue threads that have to wait for
    6. * the "completion" event.
    7. *
    8. * See also: complete(), wait_for_completion() (and friends _timeout,
    9. * _interruptible, _interruptible_timeout, and _killable), init_completion(),
    10. * reinit_completion(), and macros DECLARE_COMPLETION(),
    11. * DECLARE_COMPLETION_ONSTACK().
    12. */
    13. struct completion {
    14. unsigned int done;
    15. wait_queue_head_t wait;
    16. };

    wait等待队列头,用来放置需要等到的任务,done用来指示任务是否完成。

    可以看到其内部是通过等待队列来实现的。

    2.2 init_completion

    init_completion用于初始化完成量:

    1. #define init_completion(x) __init_completion(x)
    2. /**
    3. * init_completion - Initialize a dynamically allocated completion
    4. * @x: pointer to completion structure that is to be initialized
    5. *
    6. * This inline function will initialize a dynamically created completion
    7. * structure.
    8. */
    9. static inline void __init_completion(struct completion *x)
    10. {
    11. x->done = 0;
    12. // 初始化等待队列头
    13. init_waitqueue_head(&x->wait);
    14. }
    2.3 等待完成量
    2.3.1wait_for_completion

    wait_for_completion用于等待完成量的释放,定义在kernel/sched/completion.c;

    1. do_wait_for_common(struct completion *x,
    2. long (*action)(long), long timeout, int state)
    3. {
    4. if (!x->done) {
    5. DECLARE_WAITQUEUE(wait, current);
    6. __add_wait_queue_entry_tail_exclusive(&x->wait, &wait);
    7. do {
    8. if (signal_pending_state(state, current)) {
    9. timeout = -ERESTARTSYS;
    10. break;
    11. }
    12. __set_current_state(state);
    13. spin_unlock_irq(&x->wait.lock);
    14. timeout = action(timeout);
    15. spin_lock_irq(&x->wait.lock);
    16. } while (!x->done && timeout);
    17. __remove_wait_queue(&x->wait, &wait);
    18. if (!x->done)
    19. return timeout;
    20. }
    21. if (x->done != UINT_MAX)
    22. x->done--;
    23. return timeout ?: 1;
    24. }
    25. /**
    26. * wait_for_completion: - waits for completion of a task
    27. * @x: holds the state of this particular completion
    28. *
    29. * This waits to be signaled for completion of a specific task. It is NOT
    30. * interruptible and there is no timeout.
    31. *
    32. * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
    33. * and interrupt capability. Also see complete().
    34. */
    35. void __sched wait_for_completion(struct completion *x)
    36. {
    37. wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
    38. }

    wait_for_completion函数的主要作用是等待某个特定任务的完成。当调用该函数时,如果任务的完成状态没有被设置为完成,当前线程将被阻塞,直到任务的完成状态被设置为完成。

    需要注意的是,wait_for_completion函数是不可中断的(non-interruptible),这意味着无论是否收到中断信号,当前线程都会一直等待任务的完成。此外,该函数也没有超时功能,即使等待时间很长,也不会自动超时返回。

    2.3.2 wait_for_completion_interruptible

    wait_for_completion_interruptible同样用于等待完成量的释放,只不过该函数是可以中断的,定义在kernel/sched/completion.c;

    1. /**
    2. * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
    3. * @x: holds the state of this particular completion
    4. *
    5. * This waits for completion of a specific task to be signaled. It is
    6. * interruptible.
    7. *
    8. * Return: -ERESTARTSYS if interrupted, 0 if completed.
    9. */
    10. int __sched wait_for_completion_interruptible(struct completion *x)
    11. {
    12. long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
    13. if (t == -ERESTARTSYS)
    14. return t;
    15. return 0;
    16. }
    2.4 complete

    complete函数用于唤醒等待此特定complete事件的单个线程,定义在kernel/sched/completion.c;

    1. /**
    2. * complete: - signals a single thread waiting on this completion
    3. * @x: holds the state of this particular completion
    4. *
    5. * This will wake up a single thread waiting on this completion. Threads will be
    6. * awakened in the same order in which they were queued.
    7. *
    8. * See also complete_all(), wait_for_completion() and related routines.
    9. *
    10. * If this function wakes up a task, it executes a full memory barrier before
    11. * accessing the task state.
    12. */
    13. void complete(struct completion *x)
    14. {
    15. unsigned long flags;
    16. spin_lock_irqsave(&x->wait.lock, flags);
    17. if (x->done != UINT_MAX)
    18. x->done++;
    19. __wake_up_locked(&x->wait, TASK_NORMAL, 1);
    20. spin_unlock_irqrestore(&x->wait.lock, flags);
    21. }

    当调用该函数时,如果有线程正在等待该完成状态,它将被唤醒并继续执行。

    需要注意的是,complete函数会按照线程入队的顺序依次唤醒等待的线程。

    2.5 completion_done

    completion_done函数用于检测某个complete是否有正在等待的线程,定义在kernel/sched/completion.c;

    1. /**
    2. * completion_done - Test to see if a completion has any waiters
    3. * @x: completion structure
    4. *
    5. * Return: 0 if there are waiters (wait_for_completion() in progress)
    6. * 1 if there are no waiters.
    7. *
    8. * Note, this will always return true if complete_all() was called on @X.
    9. */
    10. bool completion_done(struct completion *x)
    11. {
    12. unsigned long flags;
    13. if (!READ_ONCE(x->done))
    14. return false;
    15. /*
    16. * If ->done, we need to wait for complete() to release ->wait.lock
    17. * otherwise we can end up freeing the completion before complete()
    18. * is done referencing it.
    19. */
    20. spin_lock_irqsave(&x->wait.lock, flags);
    21. spin_unlock_irqrestore(&x->wait.lock, flags);
    22. return true;
    23. }

    当调用该函数时,如果有线程正在等待该完成状态,则返回0;如果没有线程在等待,则返回1。

    需要注意的是,如果之前调用了complete_all函数来完成所有等待的线程,则无论如何都会返回1,表示没有等待的线程。

    三、completion示例程序

    3.1 驱动程序

    completion_dev.c文件定义:

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #include
    10. #include
    11. #include /* For BUG_ON. */
    12. #include
    13. #include /* Needed for the macros */
    14. #include /* Needed for pr_info() */
    15. #include /* Needed by all modules */
    16. #include
    17. #include
    18. #include
    19. #include
    20. #include
    21. #include
    22. #include
    23. #include
    24. #include
    25. #include
    26. #include
    27. #include
    28. #define DELAY_CMD_WRITE _IOW('A',0,unsigned int)
    29. #define DELAY_CMD_READ _IOW('A',1,unsigned int)
    30. #define ERROR (-1)
    31. DEFINE_KFIFO(myfifo, char, 1024);
    32. dev_t devid; // 起始设备编号
    33. struct cdev hello_cdev; // 保存操作结构体的字符设备
    34. struct class *hello_cls;
    35. DECLARE_WAIT_QUEUE_HEAD(wq);
    36. static int hello_open(struct inode *inode, struct file *file)
    37. {
    38. pr_info("hello_open \n");
    39. return 0;
    40. }
    41. static ssize_t hello_write(struct file *filp, const char __user *user_buffer,
    42. size_t size, loff_t *offset)
    43. {
    44. int ret;
    45. unsigned int len = 0;
    46. pr_info("write");
    47. ret = kfifo_from_user(&myfifo, user_buffer, size, &len);
    48. if (ret != 0) {
    49. pr_err("kfifo_from_user error");
    50. return 0;
    51. }
    52. if (len <= 0)
    53. return 0;
    54. *offset += len;
    55. wake_up(&wq);
    56. return len;
    57. }
    58. static ssize_t hello_read(struct file *filp, char __user *user_buffer,
    59. size_t count, loff_t *offset)
    60. {
    61. int ret;
    62. unsigned int len = 0;
    63. pr_info("read");
    64. ret = kfifo_to_user(&myfifo, user_buffer, count, &len);
    65. if (len <= 0)
    66. return 0;
    67. *offset += len;
    68. return len;
    69. }
    70. unsigned int hello_poll(struct file *flip, struct poll_table_struct *table)
    71. {
    72. int mask = 0;
    73. pr_info("hello_poll \n");
    74. poll_wait(flip, &wq, table);
    75. if (kfifo_is_empty(&myfifo)) {
    76. } else {
    77. mask |= POLLIN | POLLRDNORM;
    78. }
    79. return mask;
    80. }
    81. int hello_close(struct inode *inode, struct file *flip)
    82. {
    83. pr_info("hello_close \n");
    84. return 0;
    85. }
    86. // 定义并初始化完成量
    87. DECLARE_COMPLETION(mycompletion);
    88. static long hello_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
    89. {
    90. pr_info("cmd %d\n", cmd);
    91. switch (_IOC_NR(cmd)) {
    92. case 0: {
    93. pr_info("i am waiting \n");
    94. // 等待完成量
    95. wait_for_completion(&mycompletion);
    96. pr_info("haha,i get the message\n");
    97. break;
    98. }
    99. case 1: {
    100. pr_info("complete \n");
    101. // 唤醒完成量
    102. complete(&mycompletion);
    103. break;
    104. }
    105. default: {
    106. pr_info("default: \n");
    107. }
    108. }
    109. return 0;
    110. }
    111. static const struct file_operations hello_fops = {
    112. .owner = THIS_MODULE,
    113. .open = hello_open,
    114. .read = hello_read,
    115. .write = hello_write,
    116. .poll = hello_poll,
    117. .release = hello_close,
    118. .unlocked_ioctl = hello_ioctl,
    119. };
    120. static __init int hello_init(void)
    121. {
    122. int err;
    123. pr_info("hello driver init\n");
    124. /* 动态分配字符设备: (major,0) */
    125. err = alloc_chrdev_region(&devid, 0, 1, "hello");
    126. if (err != 0) {
    127. return err;
    128. }
    129. cdev_init(&hello_cdev, &hello_fops);
    130. cdev_add(&hello_cdev, devid, 1);
    131. /* 创建类,它会在sys目录下创建/sys/class/hello这个类 */
    132. hello_cls = class_create(THIS_MODULE, "hello");
    133. if(IS_ERR(hello_cls)){
    134. printk("can't create class\n");
    135. return ERROR;
    136. }
    137. /* 在/sys/class/hello下创建hello设备,然后mdev通过这个自动创建/dev/hello这个设备节点 */
    138. device_create(hello_cls, NULL, devid, NULL, "hello");
    139. return 0;
    140. }
    141. static void __exit hello_exit(void)
    142. {
    143. pr_info("hello driver exit\n");
    144. /* 注销类、以及类设备 /sys/class/hello会被移除*/
    145. device_destroy(hello_cls, devid);
    146. class_destroy(hello_cls);
    147. cdev_del(&hello_cdev);
    148. unregister_chrdev_region(devid, 1);
    149. }
    150. module_init(hello_init);
    151. module_exit(hello_exit);
    152. MODULE_LICENSE("GPL");

    Makefile文件:

    1. # SPDX-License-Identifier: Apache-2.0
    2. obj-m := completion_dev.o
    3. KDIR := /lib/modules/$(shell uname -r)/build
    4. PWD := $(shell pwd)
    5. default:
    6. $(MAKE) -C $(KDIR) M=$(PWD) SUBDIRS=$(PWD) modules
    7. clean:
    8. $(MAKE) -C $(KDIR) M=$(PWD) SUBDIRS=$(PWD) clean

    指向编译安装命令:

    1. make
    2. insmod completion_dev.ko
    3.2 应用程序

    main.c文件定义:

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #include
    10. #include
    11. #include
    12. #define DELAY_CMD_0_WRITE _IOW('A',0,unsigned int)
    13. #define DELAY_CMD_1_READ _IOW('A',1,unsigned int)
    14. static void* write01(void *ptr)
    15. {
    16. int fd = open("/dev/hello", O_RDWR, O_NONBLOCK);
    17. if (fd < 0) {
    18. perror("open");
    19. printf("error open\n");
    20. return NULL;
    21. }
    22. printf("write start \n");
    23. ioctl(fd, DELAY_CMD_0_WRITE, 100);
    24. printf("write end \n");
    25. close(fd);
    26. return NULL;
    27. }
    28. static void* read01(void *ptr)
    29. {
    30. int fd = open("/dev/hello", O_RDWR, O_NONBLOCK);
    31. if (fd < 0) {
    32. perror("open");
    33. printf("error open\n");
    34. return NULL;
    35. }
    36. printf("read start \n");
    37. ioctl(fd, DELAY_CMD_1_READ, 100);
    38. printf("read end \n");
    39. close(fd);
    40. return NULL;
    41. }
    42. /**
    43. * first read then write
    44. */
    45. int main()
    46. {
    47. pthread_t thread, thread2;
    48. pthread_create(&thread, NULL, write01, NULL);
    49. sleep(2);
    50. pthread_create(&thread2, NULL, read01, NULL);
    51. pthread_join(thread, NULL);
    52. pthread_join(thread2, NULL);
    53. printf("main exit\n");
    54. return EXIT_SUCCESS;
    55. }

    编译运行:

    1. gcc -o main main.c -lpthread
    2. ./main

    应用先发0,再发1 ,驱动中的0会等待1的完成量,可以看到打印信息:

    1. write start
    2. read start
    3. write end
    4. read end
    5. main exit

    参考文章

    [1] linux驱动移植-SPI控制器驱动

    [2] 深入理解Linux内核 -- completion机制

    [3] linux内核完成量completion使用说明

  • 相关阅读:
    「Redis」04 发布和订阅
    一步一图带你深入理解 Linux 虚拟内存管理
    【PAT(甲级)】1066 Root of AVL Tree
    漏洞复现----48、Airflow dag中的命令注入(CVE-2020-11978)
    单例设计模式常见的七种写法
    cadence virtuoso寄生参数提取问题
    代码随想录算法训练营第四十九天丨 动态规划part12
    Stream 的使用,我觉得使用它是非常方便的
    【软件安装】Linux中RabbitMQ的安装
    计算机毕设(附源码)JAVA-SSM基于web的医院门诊管理系统
  • 原文地址:https://blog.csdn.net/Graceful_scenery/article/details/134283524