example_atomic.c 1.8 KB

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