# [Linux Kernel慢慢學]Different betweeen ioctl, unlocked_ioctl and compat_ioctl

Posted by John on 2020-10-24
Words 1.4k and Reading Time 5 Minutes
Viewed Times

## 前言

(以下linux source code如果沒有特別提及版本，接以v4.1.14為主)

## ioctl是什麼?

ioctl()是撰寫driver一個很重要的接口，以字元裝置驅動(char device driver)來說，透過這個接口可以讓user來操作driver執行一些行為。

## Big Kernel Lock下的舊產物: ioctl

ioctl()在2.6版本以前是還有這個function的，例如你可以在2.5.75的fs.h中看到。但在2.6以後就被替換成unlocked_ioctl()了，為什麼呢?

ioctl() is one of the remaining parts of the kernel which runs under the Big Kernel Lock (BKL). In the past, the usage of the BKL has made it possible for long-running ioctl() methods to create long latencies for unrelated processes. Recent changes, which have made BKL-covered code preemptible, have mitigated that problem somewhat. Even so, the desire to eventually get rid of the BKL altogether suggests that ioctl() should move out from under its protection.

long (*unlocked_ioctl) (struct file *filp, unsigned int cmd, unsigned long arg);

• unlocked_ioctl()不再提供inode參數，但你仍可以透過filp->f_dentry->d_inode來取得
• unlocked_ioctl()不再使用BKL，工程師需要根據自己的需求來決定要不要加入lock的機制

• 而在2.6.36後就正式將ioctl()移除了，大家都必須透過unlocked_ioctl()來提供ioctl的接口

## 為了相容性而出現的compat_ioctl

If this method exists, it will be called (without the BKL) whenever a 32-bit process calls ioctl() on a 64-bit system. It should then do whatever is required to convert the argument to native data types and carry out the request

compat_ioctl()實際上要怎麼寫呢? 隨便找一個example code來看一下:

## 總結

• unlock_ioctl()
• compat_ioctl()

>