Global TMW:
Login  |  Register          Free Newsletter Subscription
Subscribe
Email
Print
Reprint
Learn RSS

Linux Applications Cruise With New Drivers

An introduction to Linux device drivers will help you understand how they work and how complex they can be.

David Marsh, Contributing Technical Editor -- Test & Measurement World, 4/15/2000

Related Information
A version of this article appeared in the October-November issue of Test & Measurement Europe. Download the article as a pdf.

Eighteen months ago, I examined Linux as a possible operating system (OS) for test and measurement applications.1 Since then, Linux has captured 17% of the general-server market. More significantly, commercial Linux suppliers have positioned the OS to compete head-on with Windows.

In this article, I’ll explain how to start using Linux and describe the types of device drivers it uses. And if you’re a C programmer, I’ll show you how to write some simple drivers on your own. (Future articles in T&MW will describe how to move device drivers from Windows NT to Linux.2)

Your first step is to obtain a copy of Linux. You can download a free copy over the Internet or purchase a ready-to-use package. Linux International (www.li.org ) provides a list of suppliers and sources for the free distribution. Downloads take hours of connect time, so consider buying a complete package, which can sell for as little as $30. A typical package supplies a CD-ROM containing a stable OS kernel release (currently 2.2.14), applications, utilities, development tools, and system documentation. Several books come with a CD-ROM containing Linux (see “For Further Reading”).

If you plan to use a Linux PC to access online resources, you will save time by starting with an Internet-ready Windows PC. And if you have enough disk space on a Windows-based PC to accommodate Linux and Windows, consider a dual-boot Windows/Linux installation that will let you use Linux or Windows on the same PC. You’ll need at least 16 Mbytes of RAM and an extra 1 Gbyte on your hard disk for a dual installation. Be sure to back up your Windows system before you take the dual-boot path!

In the past year or so, Linux vendors have improved the procedure for installing the OS, but steps vary from supplier to supplier. I used Red Hat’s Linux (version 6.1) (www.redhat.com) for this article, but packages from other sources—commercial and free—offer equivalent operations. Provided you know what hardware your PC contains, you should have Linux running in under two hours3. My Red Hat installation that included “everything”—all of the applications and ancillary programs—took 3.5 Gbytes of disk space, but you can get by with about 1 Gbyte for a basic installation. You can add applications later, as you need them.

After you have Linux installed on a PC, familiarize yourself with the GUI and the command-line interface. The latest GUIs from KDE (www.kde.org ) and Gnome (www.gnome.org)—usually included with Linux packages—let you choose the type of screen style and tools (Fig. 1) available on the display. Before you install an application, such as a word processor, ensure it works with your choice of GUI. By selecting “everything” during installation (as I did), you’ll load both the KDE and the Gnome GUI, and you can choose either as your desktop when you log in. Both GUIs provide four windows that you can move among during a session. The differences between the two GUIs are slight and have more to do with aesthetics than function.

Navigation through Linux’s directories and files relies on the command-line screen, in which you’ll have to get used to forward-slash (/) path direction and case-sensitive filenames. Then there’s file security: File permissions apply to directories and individual files at three levels (user, group, and others). You may copy a file only to find you can’t do anything with it; attempts to open or view it fail and you may not get a helpful error message. Pay careful attention to the permission levels you set so you can access the system resources. If you’re a hacker, you can move through this maze by using a GUI-based file manager such as kfmsu that supports root-level control; kfmsu installs as part of the KDE software.

TMW00_042F1Fig1.gif (24055 bytes)
Figure 1. This screen photo shows a LabView data-acquisition window as it appears on the KDE GUI desktop. (Courtesy of National Instruments.)
 Take Care with Root Privileges
You normally log in at user level with the password you created for your user account, but you log in at root level (sometimes called super user level) when you need to perform privileged functions, such as loading device drivers. At this level, you can modify directory and file permissions—and also wreak havoc if you’re not careful! Log in at root level only as necessary; as a root user, you could easily make a wrong move and ruin your installation.

Producing device drivers or utilities for your system means working within a software-development environment. In the Linux realm, C is the language of choice, so you’ll need a C compiler, a text editor, and C libraries. You can set them up using the standard package installer that comes with Linux.

Creating a simple program takes three steps: writing the program, compiling it, and running it. Well, maybe a fourth step, too—debugging it. Listing 1 shows an example of a simple program. After compilation, it will display “hello world” on the PC’s screen. (Linux comes with the C compiler gcc, which you can access from the command line.) Unlike Basic, C provides no built-in I/O operations. The printf statement represents a function call to a library of I/O operations. The C program invokes the ANSI-standard I/O function library through the #include stdio.h command. C supports many other standard libraries and libraries from third parties.

Listing 1.
#include <STDIO.H>   
/*includes C's standard input-output library functions*/
main()    /*entry point to program*/
{ /*actions lie between curly braces*/
printf("hello world ");    /*call printf function, display message*/
/*and force a new line*/
}    /*end of actions*/

ANSI C provides library functions that let programs control standard devices such as disk drives, the keyboard, and the display, as well as other devices that contain I/O ports. Actually, the OS controls the devices; a program simply uses high-level commands to ask the OS to perform an I/O operation by making calls to functions. To control hardware other than that built into a PC, you don’t want to have to control individual bits at I/O ports. Instead, you want a device driver to connect your software and hardware. In effect, the driver isolates you from the hardware details.4 Before writing a driver, search the Web to see if someone has one you can use. The Free University of Berlin offers useful information at the Linux Lab Project (www.llp.fu-berlin.de ), a site dedicated to software for measurement and control applications. Vendors may also provide Linux driver software for their products.

Drivers Work in Two Memory Spaces
Under Linux, device drivers can operate out of one of two sections of memory: kernel space (a protected area set aside by Linux for its own use), or user space (memory that Linux assigns to a user). Kernel-space drivers have the most power, but they’re difficult to understand and to develop. User-space kernels are easier to develop, and they can draw on many functions and procedures in C libraries. They also have limits as to what they can do with system hardware. Drivers that run in kernel space have several advantages over those in user space. They’re fast because they don’t invoke context switches, they have direct access to the interrupts, they support block-transfer devices, they’re available until you unload them, and if properly written, they’re re-entrant. Linux loads kernel-space drivers and retains them in memory until you specifically unload them or until you shut down the computer. Properly written kernel-space drivers make devices look like a file. A character-like device (called a char), such as an I/O port, returns a single byte or word: A block device, such as the buffer on a data-acquisition card, returns multiple bytes. You mount either device type as a file system node that the kernel manages, and the char/block difference becomes transparent to users.

On the other hand, writing kernel-space drivers calls for advanced C programming skills. To write them properly requires knowledge of arcane issues such as kernel headers, kernel-dependent version control, memory management, and resource control. And if your kernel-space driver doesn’t work properly, it can crash your system—requiring a reboot. Debugging a kernel-space driver causes headaches and requires specialized tools. Debugging at this level goes beyond the scope of this article, but you’ll find more information and sample source code in The Linux Kernel Module Programming Guide. Also, the book Linux Device Drivers provides more information about kernel-space drivers and includes examples you can download. (See “For Further Reading” to locate these items.)

If you’re just getting started writing device drivers or if you’re developing prototype hardware, keep your drivers in user-space memory. A program that crashes in Linux’s user space won’t halt the PC, unless you’re trying to control hardware that goes haywire and crashes the PC on its own. Mitch Bunnell, chief technical officer at Lynx Real-Time Systems (San Jose, CA), says, “There are limits on programs in user space, such as restricted access to the PC’s interrupts, but it’s still better to develop at this level.” Bunnell notes user-space device access requires a context switch, so if Linux has swapped your device driver from user space to disk, response time suffers; Linux must retrieve the driver before it can use it. During a swap, the Linux kernel can “move” the contents of memory into a swap space or onto a hard disk.

TMW00_042F1fig2.gif (23326 bytes)
Figure 2. The pin connections and register maps for a standard PC parallel port show the logic of the connections between internal PC registers and the pins. This is not a schematic of the port circuitry. The port is not enabled for ECP or EPP operation.
Because user-space drivers run as a single thread, they serialize read/write accesses and make simultaneous I/O accesses difficult. “To provide reasonable simultaneous access,” Bunnell says, “user-level drivers must not block or wait on other tasks. These factors aren’t an issue with a single device, but they become a huge problem for systems that include many devices such as those in a VXIbus system.” In contrast, correctly implemented kernel-space drivers are re-entrant, so even if you lock a process while waiting for an external event, another device can use the corresponding driver without compromising data integrity. If possible, commercial drivers avoid running from user space.

Drivers Use C Libraries
Developing device-drivers in user space also lets you use all the C libraries. Kernel-space drivers can only access the smaller number of functions available at the kernel level. User-space operations let you link in functions from many sources, so you can extend existing libraries. You can’t do that in the kernel space. And in user space you can use conventional debuggers that give you almost complete control over your code. A user-space driver works like other programs except it controls hardware. You call it through a function call, and it terminates when it finishes its tasks.

It’s fairly easy to cut your device-driver teeth in user-space, where you can safely read from and write to I/O ports. Because all PCs come with a parallel printer port, you could write simple programs to toggle output pins and read input pins. The short program in Listing 2 toggles the LSB at pin 2 on the printer port. The diagram in Figure 2 isn’t a schematic for a parallel port, but it shows the logic for a traditional PC port; that is, one not enabled for ECP or EPP operations. Before you use the parallel port, check its BIOS settings and enable normal operation, not ECP or EPP operations. You can find out more about how to use I/O ports in the “HOWTOs” documents at www.linuxdoc.org . Also, the books Serial Port Complete and Parallel Port Complete supply information about I/O operations (see “For Further Reading”).

Listing 2.
#include <UNISTD.H>
#include <ASM io.h>

/*This program will toggle the lowest bit of a printer port at
a one second duty cycle under Linux. Courtesy Mitch Bunnell at
Lynx Real-Time Systems, Inc. */
#define DATA_PORT 0x378               /* printer data port I/O address */
main()
{
int x;
ioperm(DATA_PORT, 1, 1);              /*You must be logged in as a root user*/
                                     /*so the ioperm function can get */
                                     /*permission to access the I/O ports */
                                     /*from user space. */
for (;;) {
outb(1, DATA_PORT);                   /* set 8-bit output port to 1 */
sleep(1);
outb(0, DATA_PORT);
sleep(1);
x = inb(DATA_PORT);                   /* read port */
}
}

Although Listing 2 includes a command to read data from the port, the driver software does not use this value, x. You could assign a common variable to the driver routine and use it in the calling software to obtain the input value. Of course you need a real circuit at the input port—even switches and resistors to ground and +5 V—before you’ll get useful data from the input port.

When you program a device driver to run in user space, you don’t have to worry about memory allocation because the Linux kernel allocates it for your application. And unlike kernel-space memory, user-space memory is “swappable.” But when an application must call in programs from a disk, response time suffers. Disadvantages of user-space device drivers include their requirement for root-level authorization for privileged operations such as direct memory and I/O port accesses. Due to the way Linux implements security, you’ll have to log in at the root level and configure the resources you need.

To contrast a simple user-space C-language driver with a kernel-space driver, I wrote a simple “hello world” driver to work in kernel-space memory (Listing 3). Because a kernel-space driver, technically called a module, can’t link with standard C libraries, you should never declare any of the usual file headers such as stdio.h. Also, kernel-level drivers don’t contain a main() program entry point. Testing this driver requires using the Linux insmod and rmmod commands at the command line. The insmod command registers the module’s capabilities with the Linux kernel and the rmmod command removes and “cleans up” the driver’s registration. Execution of the final print statement in the example simply confirms that the module got terminated properly.

Listing 3.
#define MODULE                 /*must define before including linux/module.h*/
#include <LINUX module.h>     /*includes module library functions*/

int init_module(void)         /*registers module with kernel*/

{
printk("hello world ");      /*call kernel-level print function*/
    return 0;                  /*return an OK flag to kernel*/
}

void cleanup_module(void)     /*undoes init_module's kernel registration*/

{
    printk("bye ");           /*print an exit message*/
}

I had to have root privileges (the highest privilege) to run the module because it operates in kernel space. So after I logged in as a root user—with my password—I typed /sbin/
insmod hello_k. The graphical environment automatically directs the “hello world” output to the /var/ logs/messages file that records kernel-level actions. A built-in feature of the Linux graphical environment directs this type of output to a log file instead of to the screen. Communications between applications and kernel-space drivers use file-like operations, but the mechanisms of setting up, calling, and terminating routines goes beyond the scope of this article.

Drivers make devices look to software like file systems. So calling a kernel-level driver from user space is the job of file operations. Setting up a kernel-space driver so an application can call it requires steps that identify the driver to the system and to other applications. You also must establish the file operations—read, write, and close—that you want the driver to perform. And finally, you must add your driver to Linux’s file-operations table so that application programs can treat the driver as if it controls a file-oriented device, such as a disk drive. You can determine which kernel drivers, or modules, Linux has loaded by typing cat/proc/modules at the command line. The resulting list shows active modules along with a usage count.

To remove my driver from kernel space, I typed /sbin/rmmod hello_k. The kernel placed the driver-exit message “bye” in the system’s log file. The driver-registration process is awkward compared to the ease with which you can register DLLs using tools in Windows development environments. New tools are starting to appear, however, such as the Lynx open development environment for Red Hat Linux. For more detail on Linux modules, see “The Linux Kernel Module Programming Guide” and Linux Device Drivers (see “For Further Reading”).

In all likelihood, you won’t write your own drivers, but now you can better appreciate how drivers exist in Linux and the capabilities they can provide and limitations they have. And Linux isn’t standing still. You have to prepare for the changes that accompany Linux kernel upgrades. Those changes involve implementation of new features and new methods of working with Linux. Linux’s creator, Linus Torvalds, controls kernel releases, but there’s no guarantee of backward compatibility with earlier versions. Unlike users of many commercial operating systems, the Linux community subscribes to the “onward and upward” view that minimizes constraints and maximizes performance. But that approach demands more flexibility from you than when you align yourself with Windows. T&MW

ACKNOWLEDGEMENTS
The author would like to thank the teams at Lynx Real-Time Systems (San Jose, CA) and at National Instruments (Austin, TX) for their help in preparing this article.

FOOTNOTES

1. Marsh, David, “Linux: A Worthy OS for Real Applications ,” Test & Measurement World, October 15, 1998. pp. 18–24.

2. The May and June issues of Test & Measurement World will contain a two-part article that describes one company’s experiences moving its drivers to Linux. The article will offer pointers on how you can do the same.

3. “David’s Install.log,”   

4. Petrov, Todor, “Get Direct I/O Control with Linux ,” Test & Measurement World, April 15, 1999. pp. 7–11.

FOR FURTHER READING

Axelson, Jan, Parallel Port Complete, Lakeview Research, Madison, WI, 1996. (Read the TMW Review)

Axelson, Jan, Serial Port Complete, Lakeview Research, Madison, WI, 1998. (Read the TMW Review)

“HOWTOs,” www.linuxdoc.org/docs.html#howto.   

“The Linux Kernel Module Programming Guide,” www.linuxdoc.org/docs.html#guide.  

McCarty, Bill, Learning Red Hat Linux, O’Reilly & Associates, Sebastopol, CA, 1999. (Includes Red Hat Linux on CD-ROM.)

Petersen, Richard, Linux: The Complete Reference, 3rd ed., Osborne/McGraw-Hill, Berkeley, CA, 1999. (Includes Red Hat Linux 6.0 and Caldera OpenLinux 2.2 on CD-ROM.)

Rubini, Alessandro, Linux Device Drivers, O’Reilly & Associates, Sebastopol, CA, 1998.

Saikkonen, Riku, “Linux I/O Port Programming Mini-Howto,” www.linuxdoc.org/HOWTO/mini/IO-Port-Programming

Siever, Ellen, Linux in a Nutshell, 2nd ed., O’Reilly & Associates, Sebastopol, CA, 1999.

Welsh, Matt, M.K. Dalheimer, and Lar Kaufamn, Running Linux, 3rd ed., O’Reilly & Associates, Sebastopol, CA, 1999.

 David Marsh is a freelance writer with more than 20 years of experience in the electronics industry. He also works as a contributing editor for EDN magazine. E-mail: forncett@compuserve.com.

David's Install.log
Red Hat's Linux (version 6.1) offers a GUI-based installer option and an automated installation option. I didn't have those options 18 months ago when I first investigated Linux for T&MW. You might try the GUI installer first to uncover any hardware incompatibilities, but I like the text-based installer because it provides far more control. Also note that the text-based installer includes an "expert" option that you may need later if the installer doesn't recognize your hardware. The expert option lets you define pretty much everything in your PC instead of having the software make safe, but sometimes less-than-ideal, assumptions.

After the opening "welcome" message appears, you can choose from many installation options. I recommend you choose the "custom" installation because it provides more flexibility than the other choices. The default modes can build a system that's unusable; for example it will set up a 640x480-resolution display with a 60-Hz-refresh rate, even if your PC has a 21 in. monitor that can run at 1152x864 and 70 Hz. Experience suggests you should prepare for more than one installation attempt. If you initially make inappropriate selections, you may find it easier to re-install Linux than to research how to reconfigure your settings from within Linux. If you're determined to reconfigure from within Linux, become familiar with the linuxconf and setuptool utilities.

If you selected a "workstation" installation, the installer offers a choice of manual or automatic partitioning. A "custom" installation requires that you set partitions manually. A simple partitioning scheme comprises boot (/boot), root (/), user (/usr), and swap partitions.

You don't explicitly name the swap partition, but choose "Linux swap" rather than the default "Linux native" type. The Red Hat handbook recommends a boot partition of 16 Mbytes, but that's excessive. The files in my root partition occupy 3.5 Mbytes. The swap partition should equal the quantity of installed RAM up to a maximum of 128 Mbytes--the largest swap size Linux can handle. The user partition conventionally mounts as a read-only partition. It's where installers place most applications, libraries, and utilities. If you set a minimum partition size and check the corresponding "grow-to-fit" box, the partition will reserve all unused disk space. If you enable "grow-to-fit" for more than one partition, they will compete and dynamically resize themselves.

The boot partition needs to occur at the start of the first hard disk and cannot span the traditional 1023-cylinder DOS disk limit; check your installation documentation for restrictions. If you're planning a dual-boot system, the LILO ("Linux Loader") dual-boot utility will modify your hard disk's master boot record (MBR) to point toward /boot to start Linux; the physical locations of the other Linux partitions are then immaterial. If you don't want to tamper with the MBR, you can opt for a floppy-based Linux boot routine by creating a boot disk. Regardless of the boot mechanism, be sure to create a Linux boot disk and keep it safe in case of later difficulties.

If you're configuring your machine for networking, you need to understand how to set up the TCP/IP parameters (see the "HOWTOs" documents at www.linuxdoc.org ). After selecting mouse type, time zone, and user/root passwords, select any software packages you want to install. If you plan to write some simple drivers, you need a GUI, an editor, compiler and debugger. If you have enough disk space, select "everything", which on my PC consumed 131 Mbytes of the root partition 1313 Mbytes of user space. "Everything" also loads both the Gnome and KDE GUIs, so you can use whichever one you wish. (You can easily add or remove packages later using Red Hat's Package Manager--RPM--program.) Finally, set your video adapter specifications, create a boot disk, reboot, and your PC should be running Linux.--David Marsh

You're Not In Windows Anymore
Windows and Linux differ in how they manage information. Windows uses device “names” such as a:, c:, and d: to label disk drives. Linux identifies these devices as /dev/fd0, /dev/hda (for EIDE disks), and /dev/cdrom.
  Linux also treats disk storage differently by dividing disk space into partitions. Most PCs don’t require disk partitioning. When you install Linux, you’ll set up one partition for the OS and one or more partitions for user files. By maintaining individual partitions, Linux can establish “permissions” that determine which users may access which files and resources. At a minimum, Linux needs a root partition and a swap partition. Red Hat recommends assigning at least 600 Mbytes for the root partition, also called the Linux native partition. This partition holds the Linux OS.
  Linux OS “mounts,” or makes available, partitions when the PC boots, thus making the PC’s file “tree” appear contiguous. The term “mount” comes from a time when operators actually mounted disks and magnetic tapes on hardware according to users’ needs. Thus, files could always appear on more than one device. The OS had to locate the files and construct a map that would properly locate them. So, when a Linux manual says that a device or file gets mounted, it simply means it’s available for use.
  File structures in Linux systems can vary, but the most-used structure is ext2. This structure provides for 256-character file names and 4-Tbyte files. If given a choice, use this structure on your Linux computer. Linux installers, such as the one in Red Hat’s Linux “build” directory structures that follow the Filesystem Hierarchy Standard ( www.pathname.com/fhs/ ).--David Marsh
Email
Print
Reprint
Learn RSS

Talkback

We would love your feedback!

Post a comment

» VIEW ALL TALKBACK THREADS

Related Content

Related Content

 

By This Author

Sponsored Links



 
Advertisement
SPONSORED LINKS

More Content

  • Blogs
  • Podcasts

Blogs

  • Rick Nelson
    Taking the Measure

    August 28, 2008
    What’s your battery IQ?
    What features do you look for in a battery, and do you know which battery technologies to choose to ...
    More
  • Rick Nelson
    Taking the Measure

    August 27, 2008
    Jim Williams gets a shout-out in Forbes
    Forbes magazine has discovered that Silicon Valley isn’t all “slick marketing pitches, s...
    More
  • » VIEW ALL BLOGS RSS

Podcasts

Advertisements





NEWSLETTERS
Click on a title below to learn more.

Test Industry News (3 Times Per Month)
Machine-Vision & Inspection (Monthly)
Communications Test (Monthly)
Design, Test & Yield (Monthly)
Automotive, Aerospace & Defense (Monthly)
Instrumentation (Monthly)
Resource Center E-Alert (Monthly)
©2008 Reed Business Information, a division of Reed Elsevier Inc. All rights reserved.
Use of this Web site is subject to its Terms of Use | Privacy Policy
Please visit these other Reed Business sites