SlideShare a Scribd company logo
Unit-5
CHAR DRIVERS AND DEBUGGING TECHNIQUES
• The Design of Scull:
– Scull stands for Simple Character Utility for Loading
Localities.
– It is Not hardware dependent
– Just acts on some memory allocated from the
kernel
– It uses part of the memory to simulate the device
– It shows the interfaces between the kernel and
the character driver
– It shows the actual installation and startup.
• The Design of Scull:
– There are several types of scull devices
– scull[0-3]
• This type has four members, scull0 , scull1 , scull2 and scull3 .
• Each encapsulates a memory area that is global and
persistent .
• Global means that all opens of these devices share the same
data.
• Persistent means that data isn't lost across closes and
reopens.
– scullpipe[0-3]
• Four devices that act like pipes between a reader and writer
process.
• Blocking and non-blocking reads and writes are illustrated
here.
• The Design of Scull:
– There are several types of scull devices
– Scullsingle:allows only one process at a time to
use the driver,
– scullpriv:private to each virtual console
– sculluid :Can be opened multiple times by one
user at a time
– scullwuid:Blocks open if another user is locking
the device
Major and Minor Numbers
• Char devices are accessed through names in
the file system
– Special files/nodes in /dev folder
>cd /dev
>ls –l
crw------- 1 root root 5, 1 Apr 12 16:50 console
brw-rw---- 1 root disk 8, 0 Apr 12 16:50 sda
brw-rw---- 1 root disk 8, 1 Apr 12 16:50 sda1
Char drivers are
identified by a
“c”
Block drivers are
identified by a
“b”
Major numbers
Minor numbers
Major and Minor Numbers
• Major number identifies the driver associated
with the device
– /dev/sda and /dev/sda1 are managed by
driver 8
• Minor number is used by the kernel to
determine which device is being referred to
The Internal Representation of Device
Numbers
• dev_t type is used to hold device numbers—
both the major and minor parts, defined in
<linux/types.h>
• Macros defined in <linux/kdev_t.h>
– 12 bits for the major number
• Use MAJOR(dev_t dev) to obtain the major number
– 20 bits for the minor number
• Use MINOR(dev_t dev) to obtain the minor
number
– Use MKDEV(int major, int minor) to turn
them into a dev_t
Allocating and Freeing Device Numbers
• To obtain one or more device numbers, use
int register_chrdev_region(dev_t first,
unsigned int count, char *name);
– first
• Beginning device number
• Minor device number is often 0
– count
• Requested number of contiguous device numbers
– name
• Name of the device
Allocating and Freeing Device Numbers
• Kernel can allocate a major number on the
fly(dynamic allocation)
int alloc_chrdev_region(dev_t *dev, unsigned
int firstminor, unsigned int count, char
*name);
– dev
• Output-only parameter that holds the first number on
success
– firstminor
• Requested first minor number
• Often 0
Allocating and Freeing Device Numbers
• To free your device numbers, use
int unregister_chrdev_region(dev_t first,
unsigned int count);
Some Important Data Structures
• file_operations
• file
• inode
• These are Defined in <linux/fs.h>
File Operations
struct file_operations {
struct module *owner;
/* pointer to the module that owns the structure prevents
the module from being unloaded while in use */
loff_t (*llseek) (struct file *, loff_t, int);
/* change the current position in a file
returns a 64-bit offset, or a negative value on errors
*/
ssize_t (*read) (struct file *, char __user *, size_t,
loff_t *);
/* returns the number of bytes read, or a negative value
on errors */
ssize_t (*aio_read) (struct kiocb *, const struct iovec *,
unsigned long, loff_t);
/* might return before a read completes */
File Operations
ssize_t (*write) (struct file *, const char __user *,
size_t, loff_t *);
/* returns the number of written bytes, or a negative
value on error */
ssize_t (*aio_write) (struct kiocb *,
const struct iovec *,
unsigned long, loff_t);
int (*readdir) (struct file *, void *, filldir_t);
/* this function pointer should be NULL for devices */
unsigned int (*poll) (struct file *,
struct poll_table_struct *);
/* query whether a read or write to file descriptors would
block */
int (*unlocked_ioctl) (struct file *, unsigned int,
unsigned long);
int (*compat_ioctl) (struct file *, unsigned int,
unsigned long);
/* provides a way to issue device-specific commands
(e.g., formatting) */
File Operations
int (*mmap) (struct file *, struct vm_area_struct *);
/* map a device memory to a process’s address */
int (*open) (struct inode *, struct file *);
/* first operation performed on the device file
if not defined, opening always succeeds, but driver
is not notified */
int (*flush) (struct file *, fl_owner_t id);
/* invoked when a process closes its copy of a file
descriptor for a device
not to be confused with fsync */
int (*release) (struct inode *, struct file *);
/* invoked when the file structure is being released */
int (*fsync) (struct file *, loff_t, loff_t, int datasync);
/* flush pending data for a file */
int (*aio_fsync) (struct kiocb *, int datasync);
/* asynchronous version of fsync */
int (*fasync) (int, struct file *, int);
/* notifies the device of a change in its FASYNC flag */
File Operations
int (*flock) (struct file *, int, struct file_lock *);
/* file locking for regular files, almost never
implemented by device drivers */
ssize_t (*splice_read) (struct file *, loff_t *, struct
pipe_inode_info *, size_t,
unsigned int);
ssize_t (*splice_write) (struct pipe_inode_info *, file *,
loff_t *, size_t, unsigned int);
/* implement gather/scatter read and write operations */
ssize_t (*sendpage) (struct file *, struct page *, int,
size_t, loff_t *, int);
/* called by kernel to send data, one page at a time
usually not used by device drivers */
File Operations
unsigned long (*get_unmapped_area) (struct file *,
unsigned long, unsigned long, unsigned long,
unsigned long);
/* finds a location in the process’s memory to map in a
memory segment on the underlying device
used to enforce alignment requirements
most drivers do not use this function */
int (*check_flags) (int);
/* allows a module to check flags passed to an fcntl call
*/
int (*setlease) (struct file *, long, struct file_lock *);
/* Establishes a lease on a file. Most drivers do not use
this function */
long (*fallocate) (struct file *file, int mode,
loff_t offset, loff_t len)
/* Guarantees reserved space on storage for a file. Most
drivers do not use this function */
};
The File Structure
• struct file
– Nothing to do with the FILE pointers
• Defined in the C Library
– Represents an open file
• A pointer to file is often called filp
The File Structure
• Some important fields
– fmode_t f_mode;
• Identifies the file as either readable or writable
– loff_t f_pos;
• Current reading/writing position (64-bits)
– unsigned int f_flags;
• File flags, such as O_RDONLY, O_NONBLOCK, O_SYNC
The File Structure
• Some important fields
– struct file_operations *f_op;
• Operations associated with the file
• Dynamically replaceable pointer
– Equivalent of method overriding in OO programming
– void *private_data;
• Can be used to store additional data structures
• Needs to be freed during the release method
The File Structure
• Some important fields
– struct dentry *f_dentry;
• Directory entry associated with the file
• Used to access the inode data structure
– filp->f_dentry->d_inode
The i-node Structure
• There can be numerous file structures
(multiple open descriptors) for a single file
• Only one inode structure per file
The i-node Structure
• Some important fields
– dev_t i_rdev;
• Contains device number
• For portability, use the following macros
– unsigned int iminor(struct inode *inode);
– unsigned int imajor(struct inode *inode);
– struct cdev *i_cdev;
• Contains a pointer to the data structure that refers to a
char device file
Char Device Registration
• Need to allocate struct cdev to represent
char devices
#include <linux/cdev.h>
/* first way */
struct cdev *my_cdev = cdev_alloc();
my_cdev->ops = &my_fops;
/* second way, for embedded cdev structure, call
this function – (see scull driver) */
void cdev_init(struct cdev *cdev, struct
file_operations *fops);
Char Device Registration
• Either way
– Need to initialize file_operations and set owner
to THIS_MODULE
• Inform the kernel by calling
int cdev_add(struct cdev *dev, dev_t num,
unsigned int count);
– num: first device number
– count: number of device numbers
• Remove a char device, call this function
void cdev_del(struct cdev *dev);
The open Method
• In most drivers, open should
– Check for device-specific errors
– Initialize the device (if opened for the first time)
– Update the f_op pointer, as needed
– Allocate and fill data structure in
filp->private_data
The release Method
• Deallocate filp->private_data
• Shut down the device on last close
– One release call per open
• Potentially multiple close calls per open due to
fork/dup
• scull has no hardware to shut down
int scull_release(struct inode *inode, struct file *filp) {
return 0;
}
scull’s Memory Usage
• Dynamically allocated
• #include <linux/slab.h>
– void *kmalloc(size_t size, int
flags);
• Allocate size bytes of memory
• For now, always use GFP_KERNEL
• Return a pointer to the allocated memory, or NULL if
the allocation fails
– void kfree(void *ptr);
read and write
ssize_t (*read) (struct file *filp, char __user *buff,
size_t count, loff_t *offp);
ssize_t (*write) (struct file *filp, const char __user *buff,
size_t count, loff_t *offp);
– filp: file pointer
– buff: a user-space pointer
• May not be valid in kernel mode
• Might be swapped out
• Could be malicious
– count: size of requested transfer
– offp: file position pointer
readv and writev
• Vector versions of read and write
– Take an array of structures
• Each contains a pointer to a buffer and a length
• Debugging Support in the Kernel:
• The following are the list of configuration options that
should be enabled for kernels used for development
• -->CONFIG_DEBUG_KERNEL
This option just makes other debugging options
available; it should be turned on but does not, by itself,
enable any features.
• -->CONFIG_DEBUG_SLAB
This crucial option turns on several types of checks in
the kernel memory allocation functions
• -->CONFIG_PROFILING
This option is found under "Profiling support." Profiling
is normally used for system performance tuning,
• Debugging with printk:
• There following are possible loglevel strings, defined in the header
<linux/kernel.h>;
• we list them in order of decreasing severity:
• KERN_EMERG
Used for emergency messages, usually those that precede a crash.
• KERN_ALERT
A situation requiring immediate action.
• KERN_CRIT
• Critical conditions, often related to serious hardware or software
failures.
• KERN_ERR
Used to report error conditions; device drivers often use KERN_ERR to
report hardware difficulties.
• Debugging by Watching:
• ----------------------
1.The strace command is a powerful tool that shows all the system calls
issued by a userspace program.
2.strace receives information from the kernel itself.
• Debugging by querying:
• ----------------------
1./proc--Proc file system (procfs) is virtual file system created on fly when
system boots and is dissolved at time of system shut down.
It contains the useful information about the processes that are currently
running, it is regarded as control and information centre for kernel.
The proc file system also provides communication medium between
kernel space and user space.
It is the best way to get relevant information is to query the system when
you need the information, instead of continually producing data.
2.ioctl
-------
ioctl (an abbreviation of input/output control) is a system call for device-
specific input/output operations and other operations which cannot be
expressed by regular system calls. It takes a parameter specifying a
request code; the effect of a call depends completely on the request code.
Request codes are often device-specific. For instance, a CD-ROM device
driver which can instruct a physical device to eject a disc would provide an
ioctl request code to do that.
Debugging System Faults
• Oops message:
• An “Oops” is what the kernel throws at us when it finds something
faulty, or an exception, in the kernel code. It’s somewhat like the
segfaults of user-space. An Oops dumps its message on the
console; it contains the processor status and the CPU registers of
when the fault occurred. The offending process that triggered this
Oops gets killed without releasing locks or cleaning up structures.
The system may not even resume its normal operations sometimes;
this is called an unstable state.
• System hangs:
• Although most bugs in kernel code end up as oops messages,
sometimes they can completely hang the system. If the system
hangs, no message is printed.
Debuggers and Related Tools
• Using gdb:
• GDB basically helps us to do four main things to catch flaws in the source code.
• Start the program, specifying arguments that may affect the general behavior.
• Stop the program on specified conditions.
• Examine the crash or when program was stopped.
• Change the code and to experiment with the modified code instantaneously.
• Kdb is simplistic shell-style interface which you can use on a system console with a
keyboard or serial console. You can use it to inspect memory, registers, process
lists, dmesg, and even set breakpoints to stop in a certain location. Kdb is not a
source level debugger, although you can set breakpoints and execute some basic
kernel run control. Kdb is mainly aimed at doing some analysis to aid in
development or diagnosing kernel problems
• Debuggers and Related Tools:
• ----------------------------
• Kgdb is intended to be used as a source level debugger for the Linux
kernel. It is used along with gdb to debug a Linux kernel. The expectation
is that gdb can be used to “break in” to the kernel to inspect memory,
variables and look through call stack information similar to the way an
application developer would use gdb to debug an application. It is possible
to place breakpoints in kernel code and perform some limited execution
stepping.
• User-Mode Linux (UML) is an interesting concept. It is structured as a
separate port of the Linux kernel with its own arch/um subdirectory. It
does not run on a new type of hardware, however; instead, it runs on a
virtual machine implemented on the Linux system call interface. Thus,
UML allows the Linux kernel to run as a separate, user-mode process on a
Linux system.
• The Linux Trace Toolkit (LTT) is a kernel patch and a set of related utilities
that allow the tracing of events in the kernel. The trace includes timing
information and can create a reasonably complete picture of what
happened over a given period of time.

More Related Content

What's hot

Driver development – memory management
Driver development – memory managementDriver development – memory management
Driver development – memory management
Vandana Salve
 
Linux device drivers
Linux device driversLinux device drivers
Linux device drivers
Abhishek Sagar
 
LINUX Device Drivers
LINUX Device DriversLINUX Device Drivers
LINUX Device Drivers
Partha Bhattacharya
 
brief intro to Linux device drivers
brief intro to Linux device driversbrief intro to Linux device drivers
brief intro to Linux device drivers
Alexandre Moreno
 
Linux Device Driver’s
Linux Device Driver’sLinux Device Driver’s
Linux Device Driver’s
Rashmi Warghade
 
Board support package_on_linux
Board support package_on_linuxBoard support package_on_linux
Board support package_on_linux
Vandana Salve
 
Kernel module programming
Kernel module programmingKernel module programming
Kernel module programming
Vandana Salve
 
Embedded Systems: Lecture 14: Introduction to GNU Toolchain (Binary Utilities)
Embedded Systems: Lecture 14: Introduction to GNU Toolchain (Binary Utilities)Embedded Systems: Lecture 14: Introduction to GNU Toolchain (Binary Utilities)
Embedded Systems: Lecture 14: Introduction to GNU Toolchain (Binary Utilities)
Ahmed El-Arabawy
 
Linux Programming
Linux ProgrammingLinux Programming
Linux internal
Linux internalLinux internal
Linux internalmcganesh
 
Type of Embedded core
Type of Embedded core Type of Embedded core
Type of Embedded core mukul bhardwaj
 
Linux Module Programming
Linux Module ProgrammingLinux Module Programming
Linux Module Programming
Amir Payberah
 
Device Drivers
Device DriversDevice Drivers
Device Drivers
Kushal Modi
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
Tushar B Kute
 
linux device driver
linux device driverlinux device driver
linux device driver
Rahul Batra
 
Linux Kernel and Driver Development Training
Linux Kernel and Driver Development TrainingLinux Kernel and Driver Development Training
Linux Kernel and Driver Development Training
Stephan Cadene
 
Linux Internals - Interview essentials - 1.0
Linux Internals - Interview essentials - 1.0Linux Internals - Interview essentials - 1.0
Linux Internals - Interview essentials - 1.0
Emertxe Information Technologies Pvt Ltd
 
Course 102: Lecture 9: Input Output Internals
Course 102: Lecture 9: Input Output Internals Course 102: Lecture 9: Input Output Internals
Course 102: Lecture 9: Input Output Internals
Ahmed El-Arabawy
 
Introduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device Drivers
RajKumar Rampelli
 

What's hot (20)

Driver development – memory management
Driver development – memory managementDriver development – memory management
Driver development – memory management
 
Linux device drivers
Linux device driversLinux device drivers
Linux device drivers
 
LINUX Device Drivers
LINUX Device DriversLINUX Device Drivers
LINUX Device Drivers
 
brief intro to Linux device drivers
brief intro to Linux device driversbrief intro to Linux device drivers
brief intro to Linux device drivers
 
Linux Device Driver’s
Linux Device Driver’sLinux Device Driver’s
Linux Device Driver’s
 
Board support package_on_linux
Board support package_on_linuxBoard support package_on_linux
Board support package_on_linux
 
Kernel module programming
Kernel module programmingKernel module programming
Kernel module programming
 
Embedded Systems: Lecture 14: Introduction to GNU Toolchain (Binary Utilities)
Embedded Systems: Lecture 14: Introduction to GNU Toolchain (Binary Utilities)Embedded Systems: Lecture 14: Introduction to GNU Toolchain (Binary Utilities)
Embedded Systems: Lecture 14: Introduction to GNU Toolchain (Binary Utilities)
 
Linux Programming
Linux ProgrammingLinux Programming
Linux Programming
 
Linux internal
Linux internalLinux internal
Linux internal
 
Type of Embedded core
Type of Embedded core Type of Embedded core
Type of Embedded core
 
Unix kernal
Unix kernalUnix kernal
Unix kernal
 
Linux Module Programming
Linux Module ProgrammingLinux Module Programming
Linux Module Programming
 
Device Drivers
Device DriversDevice Drivers
Device Drivers
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
 
linux device driver
linux device driverlinux device driver
linux device driver
 
Linux Kernel and Driver Development Training
Linux Kernel and Driver Development TrainingLinux Kernel and Driver Development Training
Linux Kernel and Driver Development Training
 
Linux Internals - Interview essentials - 1.0
Linux Internals - Interview essentials - 1.0Linux Internals - Interview essentials - 1.0
Linux Internals - Interview essentials - 1.0
 
Course 102: Lecture 9: Input Output Internals
Course 102: Lecture 9: Input Output Internals Course 102: Lecture 9: Input Output Internals
Course 102: Lecture 9: Input Output Internals
 
Introduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device Drivers
 

Similar to Char Drivers And Debugging Techniques

Writing Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linux
RajKumar Rampelli
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
Tushar B Kute
 
Ganesh naik linux_kernel_internals
Ganesh naik linux_kernel_internalsGanesh naik linux_kernel_internals
Ganesh naik linux_kernel_internals
Ganesh Naik
 
Ganesh naik linux_kernel_internals
Ganesh naik linux_kernel_internalsGanesh naik linux_kernel_internals
Ganesh naik linux_kernel_internals
nullowaspmumbai
 
The TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux KernelThe TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux Kernel
Divye Kapoor
 
Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)
Emertxe Information Technologies Pvt Ltd
 
Linux io introduction-fudcon-2015-with-demo-slides
Linux io introduction-fudcon-2015-with-demo-slidesLinux io introduction-fudcon-2015-with-demo-slides
Linux io introduction-fudcon-2015-with-demo-slides
KASHISH BHATIA
 
Lamp
LampLamp
LampReka
 
Lamp1
Lamp1Lamp1
Lamp1Reka
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - Processes
HelpWithAssignment.com
 
Auditing the Opensource Kernels
Auditing the Opensource KernelsAuditing the Opensource Kernels
Auditing the Opensource KernelsSilvio Cesare
 
Operating Systems 1 (5/12) - Architectures (Unix)
Operating Systems 1 (5/12) - Architectures (Unix)Operating Systems 1 (5/12) - Architectures (Unix)
Operating Systems 1 (5/12) - Architectures (Unix)
Peter Tröger
 
Unix.system.calls
Unix.system.callsUnix.system.calls
Unix.system.calls
GRajendra
 
An Introduction To Linux
An Introduction To LinuxAn Introduction To Linux
An Introduction To Linux
Ishan A B Ambanwela
 
Embedded system - embedded system programming
Embedded system - embedded system programmingEmbedded system - embedded system programming
Embedded system - embedded system programming
Vibrant Technologies & Computers
 
Android memory analysis Debug slides.pdf
Android memory analysis Debug slides.pdfAndroid memory analysis Debug slides.pdf
Android memory analysis Debug slides.pdf
VishalKumarJha10
 

Similar to Char Drivers And Debugging Techniques (20)

Writing Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linux
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
 
Ganesh naik linux_kernel_internals
Ganesh naik linux_kernel_internalsGanesh naik linux_kernel_internals
Ganesh naik linux_kernel_internals
 
Ganesh naik linux_kernel_internals
Ganesh naik linux_kernel_internalsGanesh naik linux_kernel_internals
Ganesh naik linux_kernel_internals
 
The TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux KernelThe TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux Kernel
 
Basic Linux Internals
Basic Linux InternalsBasic Linux Internals
Basic Linux Internals
 
Linux
LinuxLinux
Linux
 
Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)
 
Linux io introduction-fudcon-2015-with-demo-slides
Linux io introduction-fudcon-2015-with-demo-slidesLinux io introduction-fudcon-2015-with-demo-slides
Linux io introduction-fudcon-2015-with-demo-slides
 
Lamp
LampLamp
Lamp
 
Lamp1
Lamp1Lamp1
Lamp1
 
Lamp1
Lamp1Lamp1
Lamp1
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - Processes
 
kkMemory management
kkMemory managementkkMemory management
kkMemory management
 
Auditing the Opensource Kernels
Auditing the Opensource KernelsAuditing the Opensource Kernels
Auditing the Opensource Kernels
 
Operating Systems 1 (5/12) - Architectures (Unix)
Operating Systems 1 (5/12) - Architectures (Unix)Operating Systems 1 (5/12) - Architectures (Unix)
Operating Systems 1 (5/12) - Architectures (Unix)
 
Unix.system.calls
Unix.system.callsUnix.system.calls
Unix.system.calls
 
An Introduction To Linux
An Introduction To LinuxAn Introduction To Linux
An Introduction To Linux
 
Embedded system - embedded system programming
Embedded system - embedded system programmingEmbedded system - embedded system programming
Embedded system - embedded system programming
 
Android memory analysis Debug slides.pdf
Android memory analysis Debug slides.pdfAndroid memory analysis Debug slides.pdf
Android memory analysis Debug slides.pdf
 

Recently uploaded

The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 

Recently uploaded (20)

The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 

Char Drivers And Debugging Techniques

  • 1. Unit-5 CHAR DRIVERS AND DEBUGGING TECHNIQUES
  • 2. • The Design of Scull: – Scull stands for Simple Character Utility for Loading Localities. – It is Not hardware dependent – Just acts on some memory allocated from the kernel – It uses part of the memory to simulate the device – It shows the interfaces between the kernel and the character driver – It shows the actual installation and startup.
  • 3. • The Design of Scull: – There are several types of scull devices – scull[0-3] • This type has four members, scull0 , scull1 , scull2 and scull3 . • Each encapsulates a memory area that is global and persistent . • Global means that all opens of these devices share the same data. • Persistent means that data isn't lost across closes and reopens. – scullpipe[0-3] • Four devices that act like pipes between a reader and writer process. • Blocking and non-blocking reads and writes are illustrated here.
  • 4. • The Design of Scull: – There are several types of scull devices – Scullsingle:allows only one process at a time to use the driver, – scullpriv:private to each virtual console – sculluid :Can be opened multiple times by one user at a time – scullwuid:Blocks open if another user is locking the device
  • 5. Major and Minor Numbers • Char devices are accessed through names in the file system – Special files/nodes in /dev folder >cd /dev >ls –l crw------- 1 root root 5, 1 Apr 12 16:50 console brw-rw---- 1 root disk 8, 0 Apr 12 16:50 sda brw-rw---- 1 root disk 8, 1 Apr 12 16:50 sda1 Char drivers are identified by a “c” Block drivers are identified by a “b” Major numbers Minor numbers
  • 6. Major and Minor Numbers • Major number identifies the driver associated with the device – /dev/sda and /dev/sda1 are managed by driver 8 • Minor number is used by the kernel to determine which device is being referred to
  • 7. The Internal Representation of Device Numbers • dev_t type is used to hold device numbers— both the major and minor parts, defined in <linux/types.h> • Macros defined in <linux/kdev_t.h> – 12 bits for the major number • Use MAJOR(dev_t dev) to obtain the major number – 20 bits for the minor number • Use MINOR(dev_t dev) to obtain the minor number – Use MKDEV(int major, int minor) to turn them into a dev_t
  • 8. Allocating and Freeing Device Numbers • To obtain one or more device numbers, use int register_chrdev_region(dev_t first, unsigned int count, char *name); – first • Beginning device number • Minor device number is often 0 – count • Requested number of contiguous device numbers – name • Name of the device
  • 9. Allocating and Freeing Device Numbers • Kernel can allocate a major number on the fly(dynamic allocation) int alloc_chrdev_region(dev_t *dev, unsigned int firstminor, unsigned int count, char *name); – dev • Output-only parameter that holds the first number on success – firstminor • Requested first minor number • Often 0
  • 10. Allocating and Freeing Device Numbers • To free your device numbers, use int unregister_chrdev_region(dev_t first, unsigned int count);
  • 11. Some Important Data Structures • file_operations • file • inode • These are Defined in <linux/fs.h>
  • 12. File Operations struct file_operations { struct module *owner; /* pointer to the module that owns the structure prevents the module from being unloaded while in use */ loff_t (*llseek) (struct file *, loff_t, int); /* change the current position in a file returns a 64-bit offset, or a negative value on errors */ ssize_t (*read) (struct file *, char __user *, size_t, loff_t *); /* returns the number of bytes read, or a negative value on errors */ ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t); /* might return before a read completes */
  • 13. File Operations ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *); /* returns the number of written bytes, or a negative value on error */ ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t); int (*readdir) (struct file *, void *, filldir_t); /* this function pointer should be NULL for devices */ unsigned int (*poll) (struct file *, struct poll_table_struct *); /* query whether a read or write to file descriptors would block */ int (*unlocked_ioctl) (struct file *, unsigned int, unsigned long); int (*compat_ioctl) (struct file *, unsigned int, unsigned long); /* provides a way to issue device-specific commands (e.g., formatting) */
  • 14. File Operations int (*mmap) (struct file *, struct vm_area_struct *); /* map a device memory to a process’s address */ int (*open) (struct inode *, struct file *); /* first operation performed on the device file if not defined, opening always succeeds, but driver is not notified */ int (*flush) (struct file *, fl_owner_t id); /* invoked when a process closes its copy of a file descriptor for a device not to be confused with fsync */ int (*release) (struct inode *, struct file *); /* invoked when the file structure is being released */ int (*fsync) (struct file *, loff_t, loff_t, int datasync); /* flush pending data for a file */ int (*aio_fsync) (struct kiocb *, int datasync); /* asynchronous version of fsync */ int (*fasync) (int, struct file *, int); /* notifies the device of a change in its FASYNC flag */
  • 15. File Operations int (*flock) (struct file *, int, struct file_lock *); /* file locking for regular files, almost never implemented by device drivers */ ssize_t (*splice_read) (struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int); ssize_t (*splice_write) (struct pipe_inode_info *, file *, loff_t *, size_t, unsigned int); /* implement gather/scatter read and write operations */ ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int); /* called by kernel to send data, one page at a time usually not used by device drivers */
  • 16. File Operations unsigned long (*get_unmapped_area) (struct file *, unsigned long, unsigned long, unsigned long, unsigned long); /* finds a location in the process’s memory to map in a memory segment on the underlying device used to enforce alignment requirements most drivers do not use this function */ int (*check_flags) (int); /* allows a module to check flags passed to an fcntl call */ int (*setlease) (struct file *, long, struct file_lock *); /* Establishes a lease on a file. Most drivers do not use this function */ long (*fallocate) (struct file *file, int mode, loff_t offset, loff_t len) /* Guarantees reserved space on storage for a file. Most drivers do not use this function */ };
  • 17. The File Structure • struct file – Nothing to do with the FILE pointers • Defined in the C Library – Represents an open file • A pointer to file is often called filp
  • 18. The File Structure • Some important fields – fmode_t f_mode; • Identifies the file as either readable or writable – loff_t f_pos; • Current reading/writing position (64-bits) – unsigned int f_flags; • File flags, such as O_RDONLY, O_NONBLOCK, O_SYNC
  • 19. The File Structure • Some important fields – struct file_operations *f_op; • Operations associated with the file • Dynamically replaceable pointer – Equivalent of method overriding in OO programming – void *private_data; • Can be used to store additional data structures • Needs to be freed during the release method
  • 20. The File Structure • Some important fields – struct dentry *f_dentry; • Directory entry associated with the file • Used to access the inode data structure – filp->f_dentry->d_inode
  • 21. The i-node Structure • There can be numerous file structures (multiple open descriptors) for a single file • Only one inode structure per file
  • 22. The i-node Structure • Some important fields – dev_t i_rdev; • Contains device number • For portability, use the following macros – unsigned int iminor(struct inode *inode); – unsigned int imajor(struct inode *inode); – struct cdev *i_cdev; • Contains a pointer to the data structure that refers to a char device file
  • 23. Char Device Registration • Need to allocate struct cdev to represent char devices #include <linux/cdev.h> /* first way */ struct cdev *my_cdev = cdev_alloc(); my_cdev->ops = &my_fops; /* second way, for embedded cdev structure, call this function – (see scull driver) */ void cdev_init(struct cdev *cdev, struct file_operations *fops);
  • 24. Char Device Registration • Either way – Need to initialize file_operations and set owner to THIS_MODULE • Inform the kernel by calling int cdev_add(struct cdev *dev, dev_t num, unsigned int count); – num: first device number – count: number of device numbers • Remove a char device, call this function void cdev_del(struct cdev *dev);
  • 25. The open Method • In most drivers, open should – Check for device-specific errors – Initialize the device (if opened for the first time) – Update the f_op pointer, as needed – Allocate and fill data structure in filp->private_data
  • 26. The release Method • Deallocate filp->private_data • Shut down the device on last close – One release call per open • Potentially multiple close calls per open due to fork/dup • scull has no hardware to shut down int scull_release(struct inode *inode, struct file *filp) { return 0; }
  • 27. scull’s Memory Usage • Dynamically allocated • #include <linux/slab.h> – void *kmalloc(size_t size, int flags); • Allocate size bytes of memory • For now, always use GFP_KERNEL • Return a pointer to the allocated memory, or NULL if the allocation fails – void kfree(void *ptr);
  • 28. read and write ssize_t (*read) (struct file *filp, char __user *buff, size_t count, loff_t *offp); ssize_t (*write) (struct file *filp, const char __user *buff, size_t count, loff_t *offp); – filp: file pointer – buff: a user-space pointer • May not be valid in kernel mode • Might be swapped out • Could be malicious – count: size of requested transfer – offp: file position pointer
  • 29. readv and writev • Vector versions of read and write – Take an array of structures • Each contains a pointer to a buffer and a length
  • 30. • Debugging Support in the Kernel: • The following are the list of configuration options that should be enabled for kernels used for development • -->CONFIG_DEBUG_KERNEL This option just makes other debugging options available; it should be turned on but does not, by itself, enable any features. • -->CONFIG_DEBUG_SLAB This crucial option turns on several types of checks in the kernel memory allocation functions • -->CONFIG_PROFILING This option is found under "Profiling support." Profiling is normally used for system performance tuning,
  • 31. • Debugging with printk: • There following are possible loglevel strings, defined in the header <linux/kernel.h>; • we list them in order of decreasing severity: • KERN_EMERG Used for emergency messages, usually those that precede a crash. • KERN_ALERT A situation requiring immediate action. • KERN_CRIT • Critical conditions, often related to serious hardware or software failures. • KERN_ERR Used to report error conditions; device drivers often use KERN_ERR to report hardware difficulties.
  • 32. • Debugging by Watching: • ---------------------- 1.The strace command is a powerful tool that shows all the system calls issued by a userspace program. 2.strace receives information from the kernel itself. • Debugging by querying: • ---------------------- 1./proc--Proc file system (procfs) is virtual file system created on fly when system boots and is dissolved at time of system shut down. It contains the useful information about the processes that are currently running, it is regarded as control and information centre for kernel. The proc file system also provides communication medium between kernel space and user space. It is the best way to get relevant information is to query the system when you need the information, instead of continually producing data. 2.ioctl ------- ioctl (an abbreviation of input/output control) is a system call for device- specific input/output operations and other operations which cannot be expressed by regular system calls. It takes a parameter specifying a request code; the effect of a call depends completely on the request code. Request codes are often device-specific. For instance, a CD-ROM device driver which can instruct a physical device to eject a disc would provide an ioctl request code to do that.
  • 33. Debugging System Faults • Oops message: • An “Oops” is what the kernel throws at us when it finds something faulty, or an exception, in the kernel code. It’s somewhat like the segfaults of user-space. An Oops dumps its message on the console; it contains the processor status and the CPU registers of when the fault occurred. The offending process that triggered this Oops gets killed without releasing locks or cleaning up structures. The system may not even resume its normal operations sometimes; this is called an unstable state. • System hangs: • Although most bugs in kernel code end up as oops messages, sometimes they can completely hang the system. If the system hangs, no message is printed.
  • 34. Debuggers and Related Tools • Using gdb: • GDB basically helps us to do four main things to catch flaws in the source code. • Start the program, specifying arguments that may affect the general behavior. • Stop the program on specified conditions. • Examine the crash or when program was stopped. • Change the code and to experiment with the modified code instantaneously. • Kdb is simplistic shell-style interface which you can use on a system console with a keyboard or serial console. You can use it to inspect memory, registers, process lists, dmesg, and even set breakpoints to stop in a certain location. Kdb is not a source level debugger, although you can set breakpoints and execute some basic kernel run control. Kdb is mainly aimed at doing some analysis to aid in development or diagnosing kernel problems
  • 35. • Debuggers and Related Tools: • ---------------------------- • Kgdb is intended to be used as a source level debugger for the Linux kernel. It is used along with gdb to debug a Linux kernel. The expectation is that gdb can be used to “break in” to the kernel to inspect memory, variables and look through call stack information similar to the way an application developer would use gdb to debug an application. It is possible to place breakpoints in kernel code and perform some limited execution stepping. • User-Mode Linux (UML) is an interesting concept. It is structured as a separate port of the Linux kernel with its own arch/um subdirectory. It does not run on a new type of hardware, however; instead, it runs on a virtual machine implemented on the Linux system call interface. Thus, UML allows the Linux kernel to run as a separate, user-mode process on a Linux system. • The Linux Trace Toolkit (LTT) is a kernel patch and a set of related utilities that allow the tracing of events in the kernel. The trace includes timing information and can create a reasonably complete picture of what happened over a given period of time.