Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. #include <linux/kernel.h>
  2. #include <linux/module.h>
  3. #include <linux/fs.h>
  4. #include <asm/uaccess.h>
  5.  
  6. #define MAX_BUF_SIZE 1024
  7. #define DEVICE_NAME "MY_AUDIO_DEVICE"
  8. #define TRUE 1
  9. #define FALSE !TRUE
  10.  
  11. static ssize_t device_read(struct file*, char*, size_t, loff_t*);
  12. static ssize_t device_write(struct file*, const char*, size_t, loff_t*);
  13. static int device_open(struct inode*, struct file*);
  14. static int device_release(struct inode*, struct file*);
  15.  
  16. static char audio_buffer[MAX_BUF_SIZE] = {"THIS BUFFER DOES NOT REALLY INCLUDE AUDIO DATA"};
  17.  
  18. static struct file_operations fops =
  19. {
  20. .read = device_read,
  21. .write = device_write,
  22. .open = device_open,
  23. .release = device_release
  24. };
  25.  
  26. static int major_number = 0;
  27. static char is_opened = FALSE;
  28.  
  29. static int driver_init(void)
  30. {
  31. if ((major_number = register_chrdev(0, DEVICE_NAME, &fops)) < 0)
  32. {
  33. printk("register_chrdev failed with status = %d\n", major_number);
  34. return major_number;
  35. }
  36.  
  37. printk("Device driver was successfully loaded. The major number is: %d\n", major_number);
  38. printk("'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, major_number);
  39. return 0;
  40. }
  41.  
  42.  
  43. static void driver_cleanup(void)
  44. {
  45. unregister_chrdev(major_number, DEVICE_NAME);
  46. }
  47.  
  48. static int device_open(struct inode* node, struct file* f)
  49. {
  50. if (is_opened)
  51. return -EBUSY;
  52.  
  53. is_opened = TRUE;
  54.  
  55. return 0;
  56. }
  57.  
  58. static int device_release(struct inode* node, struct file* f)
  59. {
  60. is_opened = FALSE;
  61. return 0;
  62. }
  63.  
  64. static ssize_t device_write(struct file* file, const char* buffer, size_t length, loff_t* offset)
  65. {
  66. printk("Write operation is not supported on this device.\n");
  67. return -EINVAL;
  68. }
  69.  
  70. static ssize_t device_read(struct file* file, char* buffer, size_t length, loff_t* offset)
  71. {
  72. if (length >= MAX_BUF_SIZE)
  73. length = MAX_BUF_SIZE - 1;
  74. if (copy_to_user(buffer, audio_buffer, length))
  75. return -EINVAL;
  76. return length;
  77. }
  78.  
  79. module_init(driver_init);
  80. module_exit(driver_cleanup);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement