example_atomic.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <linux/kernel.h>
  2. #include <linux/module.h>
  3. #include <linux/interrupt.h>
  4. #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
  5. #define BYTE_TO_BINARY(byte) \
  6. (byte & 0x80 ? '1' : '0'), \
  7. (byte & 0x40 ? '1' : '0'), \
  8. (byte & 0x20 ? '1' : '0'), \
  9. (byte & 0x10 ? '1' : '0'), \
  10. (byte & 0x08 ? '1' : '0'), \
  11. (byte & 0x04 ? '1' : '0'), \
  12. (byte & 0x02 ? '1' : '0'), \
  13. (byte & 0x01 ? '1' : '0')
  14. static void atomic_add_subtract(void)
  15. {
  16. atomic_t debbie;
  17. atomic_t chris = ATOMIC_INIT(50);
  18. atomic_set(&debbie, 45);
  19. /* subtract one */
  20. atomic_dec(&debbie);
  21. atomic_add(7, &debbie);
  22. /* add one */
  23. atomic_inc(&debbie);
  24. pr_info("chris: %d, debbie: %d\n",
  25. atomic_read(&chris), atomic_read(&debbie));
  26. }
  27. static void atomic_bitwise(void)
  28. {
  29. unsigned long word = 0;
  30. pr_info("Bits 0: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  31. set_bit(3, &word);
  32. set_bit(5, &word);
  33. pr_info("Bits 1: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  34. clear_bit(5, &word);
  35. pr_info("Bits 2: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  36. change_bit(3, &word);
  37. pr_info("Bits 3: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  38. if (test_and_set_bit(3, &word))
  39. pr_info("wrong\n");
  40. pr_info("Bits 4: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  41. word = 255;
  42. pr_info("Bits 5: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
  43. }
  44. static int example_atomic_init(void)
  45. {
  46. pr_info("example_atomic started\n");
  47. atomic_add_subtract();
  48. atomic_bitwise();
  49. return 0;
  50. }
  51. static void example_atomic_exit(void)
  52. {
  53. pr_info("example_atomic exit\n");
  54. }
  55. module_init(example_atomic_init);
  56. module_exit(example_atomic_exit);
  57. MODULE_AUTHOR("Bob Mottram");
  58. MODULE_DESCRIPTION("Atomic operations example");
  59. MODULE_LICENSE("GPL");