Device Drivers, Part 8: Accessing x86-Specific I/O-Mapped Hardware

Hardware access kit

This article, which is part of the series on Linux device drivers, continues the discussion on accessing hardware in Linux.

The second day in the Linux device drivers’ laboratory was expected to be quite different from the typical software-oriented class. Apart from accessing and programming architecture-specific I/O mapped hardware in x86, it had a lot to offer first-timers with regard to reading hardware device manuals (commonly called data sheets) and how to understand them to write device drivers. In contrast, the previous session about generic architecture-transparent hardware interfacing was about mapping and accessing memory-mapped devices in Linux without any device-specific details.

x86-specific hardware interfacing

Unlike most other architectures, x86 has an additional hardware accessing mechanism, through direct I/O mapping. It is a direct 16-bit addressing scheme, and doesn’t need mapping to a virtual address for access. These addresses are referred to as port addresses, or ports. Since this is an additional access mechanism, it has an additional set of x86 (assembly/machine code) instructions. And yes, there are the input instructions inb, inw, and inl for reading an 8-bit byte, a 16-bit word, and a 32-bit long word, respectively, from I/O mapped devices, through ports. The corresponding output instructions are outb, outw and outl, respectively. The equivalent C functions/macros (available through the header <asm/io.h>) are as follows:

u8 inb(unsigned long port);
u16 inw(unsigned long port);
u32 inl(unsigned long port);
void outb(u8 value, unsigned long port);
void outw(u16 value, unsigned long port);
void outl(u32 value, unsigned long port);

The basic question that may arise relates to which devices are I/O mapped and what the port addresses of these devices are. The answer is pretty simple. As per x86-standard, all these devices and their mappings are predefined. Figure 1 shows a snippet of these mappings through the kernel window /proc/ioports. The listing includes predefined DMA, the timer and RTC, apart from serial, parallel and PCI bus interfaces, to name a few.

x86-specific I/O ports

Figure 1: x86-specific I/O ports

Simplest: serial port on x86

For example, the first serial port is always I/O mapped from 0x3F8 to 0x3FF. But what does this mapping mean? What do we do with this? How does it help us to use the serial port? That is where a data-sheet of the corresponding device needs to be looked up.

A serial port is controlled by the serial controller device, commonly known as an UART (Universal Asynchronous Receiver/Transmitter) or at times a USART (Universal Synchronous/Asynchronous Receiver/Transmitter). On PCs, the typical UART used is the PC16550D. The data-sheet for this [PDF] can be downloaded as part of the self-extracting package [BIN file] used for the Linux device driver kit, available at lddk.esrijan.com.

Generally speaking, from where, and how, does one get these device data sheets? Typically, an online search with the corresponding device number should yield their data-sheet links. Then, how does one get the device number? Simple… by having a look at the device. If it is inside a desktop, open it up and check it out. Yes, this is the least you may have to do to get going with the hardware, in order to write device drivers. Assuming all this has been done, it is time to peep into the data sheet of the PC16550D UART.

Device driver writers need to understand the details of the registers of the device, as it is these registers that writers need to program, to use the device. Page 14 of the data sheet (also shown in Figure 2) shows the complete table of all the twelve 8-bit registers present in the UART PC16550D.

Registers of UART PC16550D

Figure 2: Registers of UART PC16550D

Each of the eight rows corresponds to the respective bit of the registers. Also, note that the register addresses start from 0 and goes up to 7. The interesting thing about this is that a data sheet always gives the register offsets, which then needs to be added to the base address of the device, to get the actual register addresses.

Who decides the base address and where is it obtained from? Base addresses are typically board/platform specific, unless they are dynamically configurable like in the case of PCI devices. In this case, i.e., a serial device on x86, it is dictated by the x86 architecture—and that precisely was the starting serial port address mentioned above—0x3F8.

Thus, the eight register offsets, 0 to 7, exactly map to the eight port addresses 0x3F8 to 0x3FF. So, these are the actual addresses to be read or written, for reading or writing the corresponding serial registers, to achieve the desired serial operations, as per the register descriptions.

All the serial register offsets and the register bit masks are defined in the header <linux/serial_reg.h>. So, rather than hard-coding these values from the data sheet, the corresponding macros could be used instead. All the following code uses these macros, along with the following:

#define SERIAL_PORT_BASE 0x3F8

Operating on the device registers
To summarise the decoding of the PC16550D UART data sheet, here are a few examples of how to do read and write operations of the serial registers and their bits.

Reading and writing the ‘Line Control Register (LCR)’:

u8 val;

val = inb(SERIAL_PORT_BASE + UART_LCR /* 3 */);
outb(val, SERIAL_PORT_BASE + UART_LCR /* 3 */);

Setting and clearing the ‘Divisor Latch Access Bit (DLAB)’ in LCR:

u8 val;

val = inb(SERIAL_PORT_BASE + UART_LCR /* 3 */);

/* Setting DLAB */
val |= UART_LCR_DLAB /* 0x80 */;
outb(val, SERIAL_PORT_BASE + UART_LCR /* 3 */);

/* Clearing DLAB */
val &= ~UART_LCR_DLAB /* 0x80 */;
outb(val, SERIAL_PORT_BASE + UART_LCR /* 3 */);

Reading and writing the ‘Divisor Latch’:

u8 dlab;
u16 val;
dlab = inb(SERIAL_PORT_BASE + UART_LCR);
dlab |= UART_LCR_DLAB; // Setting DLAB to access Divisor Latch
outb(dlab, SERIAL_PORT_BASE + UART_LCR);

val = inw(SERIAL_PORT_BASE + UART_DLL /* 0 */);
outw(val, SERIAL_PORT_BASE + UART_DLL /* 0 */);

Blinking an LED

To get a real experience of low-level hardware access and Linux device drivers, the best way would be to play with the Linux device driver kit (LDDK) mentioned above. However, just for a feel of low-level hardware access, a blinking light emitting diode (LED) may be tried, as follows:

Connect a light-emitting diode (LED) with a 330 ohm resistor in series across Pin 3 (Tx) and Pin 5 (Gnd) of the DB9 connector of your PC.

Pull up and down the transmit (Tx) line with a 500 ms delay, by loading and unloading the blink_led driver, using insmod blink_led.ko and rmmod blink_led, respectively.

Driver file blink_led.ko can be created from its source file blink_led.c by running make with the usual driver Makefile. Given below is the complete blink_led.c:

#include <linux/module.h>
#include <linux/version.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <asm/io.h>

#include <linux/serial_reg.h>

#define SERIAL_PORT_BASE 0x3F8

int __init init_module()
{
    int i;
    u8 data;

    data = inb(SERIAL_PORT_BASE + UART_LCR);
    for (i = 0; i < 5; i++)
    {
        /* Pulling the Tx line low */
        data |= UART_LCR_SBC;
        outb(data, SERIAL_PORT_BASE + UART_LCR);
        msleep(500);
        /* Defaulting the Tx line high */
        data &= ~UART_LCR_SBC;
        outb(data, SERIAL_PORT_BASE + UART_LCR);
        msleep(500);
    }
    return 0;
}

void __exit cleanup_module()
{
}

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Anil Kumar Pugalia <email_at_sarika-pugs_dot_com>");
MODULE_DESCRIPTION("Blinking LED Hack");

Looking ahead

You might have wondered why Shweta is missing from this article? She bunked all the classes! Watch out for the next article to find out why.

  • PeterHiggs

    Nice article Pugs !!! I just wonder about one thing. When you mentioned about the base address registers will be dictated by x86, is it like, after we insert the device into PCI slot, we can see the iomap with the command ioports on CLI prompt?

    • anil_pugalia

      Please read carefully. If it is *not* a PCI device, its base address (not register) will be dictated by x86 architecture, and could be obtained from x86 reference manual (or googling).

  • http://twitter.com/Vineel567 Vineel Kumar Reddy

    U really Saved my brain power …. i was banging my head for all these little bits of information to be stitched together from so many days…. thanks anil… keep it up

    • anil_pugalia

      Thanks for looking it from this angle.

  • Dev

    On my computer I dont have a DB9 connector. Will this program work if I buy a USB to DB9 adapter?(I dont think it would work but I just wanted to confirm anyway). If not then how coul I get it to work? Are there some alternatives?

    • http://twitter.com/anil_pugalia Anil Pugalia

      As you said right, it would not work with a USB to DB9 adaptor, with the above code. Other alternative could be to use any other low level interface, and then change the above code to program that, like PCI Serial Card.

  • http://www.facebook.com/karthi.prime Karthi Prime

    I have been following all of your tutorial series. I like your style of explaining things. Its awesome. A doubt: In the c file: blink_led.c, How these lines:
    data = inb(SERIAL_PORT_BASE + UART_LCR);
    data |= UART_LCR_SBC;
    outb(data, SERIAL_PORT_BASE + UART_LCR); – pulling the tx line low?

    • http://twitter.com/anil_pugalia Anil Pugalia

      For that, you have to use the sysfs apis to expose your interface as a file under /sys. An beautiful example of that is the misc drivers. Check out drivers in the kernel source under drivers/misc/ folder

  • Charan

    Hi Anil,
    This is very nice article on i/o port accessing.But one thing is that, I think the module might not able to access the some i/o ports.So the first thing is that we have to check whether the i/o port is accessible by using the interface request_region() interface function .Correct me if i am wrong.
    And i have one basic question.Is there any way to make normal RAM memory as a i/o port memory.

    • anil_pugalia

      For first part you are correct.

      For second part, RAM memory cannot be accessed as a I/O port

  • deep

    hello sir

    i have added a line in blink_led.c-

    printk(KERN_INFO “LED BLINK”);

    but no string prints

    • anil_pugalia

      Where are you expecting the print to come? Did you check dmesg?

      • deep

        in terminal after insmod blink_led.ko

        • anil_pugalia

          That’s the problem. printk puts it in kernel’s ring buffer, not the terminal. Check it out by typing dmesg. It would be at the end of the dmesg log.

  • deep

    Hello sir
    how do we know default baud rate setting and how can we change the baud rate setting i mean which resister we should modify??

    • anil_pugalia

      Check out the Divisor Latch registers (both Low & High) and their explanations.

  • Pradeep M C

    hello sir, i am following your article and in the above blink_led.c, am a bit confused as i find no module_init() and module_exit() macros. are they not needed when the driver is being inserted and removed using the insmod and rmmod commands?

    • anil_pugalia

      Good question. I was expecting for at least someone to ask this question. Now, as you have asked, here goes the answer. init_module() & cleanup_module() are the pre-defined names for the constructor & the destructor, respectively. Hence, you do not need module_init & module_exit to translate your other function names to these pre-defined ones. Note of caution: Since kernel 2.6 onwards, if you are building the driver into the kernel, you have to define your own function names & then use module_init() & module_exit().

  • Devendra Gupta

    Dear Anil- Thanks for the wonderful article. I have also read an
    article at url
    http://www.freesoftwaremagazine.com/articles/drivers_linux
    in
    this url he made a driver for parallel port and then make an
    application to flash LEDs on parallel port, But you have written a
    similar code in the kernel space as a driver, I am confused whether the
    blinking part should come in user space application program or we should
    make driver for it as you have made.

    • anil_pugalia

      There is no one answer to it. It varies from case to case. Moreover, my purpose was to demonstrate the the hardware interfacing calls like outb, which is in kernel space in both the cases.

  • Raashid

    Is it possible to do the same using qemu, as I don’t have root permissions for insmod?

    • anil_pugalia

      But then you may not be able to access the real hardware, which is what this article is all about.

All published articles are released under Creative Commons Attribution-NonCommercial 3.0 Unported License, unless otherwise noted.
Open Source For You is powered by WordPress, which gladly sits on top of a CentOS-based LEMP stack.

Creative Commons License.