FreeBSD Developers Handbook
FreeBSD Developers Handbook
Welcome to the Developers’ Handbook. This manual is a work in progress and is the work of many individuals.
Many sections do not yet exist and some of those that do exist need to be updated. If you are interested in helping
with this project, send email to the FreeBSD documentation project mailing list <[email protected]>.
The latest version of this document is always available from the FreeBSD World Wide Web server
(http://www.FreeBSD.org/). It may also be downloaded in a variety of formats and compression options from the
FreeBSD FTP server (ftp://ftp.FreeBSD.org/pub/FreeBSD/doc) or one of the numerous mirror sites
(http://www.freebsd.org/handbook/mirrors-ftp.html).
Redistribution and use in source (SGML DocBook) and ’compiled’ forms (SGML, HTML, PDF, PostScript, RTF and so forth) with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code (SGML DocBook) must retain the above copyright notice, this list of conditions
and the following disclaimer as the first lines of this file unmodified.
2. Redistributions in compiled form (transformed to other DTDs, converted to PDF, PostScript, RTF and other
formats) must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Important: THIS DOCUMENTATION IS PROVIDED BY THE FREEBSD DOCUMENTATION PROJECT "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
NO EVENT SHALL THE FREEBSD DOCUMENTATION PROJECT BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
Table of Contents
I. Introduction ...............................................................................................................................................................8
1 Developing on FreeBSD.....................................................................................................................................9
2 The BSD Vision .................................................................................................................................................1
3 Architectural Overview ......................................................................................................................................2
4 The Layout of /usr/src ........................................................................................................................................3
II. Basics.........................................................................................................................................................................4
5 Programming Tools ............................................................................................................................................5
5.1 Synopsis.................................................................................................................................................5
5.2 Introduction............................................................................................................................................5
5.3 Introduction to Programming ................................................................................................................5
5.4 Compiling with cc .................................................................................................................................8
5.5 Make ....................................................................................................................................................16
5.6 Debugging............................................................................................................................................21
5.7 Using Emacs as a Development Environment.....................................................................................25
5.8 Further Reading ...................................................................................................................................35
6 Secure Programming ........................................................................................................................................37
6.1 Synopsis...............................................................................................................................................37
6.2 Secure Design Methodology................................................................................................................37
6.3 Buffer Overflows .................................................................................................................................37
6.4 SetUID issues.......................................................................................................................................40
6.5 Limiting your program’s environment.................................................................................................40
6.6 Trust .....................................................................................................................................................42
6.7 Race Conditions...................................................................................................................................42
III. Kernel ....................................................................................................................................................................43
7 History of the Unix Kernel...............................................................................................................................44
8 Locking Notes ..................................................................................................................................................45
8.1 Mutexes................................................................................................................................................45
8.2 Lock Manager Locks ...........................................................................................................................48
8.3 Atomically Protected Variables ...........................................................................................................48
IV. Memory Management ..........................................................................................................................................49
9 Virtual Memory System ...................................................................................................................................50
9.1 The FreeBSD VM System ...................................................................................................................50
10 DMA...............................................................................................................................................................54
10.1 DMA: What it is and How it Works ..................................................................................................54
V. I/O System...............................................................................................................................................................67
11 UFS.................................................................................................................................................................68
3
VI. Interprocess Communication ..............................................................................................................................69
12 Signals ............................................................................................................................................................70
VII. Networking ..........................................................................................................................................................71
13 Sockets ...........................................................................................................................................................72
13.1 Synopsis.............................................................................................................................................72
13.2 Networking and Diversity..................................................................................................................72
13.3 Protocols ............................................................................................................................................72
13.4 The Sockets Model ............................................................................................................................75
13.5 Essential Socket Functions ................................................................................................................75
13.6 Helper Functions................................................................................................................................91
13.7 Concurrent Servers ............................................................................................................................94
14 IPv6 Internals .................................................................................................................................................97
14.1 IPv6/IPsec Implementation................................................................................................................97
VIII. Network Filesystems........................................................................................................................................118
15 AFS...............................................................................................................................................................119
IX. Terminal Handling .............................................................................................................................................120
16 Syscons.........................................................................................................................................................121
X. Sound.....................................................................................................................................................................122
17 OSS...............................................................................................................................................................123
XI. Device Drivers .....................................................................................................................................................124
18 Writing FreeBSD Device Drivers.................................................................................................................125
18.1 Introduction......................................................................................................................................125
18.2 Dynamic Kernel Linker Facility - KLD...........................................................................................125
18.3 Accessing a device driver ................................................................................................................127
18.4 Character Devices ............................................................................................................................127
18.5 Network Drivers...............................................................................................................................131
19 ISA device drivers ........................................................................................................................................133
19.1 Synopsis...........................................................................................................................................133
19.2 Basic information.............................................................................................................................133
19.3 Device_t pointer...............................................................................................................................135
19.4 Config file and the order of identifying and probing during auto-configuration .............................136
19.5 Resources.........................................................................................................................................138
19.6 Bus memory mapping......................................................................................................................141
19.7 DMA ................................................................................................................................................149
19.8 xxx_isa_probe..................................................................................................................................151
19.9 xxx_isa_attach .................................................................................................................................158
19.10 xxx_isa_detach ..............................................................................................................................162
19.11 xxx_isa_shutdown .........................................................................................................................163
4
20 PCI Devices..................................................................................................................................................165
20.1 Probe and Attach..............................................................................................................................165
20.2 Bus Resources..................................................................................................................................169
21 Common Access Method SCSI Controllers.................................................................................................173
21.1 Synopsis...........................................................................................................................................173
21.2 General architecture.........................................................................................................................173
21.3 Polling..............................................................................................................................................194
21.4 Asynchronous Events ......................................................................................................................195
21.5 Interrupts..........................................................................................................................................196
21.6 Errors Summary...............................................................................................................................203
21.7 Timeout Handling ............................................................................................................................204
22 USB Devices ................................................................................................................................................206
22.1 Introduction......................................................................................................................................206
22.2 Host Controllers...............................................................................................................................207
22.3 USB Device Information .................................................................................................................209
22.4 Device probe and attach...................................................................................................................211
22.5 USB Drivers Protocol Information ..................................................................................................212
23 NewBus ........................................................................................................................................................215
XII. Architectures .....................................................................................................................................................216
24 x86 Assembly Language Programming .......................................................................................................217
24.1 Synopsis...........................................................................................................................................217
24.2 The Tools .........................................................................................................................................217
24.3 System Calls ....................................................................................................................................218
24.4 Return Values...................................................................................................................................221
24.5 Creating Portable Code....................................................................................................................222
24.6 Our First Program ............................................................................................................................227
24.7 Writing Unix Filters.........................................................................................................................229
24.8 Buffered Input and Output...............................................................................................................232
24.9 Command Line Arguments..............................................................................................................240
24.10 Unix Environment..........................................................................................................................244
24.11 Working with Files.........................................................................................................................250
24.12 One-Pointed Mind .........................................................................................................................262
24.13 Using the FPU................................................................................................................................272
24.14 Caveats...........................................................................................................................................305
24.15 Acknowledgements........................................................................................................................306
25 Alpha ............................................................................................................................................................308
26 IA-64 ............................................................................................................................................................309
XIII. Debugging.........................................................................................................................................................310
27 Truss .............................................................................................................................................................311
5
XIV. Compatibility Layers.......................................................................................................................................312
28 Linux ............................................................................................................................................................313
XV. Appendices .........................................................................................................................................................314
Bibliography......................................................................................................................................................315
Index..................................................................................................................................................................315
6
List of Tables
8-1. Mutex List..............................................................................................................................................................46
8-2. lockmgr(9) Lock List.............................................................................................................................................48
List of Examples
5-1. A sample .emacs file............................................................................................................................................28
7
I. Introduction
Chapter 1 Developing on FreeBSD
This will need to discuss FreeBSD as a development platform, the vision of BSD, architectural overview, layout of
/usr/src, history, etc.
Thank you for considering FreeBSD as your development platform! We hope it will not let you down.
9
Chapter 2 The BSD Vision
1
Chapter 3 Architectural Overview
2
Chapter 4 The Layout of /usr/src
The complete source code to FreeBSD is available from our public CVS repository. The source code is normally
installed in /usr/src which contains the following subdirectories.
Directory Description
bin/ Source for files in /bin
contrib/ Source for files from contributed software.
crypto/ DES source
etc/ Source for files in /etc
games/ Source for files in /usr/games
gnu/ Utilities covered by the GNU Public License
include/ Source for files in /usr/include
kerberosIV/ Source for Kerbereros version IV
kerberos5/ Source for Kerbereros version 5
lib/ Source for files in /usr/lib
libexec/ Source for files in /usr/libexec
release/ Files required to produce a FreeBSD release
sbin/ Source for files in /sbin
secure/ FreeSec sources
share/ Source for files in /sbin
sys/ Kernel source files
tools/ Tools used for maintenance and testing of FreeBSD
usr.bin/ Source for files in /usr/bin
usr.sbin/ Source for files in /usr/sbin
3
II. Basics
Chapter 5 Programming Tools
This chapter was written by James Raynard <[email protected] >. Modifications for the Developers’
Handbook by Murray Stokely <[email protected] >.
5.1 Synopsis
This document is an introduction to using some of the programming tools supplied with FreeBSD, although much of
it will be applicable to many other versions of Unix. It does not attempt to describe coding in any detail. Most of the
document assumes little or no previous programming knowledge, although it is hoped that most programmers will
find something of value in it.
5.2 Introduction
FreeBSD offers an excellent development environment. Compilers for C, C++, and Fortran and an assembler come
with the basic system, not to mention a Perl interpreter and classic Unix tools such as sed and awk. If that is not
enough, there are many more compilers and interpreters in the Ports collection. FreeBSD is very compatible with
standards such as POSIX and ANSI C, as well with its own BSD heritage, so it is possible to write applications that
will compile and run with little or no modification on a wide range of platforms.
However, all this power can be rather overwhelming at first if you’ve never written programs on a Unix platform
before. This document aims to help you get up and running, without getting too deeply into more advanced topics.
The intention is that this document should give you enough of the basics to be able to make some sense of the
documentation.
Most of the document requires little or no knowledge of programming, although it does assume a basic competence
with using Unix and a willingness to learn!
5
Chapter 5 Programming Tools
5.3.1 Interpreters
With an interpreter, the language comes as an environment, where you type in commands at a prompt and the
environment executes them for you. For more complicated programs, you can type the commands into a file and get
the interpreter to load the file and execute the commands in it. If anything goes wrong, many interpreters will drop
you into a debugger to help you track down the problem.
The advantage of this is that you can see the results of your commands immediately, and mistakes can be corrected
readily. The biggest disadvantage comes when you want to share your programs with someone. They must have the
same interpreter, or you must have some way of giving it to them, and they need to understand how to use it. Also
users may not appreciate being thrown into a debugger if they press the wrong key! From a performance point of
view, interpreters can use up a lot of memory, and generally do not generate code as efficiently as compilers.
In my opinion, interpreted languages are the best way to start if you have not done any programming before. This
kind of environment is typically found with languages like Lisp, Smalltalk, Perl and Basic. It could also be argued
that the Unix shell (sh, csh) is itself an interpreter, and many people do in fact write shell “scripts” to help with
various “housekeeping” tasks on their machine. Indeed, part of the original Unix philosophy was to provide lots of
small utility programs that could be linked together in shell scripts to perform useful tasks.
as root. Obviously, you will need to have a fully functional FreeBSD 2.1.0 or later system for the package to work!
BASIC
Short for Beginner’s All-purpose Symbolic Instruction Code. Developed in the 1950s for teaching University
students to program and provided with every self-respecting personal computer in the 1980s, BASIC has been
the first programming language for many programmers. It’s also the foundation for Visual Basic.
The Bywater Basic Interpreter (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/bwbasic-2.10.tgz) and the
Phil Cockroft’s Basic Interpreter (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/pbasic-2.0.tgz) (formerly
Rabbit Basic) are available as FreeBSD packages (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/).
6
Chapter 5 Programming Tools
Lisp
A language that was developed in the late 1950s as an alternative to the “number-crunching” languages that
were popular at the time. Instead of being based on numbers, Lisp is based on lists; in fact the name is short for
“List Processing”. Very popular in AI (Artificial Intelligence) circles.
Lisp is an extremely powerful and sophisticated language, but can be rather large and unwieldy.
FreeBSD has GNU Common Lisp (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/gcl-2.0.tgz) available as a
package.
Perl
Very popular with system administrators for writing scripts; also often used on World Wide Web servers for
writing CGI scripts.
The latest version (version 5) comes with FreeBSD.
Scheme
A dialect of Lisp that is rather more compact and cleaner than Common Lisp. Popular in Universities as it is
simple enough to teach to undergraduates as a first language, while it has a high enough level of abstraction to
be used in research work.
FreeBSD has packages of the Elk Scheme Interpreter
(ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/elk-3.0.tgz), the MIT Scheme Interpreter
(ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/mit-scheme-7.3.tgz) and the SCM Scheme Interpreter
(ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/scm-4e1.tgz).
Icon
The Icon Programming Language (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/icon-9.0.tgz).
Logo
Brian Harvey’s LOGO Interpreter (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/ucblogo-3.3.tgz).
Python
The Python Object-Oriented Programming Language
(ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/python-1.2)
7
Chapter 5 Programming Tools
5.3.3 Compilers
Compilers are rather different. First of all, you write your code in a file (or files) using an editor. You then run the
compiler and see if it accepts your program. If it did not compile, grit your teeth and go back to the editor; if it did
compile and gave you a program, you can run it either at a shell command prompt or in a debugger to see if it works
properly. 1
Obviously, this is not quite as direct as using an interpreter. However it allows you to do a lot of things which are
very difficult or even impossible with an interpreter, such as writing code which interacts closely with the operating
system—or even writing your own operating system! It’s also useful if you need to write very efficient code, as the
compiler can take its time and optimise the code, which would not be acceptable in an interpreter. And distributing a
program written for a compiler is usually more straightforward than one written for an interpreter—you can just give
them a copy of the executable, assuming they have the same operating system as you.
Compiled languages include Pascal, C and C++. C and C++ are rather unforgiving languages, and best suited to
more experienced programmers; Pascal, on the other hand, was designed as an educational language, and is quite a
good language to start with. Unfortunately, FreeBSD doesn’t have any Pascal support, except for a Pascal-to-C
converter in the ports.
As the edit-compile-run-debug cycle is rather tedious when using separate programs, many commercial compiler
makers have produced Integrated Development Environments (IDEs for short). FreeBSD does not have an IDE as
such; however it is possible to use Emacs for this purpose. This is discussed in Section 5.7.
1. Pre-process your source code to remove comments and do other tricks like expanding macros in C.
2. Check the syntax of your code to see if you have obeyed the rules of the language. If you have not, it will
complain!
3. Convert the source code into assembly language—this is very close to machine code, but still understandable by
humans. Allegedly. 2
4. Convert the assembly language into machine code—yep, we are talking bits and bytes, ones and zeros here.
8
Chapter 5 Programming Tools
5. Check that you have used things like functions and global variables in a consistent way. For example, if you
have called a non-existent function, it will complain.
6. If you are trying to produce an executable from several source code files, work out how to fit them all together.
7. Work out how to produce something that the system’s run-time loader will be able to load into memory and run.
8. Finally, write the executable on the file system.
The word compiling is often used to refer to just steps 1 to 4—the others are referred to as linking. Sometimes step 1
is referred to as pre-processing and steps 3-4 as assembling.
Fortunately, almost all this detail is hidden from you, as cc is a front end that manages calling all these programs
with the right arguments for you; simply typing
% cc foobar.c
will cause foobar.c to be compiled by all the steps above. If you have more than one file to compile, just do
something like
% cc foo.c bar.c
Note that the syntax checking is just that—checking the syntax. It will not check for any logical mistakes you may
3
have made, like putting the program into an infinite loop, or using a bubble sort when you meant to use a binary sort.
There are lots and lots of options for cc, which are all in the man page. Here are a few of the most important ones,
with examples of how to use them.
-o filename
4
The output name of the file. If you do not use this option, cc will produce an executable called a.out.
-c
Just compile the file, do not link it. Useful for toy programs where you just want to check the syntax, or if you
are using a Makefile.
% cc -c foobar.c
This will produce an object file (not an executable) called foobar.o. This can be linked together with other
object files into an executable.
9
Chapter 5 Programming Tools
-g
Create a debug version of the executable. This makes the compiler put information into the executable about
which line of which source file corresponds to which function call. A debugger can use this information to show
the source code as you step through the program, which is very useful; the disadvantage is that all this extra
information makes the program much bigger. Normally, you compile with -g while you are developing a
program and then compile a “release version” without -g when you’re satisfied it works properly.
% cc -g foobar.c
5
This will produce a debug version of the program.
-O
Create an optimised version of the executable. The compiler performs various clever tricks to try and produce
an executable that runs faster than normal. You can add a number after the -O to specify a higher level of
optimisation, but this often exposes bugs in the compiler’s optimiser. For instance, the version of cc that comes
with the 2.1.0 release of FreeBSD is known to produce bad code with the -O2 option in some circumstances.
Optimisation is usually only turned on when compiling a release version.
% cc -O -o foobar foobar.c
The following three flags will force cc to check that your code complies to the relevant international standard, often
referred to as the ANSI standard, though strictly speaking it is an ISO standard.
-Wall
Enable all the warnings which the authors of cc believe are worthwhile. Despite the name, it will not enable all
the warnings cc is capable of.
-ansi
Turn off most, but not all, of the non-ANSI C features provided by cc. Despite the name, it does not guarantee
strictly that your code will comply to the standard.
10
Chapter 5 Programming Tools
-pedantic
Turn off all cc’s non-ANSI C features.
Without these flags, cc will allow you to use some of its non-standard extensions to the standard. Some of these are
very useful, but will not work with other compilers—in fact, one of the main aims of the standard is to allow people
to write code that will work with any compiler on any system. This is known as portable code.
Generally, you should try to make your code as portable as possible, as otherwise you may have to completely
re-write the program later to get it to work somewhere else—and who knows what you may be using in a few years
time?
This will produce an executable foobar after checking foobar.c for standard compliance.
-llibrary
Specify a function library to be used during when linking.
The most common example of this is when compiling a program that uses some of the mathematical functions
in C. Unlike most other platforms, these are in a separate library from the standard C one and you have to tell
the compiler to add it.
The rule is that if the library is called libsomething .a, you give cc the argument -lsomething . For
example, the math library is libm.a, so you give cc the argument -lm. A common “gotcha” with the math
library is that it has to be the last library on the command line.
Each of these will both produce an executable foobar from the C++ source file foobar.cc. Note that, on Unix
systems, C++ source files traditionally end in .C, .cxx or .cc, rather than the MS-DOS style .cpp (which was
11
Chapter 5 Programming Tools
already used for something else). gcc used to rely on this to work out what kind of compiler to use on the
source file; however, this restriction no longer applies, so you may now call your C++ files .cpp with impunity!
When using mathematical functions like sin(), you have to tell cc to link in the math library, like so:
2. All right, I wrote this simple program to practice using -lm. All it does is raise 2.1 to the power of 6.
#include <stdio.h>
int main() {
float f;
f = pow(2.1, 6);
printf("2.1 ^ 6 = %f\n", f);
return 0;
}
% cc temp.c -lm
12
Chapter 5 Programming Tools
like you said I should, but I get this when I run it:
% ./a.out
2.1 ^ 6 = 1023.000000
When the compiler sees you call a function, it checks if it has already seen a prototype for it. If it has not, it assumes
the function returns an int, which is definitely not what you want here.
#include <math.h>
#include <stdio.h>
int main() {
...
% ./a.out
2.1 ^ 6 = 85.766121
If you are using any of the mathematical functions, always include math.h and remember to link in the math library.
4. I compiled a file called foobar.c and I cannot find an executable called foobar. Where’s it gone?
Remember, cc will call the executable a.out unless you tell it differently. Use the -o filename option:
% cc -o foobar foobar.c
13
Chapter 5 Programming Tools
5. OK, I have an executable called foobar, I can see it when I run ls, but when I type in foobar at the command
prompt it tells me there is no such file. Why can it not find it?
Unlike MS-DOS, Unix does not look in the current directory when it is trying to find out which executable you want
it to run, unless you tell it to. Either type ./foobar, which means “run the file called foobar in the current
directory”, or change your PATH environment variable so that it looks something like
bin:/usr/bin:/usr/local/bin:.
The dot at the end means “look in the current directory if it is not in any of the others”.
6. I called my executable test, but nothing happens when I run it. What is going on?
Most Unix systems have a program called test in /usr/bin and the shell is picking that one up before it gets to
checking the current directory. Either type:
% ./test
7. I compiled my program and it seemed to run all right at first, then there was an error and it said something about
core dumped. What does that mean?
The name core dump dates back to the very early days of Unix, when the machines used core memory for storing
data. Basically, if the program failed under certain conditions, the system would write the contents of core memory
to disk in a file called core, which the programmer could then pore over to find out what went wrong.
9. When my program dumped core, it said something about a segmentation fault. What’s that?
This basically means that your program tried to perform some sort of illegal operation on memory; Unix is designed
to protect the operating system and other programs from rogue programs.
Common causes for this are:
14
Chapter 5 Programming Tools
The pointer will have some random value that, with luck, will point into an area of memory that isn’t available to
your program and the kernel will kill your program before it can do any damage. If you’re unlucky, it’ll point
somewhere inside your own program and corrupt one of your data structures, causing the program to fail
mysteriously.
Unix compilers often put string literals like "My string" into read-only areas of memory.
or
char *foo = malloc(27);
free(foo);
free(foo);
Making one of these mistakes will not always lead to an error, but they are always bad practice. Some systems and
compilers are more tolerant than others, which is why programs that ran well on one system can crash when you try
them on an another.
15
Chapter 5 Programming Tools
10. Sometimes when I get a core dump it says bus error. It says in my Unix book that this means a hardware
problem, but the computer still seems to be working. Is this true?
No, fortunately not (unless of course you really do have a hardware problem. . . ). This is usually another way of
saying that you accessed memory in a way you shouldn’t have.
11. This dumping core business sounds as though it could be quite useful, if I can make it happen when I want to.
Can I do this, or do I have to wait until there’s an error?
Yes, just go to another console or xterm, do
% ps
5.5 Make
% cc file1.c file2.c
16
Chapter 5 Programming Tools
is not too bad, but it quickly becomes very tedious when there are several files—and it can take a while to compile,
too.
One way to get around this is to use object files and only recompile the source file if the source code has changed. So
we could have something like:
if we’d changed file37.c, but not any of the others, since the last time we compiled. This may speed up the
compilation quite a bit, but doesn’t solve the typing problem.
Or we could write a shell script to solve the typing problem, but it would have to re-compile everything, making it
very inefficient on a large project.
What happens if we have hundreds of source files lying about? What if we’re working in a team with other people
who forget to tell us when they’ve changed one of their source files that we use?
Perhaps we could put the two solutions together and write something like a shell script that would contain some kind
of magic rule saying when a source file needs compiling. Now all we need now is a program that can understand
these rules, as it’s a bit too complicated for the shell.
This program is called make. It reads in a file, called a makefile, that tells it how different files depend on each other,
and works out which files need to be re-compiled and which ones don’t. For example, a rule could say something like
“if fromboz.o is older than fromboz.c, that means someone must have changed fromboz.c, so it needs to be
re-compiled.” The makefile also has rules telling make how to re-compile the source file, making it a much more
powerful tool.
Makefiles are typically kept in the same directory as the source they apply to, and can be called makefile,
Makefile or MAKEFILE. Most programmers use the name Makefile, as this puts it near the top of a directory
listing, where it can easily be seen. 6
foo: foo.c
cc -o foo foo.c
17
Chapter 5 Programming Tools
The creation line starts with a tab (press the tab key) and then the command you would type to create foo if you
were doing it at a command prompt. If foo is out of date, or does not exist, make then executes this command to
create it. In other words, this is the rule which tells make how to re-compile foo.c.
So, when you type make, it will make sure that foo is up to date with respect to your latest changes to foo.c. This
principle can be extended to Makefiles with hundreds of targets—in fact, on FreeBSD, it is possible to compile the
entire operating system just by typing make world in the appropriate directory!
Another useful property of makefiles is that the targets don’t have to be programs. For instance, we could have a
make file that looks like this:
foo: foo.c
cc -o foo foo.c
install:
cp foo /home/me
% make target
make will then only look at that target and ignore any others. For example, if we type make foo with the makefile
above, make will ignore the install target.
If we just type make on its own, make will always look at the first target and then stop without looking at any others.
So if we typed make here, it will just go to the foo target, re-compile foo if necessary, and then stop without going
on to the install target.
Notice that the install target doesn’t actually depend on anything! This means that the command on the following line
is always executed when we try to make that target by typing make install. In this case, it will copy foo into
the user’s home directory. This is often used by application makefiles, so that the application can be installed in the
correct directory when it has been correctly compiled.
This is a slightly confusing subject to try and explain. If you don’t quite understand how make works, the best thing
to do is to write a simple program like “hello world” and a make file like the one above and experiment. Then
progress to using more than one source file, or having the source file include a header file. The touch command is
very useful here—it changes the date on a file without you having to edit it.
#include <stdio.h>
18
Chapter 5 Programming Tools
#include "foo.h"
int main(....
To make sure that this file is recompiled the moment foo.h is changed, you have to add it in your Makefile:
The moment your project is getting bigger and you have more and more own include-files to maintain, it will be a
pain to keep track of all include files and the files which are depending on it. If you change an include-file but forget
to recompile all the files which are depending on it, the results will be devastating. gcc has an option to analyze your
files and to produce a list of include-files and their dependencies: -MM.
If you add this to your Makefile:
depend:
gcc -E -MM *.c > .depend
and run make depend, the file .depend will appear with a list of object-files, C-files and the include-files:
If you change foo.h, next time you run make all files depending on foo.h will be recompiled.
Don’t forget to run make depend each time you add an include-file to one of your files.
MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/
DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz
.include <bsd.port.mk>
Now, if we go to the directory for this port and type make, the following happens:
1. A check is made to see if the source code for this port is already on the system.
2. If it isn’t, an FTP connection to the URL in MASTER_SITES is set up to download the source.
3. The checksum for the source is calculated and compared it with one for a known, good, copy of the source. This
is to make sure that the source was not corrupted while in transit.
19
Chapter 5 Programming Tools
4. Any changes required to make the source work on FreeBSD are applied—this is known as patching.
5. Any special configuration needed for the source is done. (Many Unix program distributions try to work out
which version of Unix they are being compiled on and which optional Unix features are present—this is where
they are given the information in the FreeBSD ports scenario).
6. The source code for the program is compiled. In effect, we change to the directory where the source was
unpacked and do make—the program’s own make file has the necessary information to build the program.
7. We now have a compiled version of the program. If we wish, we can test it now; when we feel confident about
the program, we can type make install. This will cause the program and any supporting files it needs to be
copied into the correct location; an entry is also made into a package database, so that the port can easily be
uninstalled later if we change our mind about it.
Now I think you’ll agree that’s rather impressive for a four line script!
The secret lies in the last line, which tells make to look in the system makefile called bsd.port.mk. It’s easy to
overlook this line, but this is where all the clever stuff comes from—someone has written a makefile that tells make
to do all the things above (plus a couple of other things I didn’t mention, including handling any errors that may
occur) and anyone can get access to that just by putting a single line in their own make file!
If you want to have a look at these system makefiles, they’re in /usr/share/mk, but it’s probably best to wait until
you’ve had a bit of practice with makefiles, as they are very complicated (and if you do look at them, make sure you
have a flask of strong coffee handy!)
% zmore paper.ascii.gz
in that directory.
Many applications in the ports use GNU make, which has a very good set of “info” pages. If you have installed any
of these ports, GNU make will automatically have been installed as gmake. It’s also available as a port and package
in its own right.
To view the info pages for GNU make, you will have to edit the dir file in the /usr/local/info directory to add
an entry for it. This involves adding a line like
20
Chapter 5 Programming Tools
to the file. Once you have done this, you can type info and then select make from the menu (or in Emacs, do C-h
i).
5.6 Debugging
% gdb progname
although most people prefer to run it inside Emacs. You can do this by:
Using a debugger allows you to run the program under more controlled circumstances. Typically, you can step
through the program a line at a time, inspect the value of variables, change them, tell the debugger to run up to a
certain point and then stop, and so on. You can even attach to a program that’s already running, or load a core file to
investigate why the program crashed. It’s even possible to debug the kernel, though that’s a little trickier than the user
applications we’ll be discussing in this section.
gdb has quite good on-line help, as well as a set of info pages, so this section will concentrate on a few of the basic
commands.
Finally, if you find its text-based command-prompt style off-putting, there’s a graphical front-end for it xxgdb
(../../ports/devel.html) in the ports collection.
This section is intended to be an introduction to using gdb and does not cover specialised topics such as debugging
the kernel.
when gdb starts up, you’ll know that the program wasn’t compiled with the -g option.
21
Chapter 5 Programming Tools
At the gdb prompt, type break main. This will tell the debugger to skip over the preliminary set-up code in the
program and start at the beginning of your code. Now type run to start the program—it will start at the beginning of
the set-up code and then get stopped by the debugger when it calls main(). (If you’ve ever wondered where main()
gets called from, now you know!).
You can now step through the program, a line at a time, by pressing n. If you get to a function call, you can step into
it by pressing s. Once you’re in a function call, you can return from stepping into a function call by pressing f. You
can also use up and down to take a quick look at the caller.
Here’s a simple example of how to spot a mistake in a program with gdb. This is our program (with a deliberate
mistake):
#include <stdio.h>
int bazz(int anint);
main() {
int i;
printf("This is my program\n");
bazz(i);
return 0;
}
This program sets i to be 5 and passes it to a function bazz() which prints out the number we gave it.
When we compile and run the program we get
% cc -g -o temp temp.c
% ./temp
This is my program
anint = 4231
% gdb temp
GDB is free software and you are welcome to distribute copies of it
under certain conditions; type "show copying" to see the conditions.
There is absolutely no warranty for GDB; type "show warranty" for details.
GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.
(gdb) break main Skip the set-up code
22
Chapter 5 Programming Tools
Hang on a minute! How did anint get to be 4231? Didn’t we set it to be 5 in main()? Let’s move up to main() and
have a look.
...
main() {
int i;
i = 5;
printf("This is my program\n");
...
but we left the i=5; line out. As we didn’t initialise i, it had whatever number happened to be in that area of memory
when the program ran, which in this case happened to be 4231.
Note: gdb displays the stack frame every time we go into or out of a function, even if we’re using up and down to
move around the call stack. This shows the name of the function and the values of its arguments, which helps us
keep track of where we are and what’s going on. (The stack is a storage area where the program stores
information about the arguments passed to functions and where to go when it returns from a function call).
23
Chapter 5 Programming Tools
bit easier. Incidentally, under FreeBSD and other 4.4BSD systems, a core file is called progname.core instead of
just core, to make it clearer which program a core file belongs to.
To examine a core file, start up gdb in the usual way. Instead of typing break or run, type
If you’re not in the same directory as the core file, you’ll have to do dir /path/to/core/file first.
You should see something like this:
% gdb a.out
GDB is free software and you are welcome to distribute copies of it
under certain conditions; type "show copying" to see the conditions.
There is absolutely no warranty for GDB; type "show warranty" for details.
GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.
(gdb) core a.out.core
Core was generated by ‘a.out’.
Program terminated with signal 11, Segmentation fault.
Cannot access memory at address 0x7020796d.
#0 0x164a in bazz (anint=0x5) at temp.c:17
(gdb)
In this case, the program was called a.out, so the core file is called a.out.core. We can see that the program
crashed due to trying to access an area in memory that was not available to it in a function called bazz.
Sometimes it’s useful to be able to see how a function was called, as the problem could have occurred a long way up
the call stack in a complex program. The bt command causes gdb to print out a back-trace of the call stack:
(gdb) bt
#0 0x164a in bazz (anint=0x5) at temp.c:17
#1 0xefbfd888 in end ()
#2 0x162c in main () at temp.c:11
(gdb)
The end() function is called when a program crashes; in this case, the bazz() function was called from main().
24
Chapter 5 Programming Tools
...
if ((pid = fork()) < 0) /* _Always_ check this */
error();
else if (pid == 0) { /* child */
int PauseMode = 1;
while (PauseMode)
sleep(10); /* Wait until someone attaches to us */
...
} else { /* parent */
...
Now all you have to do is attach to the child, set PauseMode to 0, and wait for the sleep() call to return!
5.7.1 Emacs
Unfortunately, Unix systems don’t come with the kind of
everything-you-ever-wanted-and-lots-more-you-didn’t-in-one-gigantic-package integrated development
environments that other systems have. 7 However, it is possible to set up your own environment. It may not be as
pretty, and it may not be quite as integrated, but you can set it up the way you want it. And it’s free. And you have the
source to it.
The key to it all is Emacs. Now there are some people who loathe it, but many who love it. If you’re one of the
former, I’m afraid this section will hold little of interest to you. Also, you’ll need a fair amount of memory to run
it—I’d recommend 8MB in text mode and 16MB in X as the bare minimum to get reasonable performance.
Emacs is basically a highly customisable editor—indeed, it has been customised to the point where it’s more like an
operating system than an editor! Many developers and sysadmins do in fact spend practically all their time working
inside Emacs, leaving it only to log out.
It’s impossible even to summarise everything Emacs can do here, but here are some of the features of interest to
developers:
25
Chapter 5 Programming Tools
• Very powerful editor, allowing search-and-replace on both strings and regular expressions (patterns), jumping to
start/end of block expression, etc, etc.
• Pull-down menus and online help.
• Language-dependent syntax highlighting and indentation.
• Completely customisable.
• You can compile and debug programs within Emacs.
• On a compilation error, you can jump to the offending line of source code.
• Friendly-ish front-end to the info program used for reading GNU hypertext documentation, including the
documentation on Emacs itself.
• Friendly front-end to gdb, allowing you to look at the source code as you step through your program.
• You can read Usenet news and mail while your program is compiling.
And doubtless many more that I’ve overlooked.
Emacs can be installed on FreeBSD using the Emacs port (../../ports/editors.html).
Once it’s installed, start it up and do C-h t to read an Emacs tutorial—that means hold down the control key, press
h, let go of the control key, and then press t. (Alternatively, you can you use the mouse to select Emacs Tutorial
from the Help menu).
Although Emacs does have menus, it’s well worth learning the key bindings, as it’s much quicker when you’re
editing something to press a couple of keys than to try and find the mouse and then click on the right place. And,
when you’re talking to seasoned Emacs users, you’ll find they often casually throw around expressions like “M-x
replace-s RET foo RET bar RET” so it’s useful to know what they mean. And in any case, Emacs has far too
many useful functions for them to all fit on the menu bars.
Fortunately, it’s quite easy to pick up the key-bindings, as they’re displayed next to the menu item. My advice is to
use the menu item for, say, opening a file until you understand how it works and feel confident with it, then try doing
C-x C-f. When you’re happy with that, move on to another menu command.
If you can’t remember what a particular combination of keys does, select Describe Key from the Help menu and
type it in—Emacs will tell you what it does. You can also use the Command Apropos menu item to find out all the
commands which contain a particular word in them, with the key binding next to it.
By the way, the expression above means hold down the Meta key, press x, release the Meta key, type replace-s
(short for replace-string—another feature of Emacs is that you can abbreviate commands), press the return key,
type foo (the string you want replaced), press the return key, type bar (the string you want to replace foo with) and
press return again. Emacs will then do the search-and-replace operation you’ve just requested.
If you’re wondering what on earth the Meta key is, it’s a special key that many Unix workstations have.
Unfortunately, PC’s don’t have one, so it’s usually the alt key (or if you’re unlucky, the escape key).
26
Chapter 5 Programming Tools
Oh, and to get out of Emacs, do C-x C-c (that means hold down the control key, press x, press c and release the
control key). If you have any unsaved files open, Emacs will ask you if you want to save them. (Ignore the bit in the
documentation where it says C-z is the usual way to leave Emacs—that leaves Emacs hanging around in the
background, and is only really useful if you’re on a system which doesn’t have virtual terminals).
27
Chapter 5 Programming Tools
• We enable Emacs’s ability to act as a server, so that if you’re doing something outside Emacs and you want to edit
a file, you can just type in
% emacsclient filename
8
and then you can edit the file in your Emacs!
;; -*-Emacs-Lisp-*-
;; Meta
(global-set-key "\M- " ’set-mark-command)
(global-set-key "\M-\C-h" ’backward-kill-word)
(global-set-key "\M-\C-r" ’query-replace)
(global-set-key "\M-r" ’replace-string)
(global-set-key "\M-g" ’goto-line)
(global-set-key "\M-h" ’help-command)
;; Function keys
(global-set-key [f1] ’manual-entry)
(global-set-key [f2] ’info)
(global-set-key [f3] ’repeat-complex-command)
(global-set-key [f4] ’advertised-undo)
(global-set-key [f5] ’eval-current-buffer)
(global-set-key [f6] ’buffer-menu)
(global-set-key [f7] ’other-window)
(global-set-key [f8] ’find-file)
(global-set-key [f9] ’save-buffer)
(global-set-key [f10] ’next-error)
(global-set-key [f11] ’compile)
(global-set-key [f12] ’grep)
(global-set-key [C-f1] ’compile)
(global-set-key [C-f2] ’grep)
(global-set-key [C-f3] ’next-error)
(global-set-key [C-f4] ’previous-error)
(global-set-key [C-f5] ’display-faces)
(global-set-key [C-f8] ’dired)
28
Chapter 5 Programming Tools
;; Keypad bindings
(global-set-key [up] "\C-p")
(global-set-key [down] "\C-n")
(global-set-key [left] "\C-b")
(global-set-key [right] "\C-f")
(global-set-key [home] "\C-a")
(global-set-key [end] "\C-e")
(global-set-key [prior] "\M-v")
(global-set-key [next] "\C-v")
(global-set-key [C-up] "\M-\C-b")
(global-set-key [C-down] "\M-\C-f")
(global-set-key [C-left] "\M-b")
(global-set-key [C-right] "\M-f")
<
(global-set-key [C-home] "\M- ")
>
(global-set-key [C-end] "\M- ")
<
(global-set-key [C-prior] "\M- ")
>
(global-set-key [C-next] "\M- ")
;; Mouse
(global-set-key [mouse-3] ’imenu)
;; Misc
(global-set-key [C-tab] "\C-q\t") ; Control tab quotes a tab.
(setq backup-by-copying-when-mismatch t)
< >
;; Treat ’y’ or CR as yes, ’n’ as no.
(fset ’yes-or-no-p ’y-or-n-p)
(define-key query-replace-map [return] ’act)
(define-key query-replace-map [?\C-m] ’act)
;; Load packages
(require ’desktop)
(require ’tar-mode)
(if first-time
(setq auto-mode-alist
(append ’(("\\.cpp$" . c++-mode)
29
Chapter 5 Programming Tools
("\\.hpp$" . c++-mode)
("\\.lsp$" . lisp-mode)
("\\.scm$" . scheme-mode)
("\\.pl$" . perl-mode)
) auto-mode-alist)))
(defvar font-lock-mode-keyword-alist
’((c++-c-mode . c-font-lock-keywords)
(perl-mode . perl-font-lock-keywords))
"Associations between modes and keywords")
(defun font-lock-auto-mode-select ()
"Automatically select font-lock-mode if the current major mode is
in font-lock-auto-mode-list"
(if (memq major-mode font-lock-auto-mode-list)
(progn
(font-lock-mode t))
)
)
30
Chapter 5 Programming Tools
(defun my-c-mode-hook ()
(setq tab-width 4)
(define-key c-mode-map "\C-m" ’reindent-then-newline-and-indent)
(define-key c-mode-map "\C-ce" ’c-comment-edit)
(setq c-auto-hungry-initial-state ’none)
(setq c-delete-function ’backward-delete-char)
(setq c-tab-always-indent t)
;; BSD-ish indentation style
(setq c-indent-level 4)
(setq c-continued-statement-offset 4)
(setq c-brace-offset -4)
(setq c-argdecl-indent 0)
(setq c-label-offset -4))
;; Perl mode
(defun my-perl-mode-hook ()
(setq tab-width 4)
(define-key c++-mode-map "\C-m" ’reindent-then-newline-and-indent)
(setq perl-indent-level 4)
(setq perl-continued-statement-offset 4))
;; Scheme mode...
(defun my-scheme-mode-hook ()
(define-key scheme-mode-map "\C-m" ’reindent-then-newline-and-indent))
;; Emacs-Lisp mode...
(defun my-lisp-mode-hook ()
(define-key lisp-mode-map "\C-m" ’reindent-then-newline-and-indent)
(define-key lisp-mode-map "\C-i" ’lisp-indent-line)
(define-key lisp-mode-map "\C-j" ’eval-print-last-sexp))
31
Chapter 5 Programming Tools
;; Complement to next-error
(defun previous-error (n)
"Visit previous compilation error message and corresponding source code."
(interactive "p")
(next-error (- n)))
;; Misc...
(transient-mark-mode 1)
(setq mark-even-if-inactive t)
(setq visible-bell nil)
(setq next-line-add-newlines nil)
(setq compile-command "make")
(setq suggest-key-bindings nil)
(put ’eval-expression ’disabled nil)
(put ’narrow-to-region ’disabled nil)
(put ’set-goal-column ’disabled nil)
32
Chapter 5 Programming Tools
;; Under UNIX
(if (not (equal system-type ’ms-dos))
(progn
(if first-time
(server-start))))
33
Chapter 5 Programming Tools
;; All done
(message "All done, %s%s" (user-login-name) ".")
and install them by copying them into the Emacs site Lisp directory. On FreeBSD 2.1.0-RELEASE, this is
/usr/local/share/emacs/site-lisp.
/usr/ports/lang/whizbang/work/misc/whizbang.el
we would do
34
Chapter 5 Programming Tools
# cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/share/emacs/site-lisp
Next, we need to decide what extension whizbang source files have. Let’s say for the sake of argument that they all
end in .wiz. We need to add an entry to our .emacs file to make sure Emacs will be able to use the information in
whizbang.el.
Find the auto-mode-alist entry in .emacs and add a line for whizbang, such as:
...
("\\.lsp$" . lisp-mode)
("\\.wiz$" . whizbang-mode)
("\\.scm$" . scheme-mode)
...
This means that Emacs will automatically go into whizbang-mode when you edit a file ending in .wiz.
Just below this, you’ll find the font-lock-auto-mode-list entry. Add whizbang-mode to it like so:
This means that Emacs will always enable font-lock-mode (ie syntax highlighting) when editing a .wiz file.
And that’s all that’s needed. If there’s anything else you want done automatically when you open up a .wiz file, you
can add a whizbang-mode hook (see my-scheme-mode-hook for a simple example that adds auto-indent).
• Brian Harvey and Matthew Wright Simply Scheme MIT 1994. ISBN 0-262-08226-8
• Randall Schwartz Learning Perl O’Reilly 1993 ISBN 1-56592-042-2
• Patrick Henry Winston and Berthold Klaus Paul Horn Lisp (3rd Edition) Addison-Wesley 1989 ISBN
0-201-08319-1
• Brian W. Kernighan and Rob Pike The Unix Programming Environment Prentice-Hall 1984 ISBN 0-13-937681-X
• Brian W. Kernighan and Dennis M. Ritchie The C Programming Language (2nd Edition) Prentice-Hall 1988
ISBN 0-13-110362-8
• Bjarne Stroustrup The C++ Programming Language Addison-Wesley 1991 ISBN 0-201-53992-6
35
Chapter 5 Programming Tools
• W. Richard Stevens Advanced Programming in the Unix Environment Addison-Wesley 1992 ISBN 0-201-56317-7
• W. Richard Stevens Unix Network Programming Prentice-Hall 1990 ISBN 0-13-949876-1
Notes
1. If you run it in the shell, you may get a core dump.
2. To be strictly accurate, cc converts the source code into its own, machine-independent p-code instead of
assembly language at this stage.
3. In case you didn’t know, a binary sort is an efficient way of sorting things into order and a bubble sort isn’t.
4. The reasons for this are buried in the mists of history.
5. Note, we didn’t use the -o flag to specify the executable name, so we will get an executable called a.out.
Producing a debug version called foobar is left as an exercise for the reader!
6. They don’t use the MAKEFILE form as block capitals are often used for documentation files like README.
7. At least, not unless you pay out very large sums of money.
8. Many Emacs users set their EDITOR environment to emacsclient so this happens every time they need to edit
a file.
36
Chapter 6 Secure Programming
This chapter was written by Murray Stokely <[email protected]>.
6.1 Synopsis
This chapter describes some of the security issues that have plagued Unix programmers for decades and some of the
new tools available to help programmers avoid writing exploitable code.
37
Chapter 6 Secure Programming
Although stack-based attacks are by far the most common, it would also be possible to overrun the stack with a
heap-based (malloc/free) attack.
The C programming language does not perform automatic bounds checking on arrays or pointers as many other
languages do. In addition, the standard C library is filled with a handful of very dangerous functions.
strcpy(char *dest, const char *src) May overflow the dest buffer
strcat(char *dest, const char *src) May overflow the dest buffer
getwd(char *buf) May overflow the buf buffer
gets(char *s) May overflow the s buffer
[vf]scanf(const char *format, ...) May overflow its arguments.
realpath(char *path, char resolved_path[]) May overflow the path buffer
[v]sprintf(char *str, const char *format, ...) May overflow the str buffer.
#include <stdio.h>
int main() {
char ch,buffer[4096];
int i=0;
i=1;
manipulate(buffer);
i=2;
printf("The value of i is : %d\n",i);
return 0;
}
Let us examine what the memory image of this process would look like if we were to input 160 spaces into our little
program before hitting return.
38
Chapter 6 Secure Programming
"StackGuard detects and defeats stack smashing attacks by protecting the return address on the stack from being altered.
StackGuard places a "canary" word next to the return address when a function is called. If the canary word has been altered
when the function returns, then a stack smashing attack has been attempted, and the program responds by emitting an
intruder alert into syslog, and then halts."
"StackGuard is implemented as a small patch to the gcc code generator, specifically the function_prolog() and
function_epilog() routines. function_prolog() has been enhanced to lay down canaries on the stack when functions start, and
function_epilog() checks canary integrity when the function exits. Any attempt at corrupting the return address is thus
detected before the function returns."
39
Chapter 6 Secure Programming
Recompiling your application with StackGuard is an effective means of stopping most buffer-overflow attacks, but it
can still be compromised.
• libsafe
• libverify
• libparnoia
Unfortunately these library-based defenses have a number of shortcomings. These libraries only protect against a
very small set of security related issues and they neglect to fix the actual problem. These defenses may fail if the
application was compiled with -fomit-frame-pointer. Also, the LD_PRELOAD and LD_LIBRARY_PATH
environment variables can be overwritten/unset by the user.
40
Chapter 6 Secure Programming
actually take effect until you chdir() into your new environment. It should also be noted that a process can easily
break out of a chroot environment if it has root privilege. This could be accomplished by creating device nodes to
read kernel memory, attaching a debugger to a process outside of the jail, or in many other creative ways.
The behavior of the chroot() system call can be controlled somewhat with the kern.chroot_allow_open_directories
sysctl variable. When this value is set to 0, chroot() will fail with EPERM if there are any directories open. If set
to the default value of 1, then chroot() will fail with EPERM if there are any directories open and the process is
already subject to a chroot() call. For any other value, the check for open directories will be bypassed completely.
• Manipulate credential with setuid, seteuid, setgid, setegid, setgroups, setreuid, setregid,
setlogin
• Set resource limits with setrlimit
• Modify some sysctl nodes (kern.hostname)
• chroot()
41
Chapter 6 Secure Programming
This is a work in progress and is the focus of the TrustedBSD (http://www.trustedbsd.org) project. Some of the initial
work has been committed to FreeBSD-current (cap_set_proc(3)).
6.6 Trust
An application should never assume that anything about the users environment is sane. This includes (but is certainly
not limited to) : user input, signals, environment variables, resources, IPC, mmaps, the file system working directory,
file descriptors, the # of open files, etc.
You should never assume that you can catch all forms of invalid input that a user might supply. Instead, your
application should use positive filtering to only allow a specific subset of inputs that you deem safe. Improper data
validation has been the cause of many exploits, especially with CGI scripts on the world wide web. For filenames
you need to be extra careful about paths ("../", "/"), symbolic links, and shell escape characters.
Perl has a really cool feature called "Taint" mode which can be used to prevent scripts for using data derived outside
the program in an unsafe way. This mode will check command line arguments, environment variables, locale
information, the results of certain syscalls (readdir(), readlink(), getpwxxx(), and all file input.
42
III. Kernel
Chapter 7 History of the Unix Kernel
Some history of the Unix/BSD kernel, system calls, how do processes work, blocking, scheduling, threads (kernel),
context switching, signals, interrupts, modules, etc.
44
Chapter 8 Locking Notes
This chapter is maintained by the FreeBSD SMP Next Generation Project <[email protected] >.
This document outlines the locking used in the FreeBSD kernel to permit effective multi-processing within the
kernel. Locking can be achieved via several means. Data structures can be protected by mutexes or lockmgr(9) locks.
A few variables are protected simply by always using atomic operations to access them.
8.1 Mutexes
A mutex is simply a lock used to guarantee mutual exclusion. Specifically, a mutex may only be owned by one entity
at a time. If another entity wishes to obtain a mutex that is already owned, it must wait until the mutex is released. In
the FreeBSD kernel, mutexes are owned by processes.
Mutexes may be recursively acquired, but they are intended to be held for a short period of time. Specifically, one
may not sleep while holding a mutex. If you need to hold a lock across a sleep, use a lockmgr(9) lock.
Each mutex has several properties of interest:
Variable Name
The name of the struct mtx variable in the kernel source.
Logical Name
The name of the mutex assigned to it by mtx_init. This name is displayed in KTR trace messages and witness
errors and warnings and is used to distinguish mutexes in the witness code.
Type
The type of the mutex in terms of the MTX_* flags. The meaning for each flag is related to its meaning as
documented in mutex(9).
MTX_DEF
A sleep mutex
MTX_SPIN
A spin mutex
MTX_COLD
This mutex is initialized very early. Thus, it must be declared via MUTEX_DECLARE, and the MTX_COLD flag
must be passed to mtx_init.
45
Chapter 8 Locking Notes
MTX_TOPHALF
This spin mutex does not disable interrupts.
MTX_NORECURSE
Protectees
A list of data structures or data structure members that this entry protects. For data structure members, the name
will be in the form of structure name.member name.
Dependent Functions
Functions that can only be called if this mutex is held.
46
Chapter 8 Locking Notes
• astpending
• mtx.mtx_lock
48
IV. Memory Management
Chapter 9 Virtual Memory System
50
Chapter 9 Virtual Memory System
reactivation page faults to determine how active or how idle a page actually is. This leads to better decisions being
made as to when to launder or swap-out a page.
51
Chapter 9 Virtual Memory System
52
Chapter 9 Virtual Memory System
If your system is going to use the network heavily, you may want to increase NMBCLUSTERS. Typical values range
from 1024 to 4096.
The NBUF parameter is also traditionally used to scale the system. This parameter determines the amount of KVA the
system can use to map filesystem buffers for I/O. Note that this parameter has nothing whatsoever to do with the
unified buffer cache! This parameter is dynamically tuned in 3.0-CURRENT and later kernels and should generally
not be adjusted manually. We recommend that you not try to specify an NBUF parameter. Let the system pick it. Too
small a value can result in extremely inefficient filesystem operation while too large a value can starve the page
queues by causing too many pages to become wired down.
By default, FreeBSD kernels are not optimized. You can set debugging and optimization flags with the
makeoptions directive in the kernel configuration. Note that you should not use -g unless you can accommodate
the large (typically 7 MB+) kernels that result.
makeoptions DEBUG="-g"
makeoptions COPTFLAGS="-O -pipe"
Sysctl provides a way to tune kernel parameters at run-time. You typically do not need to mess with any of the sysctl
variables, especially the VM related ones.
Run time VM and system tuning is relatively straightforward. First, use softupdates on your UFS/FFS filesystems
whenever possible. /usr/src/contrib/sys/softupdates/README contains instructions (and restrictions) on
how to configure it up.
Second, configure sufficient swap. You should have a swap partition configured on each physical disk, up to four,
even on your “work” disks. You should have at least 2x the swap space as you have main memory, and possibly even
more if you do not have a lot of memory. You should also size your swap partition based on the maximum memory
configuration you ever intend to put on the machine so you do not have to repartition your disks later on. If you want
to be able to accommodate a crash dump, your first swap partition must be at least as large as main memory and
/var/crash must have sufficient free space to hold the dump.
NFS-based swap is perfectly acceptable on -4.x or later systems, but you must be aware that the NFS server will take
the brunt of the paging load.
53
Chapter 10 DMA
Note: The 8237 does allow two channels to be connected together to allow memory-to-memory DMA operations
in a non-“fly-by” mode, but nobody in the PC industry uses this scarce resource this way since it is faster to move
data between memory locations using the CPU.
In the PC architecture, each DMA channel is normally activated only when the hardware that uses a given DMA
channel requests a transfer by asserting the DRQ line for that channel.
54
Chapter 10 DMA
55
Chapter 10 DMA
For a typical floppy disk sector, the above process is repeated 512 times, once for each byte. Each time a byte is
transferred, the address register in the DMA is incremented and the counter in the DMA that shows how many bytes
are to be transferred is decremented.
When the counter reaches zero, the DMA asserts the EOP signal, which indicates that the counter has reached zero
and no more data will be transferred until the DMA controller is reprogrammed by the CPU. This event is also called
the Terminal Count (TC). There is only one EOP signal, and since only DMA channel can be active at any instant,
the DMA channel that is currently active must be the DMA channel that just completed its task.
If a peripheral wants to generate an interrupt when the transfer of a buffer is complete, it can test for its -DACKn
signal and the EOP signal both being asserted at the same time. When that happens, it means the DMA will not
transfer any more information for that peripheral without intervention by the CPU. The peripheral can then assert one
of the interrupt signals to get the processors’ attention. In the PC architecture, the DMA chip itself is not capable of
generating an interrupt. The peripheral and its associated hardware is responsible for generating any interrupt that
occurs. Subsequently, it is possible to have a peripheral that uses DMA but does not use interrupts.
It is important to understand that although the CPU always releases the bus to the DMA when the DMA makes the
request, this action is invisible to both applications and the operating systems, except for slight changes in the
amount of time the processor takes to execute instructions when the DMA is active. Subsequently, the processor
must poll the peripheral, poll the registers in the DMA chip, or receive an interrupt from the peripheral to know for
certain when a DMA transfer has completed.
56
Chapter 10 DMA
Note: “Physical” 64K boundaries should not be confused with 8086-mode 64K “Segments”, which are created by
mathematically adding a segment register with an offset register. Page Registers have no address overlap and
are mathematically OR-ed together.
To further complicate matters, the external DMA address latches on the PC/AT hold only eight bits, so that gives us
8+16=24 bits, which means that the DMA can only point at memory locations between 0 and 16Meg. For newer
computers that allow more than 16Meg of memory, the standard PC-compatible DMA cannot access memory
locations above 16Meg.
To get around this restriction, operating systems will reserve a RAM buffer in an area below 16Meg that also does
not span a physical 64K boundary. Then the DMA will be programmed to transfer data from the peripheral and into
that buffer. Once the DMA has moved the data into this buffer, the operating system will then copy the data from the
buffer to the address where the data is really supposed to be stored.
When writing data from an address above 16Meg to a DMA-based peripheral, the data must be first copied from
where it resides into a buffer located below 16Meg, and then the DMA can copy the data from the buffer to the
hardware. In FreeBSD, these reserved buffers are called “Bounce Buffers”. In the MS-DOS world, they are
sometimes called “Smart Buffers”.
Note: A new implementation of the 8237, called the 82374, allows 16 bits of page register to be specified, allows
access to the entire 32 bit address space, without the use of bounce buffers.
Single
A single byte (or word) is transferred. The DMA must release and re-acquire the bus for each additional byte.
This is commonly-used by devices that cannot transfer the entire block of data immediately. The peripheral will
request the DMA each time it is ready for another transfer.
The standard PC-compatible floppy disk controller (NEC 765) only has a one-byte buffer, so it uses this mode.
Block/Demand
Once the DMA acquires the system bus, an entire block of data is transferred, up to a maximum of 64K. If the
peripheral needs additional time, it can assert the READY signal to suspend the transfer briefly. READY should
57
Chapter 10 DMA
not be used excessively, and for slow peripheral transfers, the Single Transfer Mode should be used instead.
The difference between Block and Demand is that once a Block transfer is started, it runs until the transfer
count reaches zero. DRQ only needs to be asserted until -DACK is asserted. Demand Mode will transfer one
more bytes until DRQ is de-asserted, at which point the DMA suspends the transfer and releases the bus back to
the CPU. When DRQ is asserted later, the transfer resumes where it was suspended.
Older hard disk controllers used Demand Mode until CPU speeds increased to the point that it was more
efficient to transfer the data using the CPU, particularly if the memory locations used in the transfer were above
the 16Meg mark.
Cascade
This mechanism allows a DMA channel to request the bus, but then the attached peripheral device is responsible
for placing the addressing information on the bus instead of the DMA. This is also used to implement a
technique known as “Bus Mastering”.
When a DMA channel in Cascade Mode receives control of the bus, the DMA does not place addresses and I/O
control signals on the bus like the DMA normally does when it is active. Instead, the DMA only asserts the
-DACK signal for the active DMA channel.
At this point it is up to the peripheral connected to that DMA channel to provide address and bus control
signals. The peripheral has complete control over the system bus, and can do reads and/or writes to any address
below 16Meg. When the peripheral is finished with the bus, it de-asserts the DRQ line, and the DMA controller
can then return control to the CPU or to some other DMA channel.
Cascade Mode can be used to chain multiple DMA controllers together, and this is exactly what DMA Channel
4 is used for in the PC architecture. When a peripheral requests the bus on DMA channels 0, 1, 2 or 3, the slave
DMA controller asserts HLDREQ, but this wire is actually connected to DRQ4 on the primary DMA controller
instead of to the CPU. The primary DMA controller, thinking it has work to do on Channel 4, requests the bus
from the CPU using HLDREQ signal. Once the CPU grants the bus to the primary DMA controller, -DACK4 is
asserted, and that wire is actually connected to the HLDA signal on the slave DMA controller. The slave DMA
controller then transfers data for the DMA channel that requested it (0, 1, 2 or 3), or the slave DMA may grant
the bus to a peripheral that wants to perform its own bus-mastering, such as a SCSI controller.
Because of this wiring arrangement, only DMA channels 0, 1, 2, 3, 5, 6 and 7 are usable with peripherals on
PC/AT systems.
Note: DMA channel 0 was reserved for refresh operations in early IBM PC computers, but is generally
available for use by peripherals in modern systems.
58
Chapter 10 DMA
When a peripheral is performing Bus Mastering, it is important that the peripheral transmit data to or from
memory constantly while it holds the system bus. If the peripheral cannot do this, it must release the bus
frequently so that the system can perform refresh operations on main memory.
The Dynamic RAM used in all PCs for main memory must be accessed frequently to keep the bits stored in the
components “charged”. Dynamic RAM essentially consists of millions of capacitors with each one holding one
bit of data. These capacitors are charged with power to represent a 1 or drained to represent a 0. Because all
capacitors leak, power must be added at regular intervals to keep the 1 values intact. The RAM chips actually
handle the task of pumping power back into all of the appropriate locations in RAM, but they must be told when
to do it by the rest of the computer so that the refresh activity won’t interfere with the computer wanting to
access RAM normally. If the computer is unable to refresh memory, the contents of memory will become
corrupted in just a few milliseconds.
Since memory read and write cycles “count” as refresh cycles (a dynamic RAM refresh cycle is actually an
incomplete memory read cycle), as long as the peripheral controller continues reading or writing data to
sequential memory locations, that action will refresh all of memory.
Bus-mastering is found in some SCSI host interfaces and other high-performance peripheral controllers.
Autoinitialize
This mode causes the DMA to perform Byte, Block or Demand transfers, but when the DMA transfer counter
reaches zero, the counter and address are set back to where they were when the DMA channel was originally
programmed. This means that as long as the peripheral requests transfers, they will be granted. It is up to the
CPU to move new data into the fixed buffer ahead of where the DMA is about to transfer it when doing output
operations, and read new data out of the buffer behind where the DMA is writing when doing input operations.
This technique is frequently used on audio devices that have small or no hardware “sample” buffers. There is
additional CPU overhead to manage this “circular” buffer, but in some cases this may be the only way to
eliminate the latency that occurs when the DMA counter reaches zero and the DMA stops transfers until it is
reprogrammed.
59
Chapter 10 DMA
transfer. The LSB and MSB of the address and length are written to the same 8-bit I/O port, so another port must be
written to first to guarantee that the DMA accepts the first byte as the LSB and the second byte as the MSB of the
length and address.
Then, be sure to update the Page Register, which is external to the DMA and is accessed through a different set of
I/O ports.
Once all the settings are ready, the DMA channel can be un-masked. That DMA channel is now considered to be
“armed”, and will respond when the DRQ line for that channel is asserted.
Refer to a hardware data book for precise programming details for the 8237. You will also need to refer to the I/O
port map for the PC system, which describes where the DMA and Page Register ports are located. A complete port
map table is located below.
60
Chapter 10 DMA
61
Chapter 10 DMA
62
Chapter 10 DMA
63
Chapter 10 DMA
64
Chapter 10 DMA
65
Chapter 10 DMA
66
V. I/O System
Chapter 11 UFS
UFS, FFS, Ext2FS, JFS, inodes, buffer cache, labeling, locking, metadata, soft-updates, LFS, portalfs, procfs,
vnodes, memory sharing, memory objects, TLBs, caching
68
VI. Interprocess Communication
Chapter 12 Signals
Signals, pipes, semaphores, message queues, shared memory, ports, sockets, doors
70
VII. Networking
Chapter 13 Sockets
This chapter was written by G. Adam Stanislav. <[email protected]>
13.1 Synopsis
BSD sockets take interprocess communications to a new level. It is no longer necessary for the communicating
processes to run on the same machine. They still can, but they do not have to.
Not only do these processes not have to run on the same machine, they do not have to run under the same operating
system. Thanks to BSD sockets, your FreeBSD software can smoothly cooperate with a program running on a
Macintosh, another one running on a Sun workstation, yet another one running under Windows 2000, all connected
with an Ethernet-based local area network.
But your software can equally well cooperate with processes running in another building, or on another continent,
inside a submarine, or a space shuttle.
It can also cooperate with processes that are not part of a computer (at least not in the strict sense of the word), but of
such devices as printers, digital cameras, medical equipment. Just about anything capable of digital communications.
72
Chapter 13 Sockets
13.3 Protocols
While various programming languages tend to have complex syntax and use a number of multi-letter reserved words
(which makes them easy for the human programmer to understand), the languages of data communications tend to be
very terse. Instead of multi-byte words, they often use individual bits. There is a very convincing reason for it: While
data travels inside your computer at speeds approaching the speed of light, it often travels considerably slower
between two computers.
Because the languages used in data communications are so terse, we usually refer to them as protocols rather than
languages.
As data travels from one computer to another, it always uses more than one protocol. These protocols are layered.
The data can be compared to the inside of an onion: You have to peel off several layers of “skin” to get to the data.
This is best illustrated with a picture:
Ethernet
IP
TCP
HTTP
PNG
D A T A
In this example, we are trying to get an image from a web page we are connected to via an Ethernet.
The image consists of raw data, which is simply a sequence of RGB values that our software can process, i.e.,
convert into an image and display on our monitor.
Alas, our software has no way of knowing how the raw data is organized: Is it a sequence of RGB values, or a
sequence of grayscale intensities, or perhaps of CMYK encoded colors? Is the data represented by 8-bit quanta, or
are they 16 bits in size, or perhaps 4 bits? How many rows and columns does the image consist of? Should certain
pixels be transparent?
I think you get the picture...
To inform our software how to handle the raw data, it is encoded as a PNG file. It could be a GIF, or a JPEG, but it is
a PNG.
And PNG is a protocol.
At this point, I can hear some of you yelling, “No, it is not! It is a file format!”
Well, of course it is a file format. But from the perspective of data communications, a file format is a protocol: The
file structure is a language, a terse one at that, communicating to our process how the data is organized. Ergo, it is a
protocol.
73
Chapter 13 Sockets
Alas, if all we received was the PNG file, our software would be facing a serious problem: How is it supposed to
know the data is representing an image, as opposed to some text, or perhaps a sound, or what not? Secondly, how is it
supposed to know the image is in the PNG format as opposed to GIF, or JPEG, or some other image format?
To obtain that information, we are using another protocol: HTTP. This protocol can tell us exactly that the data
represents an image, and that it uses the PNG protocol. It can also tell us some other things, but let us stay focused on
protocol layers here.
So, now we have some data wrapped in the PNG protocol, wrapped in the HTTP protocol. How did we get it from
the server?
By using TCP/IP over Ethernet, that is how. Indeed, that is three more protocols. Instead of continuing inside out, I
am now going to talk about Ethernet, simply because it is easier to explain the rest that way.
Ethernet is an interesting system of connecting computers in a local area network (LAN). Each computer has a
network interface card (NIC), which has a unique 48-bit ID called its address. No two Ethernet NICs in the world
have the same address.
These NICs are all connected with each other. Whenever one computer wants to communicate with another in the
same Ethernet LAN, it sends a message over the network. Every NIC sees the message. But as part of the Ethernet
protocol, the data contains the address of the destination NIC (among other things). So, only one of all the network
interface cards will pay attention to it, the rest will ignore it.
But not all computers are connected to the same network. Just because we have received the data over our Ethernet
does not mean it originated in our own local area network. It could have come to us from some other network (which
may not even be Ethernet based) connected with our own network via the Internet.
All data is transfered over the Internet using IP, which stands for Internet Protocol. Its basic role is to let us know
where in the world the data has arrived from, and where it is supposed to go to. It does not guarantee we will receive
the data, only that we will know where it came from if we do receive it.
Even if we do receive the data, IP does not guarantee we will receive various chunks of data in the same order the
other computer has sent it to us. So, we can receive the center of our image before we receive the upper left corner
and after the lower right, for example.
It is TCP (Transmission Control Protocol) that asks the sender to resend any lost data and that places it all into the
proper order.
All in all, it took five different protocols for one computer to communicate to another what an image looks like. We
received the data wrapped into the PNG protocol, which was wrapped into the HTTP protocol, which was wrapped
into the TCP protocol, which was wrapped into the IP protocol, which was wrapped into the Ethernet protocol.
Oh, and by the way, there probably were several other protocols involved somewhere on the way. For example, if our
LAN was connected to the Internet through a dial-up call, it used the PPP protocol over the modem which used one
(or several) of the various modem protocols, et cetera, et cetera, et cetera...
As a developer you should be asking by now, “How am I supposed to handle it all?”
74
Chapter 13 Sockets
Luckily for you, you are not supposed to handle it all. You are supposed to handle some of it, but not all of it.
Specifically, you need not worry about the physical connection (in our case Ethernet and possibly PPP, etc). Nor do
you need to handle the Internet Protocol, or the Transmission Control Protocol.
In other words, you do not have to do anything to receive the data from the other computer. Well, you do have to ask
for it, but that is almost as simple as opening a file.
Once you have received the data, it is up to you to figure out what to do with it. In our case, you would need to
understand the HTTP protocol and the PNG file structure.
To use an analogy, all the internetworking protocols become a gray area: Not so much because we do not understand
how it works, but because we are no longer concerned about it. The sockets interface takes care of this gray area for
us:
Ethernet
IP
TCP
HTTP
PNG
D A T A
We only need to understand any protocols that tell us how to interpret the data, not how to receive it from another
process, nor how to send it to another process.
75
Chapter 13 Sockets
13.5.1.1.1 socket
The one function used by both, clients and servers, is socket(2). It is declared this way:
The return value is of the same type as that of open, an integer. FreeBSD allocates its value from the same pool as
that of file handles. That is what allows sockets to be treated the same way as files.
The domain argument tells the system what protocol family you want it to use. Many of them exist, some are vendor
specific, others are very common. They are declared in sys/socket.h.
Use PF_INET for UDP, TCP and other Internet protocols (IPv4).
Five values are defined for the type argument, again, in sys/socket.h. All of them start with “SOCK_”. The most
common one is SOCK_STREAM, which tells the system you are asking for a reliable stream delivery service (which is
TCP when used with PF_INET).
If you asked for SOCK_DGRAM, you would be requesting a connectionless datagram delivery service (in our case,
UDP).
If you wanted to be in charge of the low-level protocols (such as IP), or even network interfaces (e.g., the Ethernet),
you would need to specify SOCK_RAW.
Finally, the protocol argument depends on the previous two arguments, and is not always meaningful. In that case,
use 0 for its value.
The Unconnected Socket: Nowhere, in the socket function have we specified to what other system we should
be connected. Our newly created socket remains unconnected.
This is on purpose: To use a telephone analogy, we have just attached a modem to the phone line. We have
neither told the modem to make a call, nor to answer if the phone rings.
13.5.1.1.2 sockaddr
Various functions of the sockets family expect the address of (or pointer to, to use C terminology) a small area of the
memory. The various C declarations in the sys/socket.h refer to it as struct sockaddr. This structure is
76
Chapter 13 Sockets
/*
* Structure used by kernel to store most
* addresses.
*/
struct sockaddr {
u_char sa_len; /* total length */
sa_family_t sa_family; /* address family */
char sa_data[14]; /* actually longer; address value */
};
#define SOCK_MAXADDRLEN 255 /* longest possible addresses */
Please note the vagueness with which the sa_data field is declared, just as an array of 14 bytes, with the comment
hinting there can be more than 14 of them.
This vagueness is quite deliberate. Sockets is a very powerful interface. While most people perhaps think of it as
nothing more than the Internet interface—and most applications probably use it for that nowadays—sockets can be
used for just about any kind of interprocess communications, of which the Internet (or, more precisely, IP) is only
one.
The sys/socket.h refers to the various types of protocols sockets will handle as address families, and lists them
right before the definition of sockaddr:
/*
* Address families.
*/
#define AF_UNSPEC 0 /* unspecified */
#define AF_LOCAL 1 /* local to host (pipes, portals) */
#define AF_UNIX AF_LOCAL /* backward compatibility */
#define AF_INET 2 /* internetwork: UDP, TCP, etc. */
#define AF_IMPLINK 3 /* arpanet imp addresses */
#define AF_PUP 4 /* pup protocols: e.g. BSP */
#define AF_CHAOS 5 /* mit CHAOS protocols */
#define AF_NS 6 /* XEROX NS protocols */
#define AF_ISO 7 /* ISO protocols */
#define AF_OSI AF_ISO
#define AF_ECMA 8 /* European computer manufacturers */
#define AF_DATAKIT 9 /* datakit protocols */
#define AF_CCITT 10 /* CCITT protocols, X.25 etc */
#define AF_SNA 11 /* IBM SNA */
#define AF_DECnet 12 /* DECnet */
#define AF_DLI 13 /* DEC Direct data link interface */
#define AF_LAT 14 /* LAT */
#define AF_HYLINK 15 /* NSC Hyperchannel */
77
Chapter 13 Sockets
#define AF_MAX 33
/*
* Socket address, internet style.
*/
struct sockaddr_in {
u_char sin_len;
u_char sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
78
Chapter 13 Sockets
0 1 2 3
0 0 Family Port
4 IP Address
8 0
12 0
The three important fields are sin_family, which is byte 1 of the structure, sin_port, a 16-bit value found in
bytes 2 and 3, and sin_addr, a 32-bit integer representation of the IP address, stored in bytes 4-7.
Now, let us try to fill it out. Let us assume we are trying to write a client for the daytime protocol, which simply states
that its server will write a text string representing the current date and time to port 13. We want to use TCP/IP, so we
need to specify AF_INET in the address family field. AF_INET is defined as 2. Let us use the IP address of
192.43.244.18, which is the time server of US federal government (time.nist.gov).
0 1 2 3
0 0 2 13
4 192.43.244.18
8 0
12 0
By the way the sin_addr field is declared as being of the struct in_addr type, which is defined in
netinet/in.h:
/*
* Internet address (a structure for historical reasons)
*/
struct in_addr {
in_addr_t s_addr;
};
sa.sin_family = AF_INET;
79
Chapter 13 Sockets
sa.sin_port = 13;
sa.sin_addr.s_addr = (((((192 << 8) | 43) << 8) | 244) << 8) | 18;
0 1 2 3
0 0 2 13 0
4 18 244 43 192
8 0
12 0
0 1 2 3
0 0 2 0 13
4 192 43 244 18
8 0
12 0
And on a PDP it might look different yet. But the above two are the most common ways in use today.
Ordinarily, wanting to write portable code, programmers pretend that these differences do not exist. And they get
away with it (except when they code in assembly language). Alas, you cannot get away with it that easily when
coding for sockets.
Why?
Because when communicating with another computer, you usually do not know whether it stores data most
significant byte (MSB) or least significant byte (LSB) first.
You might be wondering, “So, will sockets not handle it for me?”
It will not.
While that answer may surprise you at first, remember that the general sockets interface only understands the
sa_len and sa_family fields of the sockaddr structure. You do not have to worry about the byte order there (of
course, on FreeBSD sa_family is only 1 byte anyway, but many other Unix systems do not have sa_len and use 2
bytes for sa_family, and expect the data in whatever order is native to the computer).
80
Chapter 13 Sockets
But the rest of the data is just sa_data[14] as far as sockets goes. Depending on the address family, sockets just
forwards that data to its destination.
Indeed, when we enter a port number, it is because we want the other computer to know what service we are asking
for. And, when we are the server, we read the port number so we know what service the other computer is expecting
from us. Either way, sockets only has to forward the port number as data. It does not interpret it in any way.
Similarly, we enter the IP address to tell everyone on the way where to send our data to. Sockets, again, only
forwards it as data.
That is why, we (the programmers, not the sockets) have to distinguish between the byte order used by our computer
and a conventional byte order to send the data in to the other computer.
We will call the byte order our computer uses the host byte order, or just the host order.
There is a convention of sending the multi-byte data over IP MSB first. This, we will refer to as the network byte
order, or simply the network order.
Now, if we compiled the above code for an Intel based computer, our host byte order would produce:
0 1 2 3
0 0 2 13 0
4 18 244 43 192
8 0
12 0
But the network byte order requires that we store the data MSB first:
0 1 2 3
0 0 2 0 13
4 192 43 244 18
8 0
12 0
Unfortunately, our host order is the exact opposite of the network order.
We have several ways of dealing with it. One would be to reverse the values in our code:
sa.sin_family = AF_INET;
sa.sin_port = 13 << 8;
sa.sin_addr.s_addr = (((((18 << 8) | 244) << 8) | 43) << 8) | 192;
81
Chapter 13 Sockets
This will trick our compiler into storing the data in the network byte order. In some cases, this is exactly the way to
do it (e.g., when programming in assembly language). In most cases, however, it can cause a problem.
Suppose, you wrote a sockets-based program in C. You know it is going to run on a Pentium, so you enter all your
constants in reverse and force them to the network byte order. It works well.
Then, some day, your trusted old Pentium becomes a rusty old Pentium. You replace it with a system whose host
order is the same as the network order. You need to recompile all your software. All of your software continues to
perform well, except the one program you wrote.
You have since forgotten that you had forced all of your constants to the opposite of the host order. You spend some
quality time tearing out your hair, calling the names of all gods you ever heard of (and some you made up), hitting
your monitor with a nerf bat, and performing all the other traditional ceremonies of trying to figure out why
something that has worked so well is suddenly not working at all.
Eventually, you figure it out, say a couple of swear words, and start rewriting your code.
Luckily, you are not the first one to face the problem. Someone else has created the htons(3) and htonl(3) C functions
to convert a short and long respectively from the host byte order to the network byte order, and the ntohs(3) and
ntohl(3) C functions to go the other way.
On MSB-first systems these functions do nothing. On LSB-first systems they convert values to the proper order.
So, regardless of what system your software is compiled on, your data will end up in the correct order if you use
these functions.
13.5.1.2.1 connect
Once a client has created a socket, it needs to connect it to a specific port on a remote system. It uses connect(2):
The s argument is the socket, i.e., the value returned by the socket function. The name is a pointer to sockaddr,
the structure we have talked about extensively. Finaly, namelen informs the system how many bytes are in our
sockaddr structure.
If connect is successful, it returns 0. Otherwise it returns -1 and stores the error code in errno.
82
Chapter 13 Sockets
There are many reasons why connect may fail. For example, with an attempt to an Internet connection, the IP
address may not exist, or it may be down, or just too busy, or it may not have a server listening at the specified port.
Or it may outright refuse any request for specific code.
/*
* daytime.c
*
* Programmed by G. Adam Stanislav
*/
<
#include stdio.h >
<
#include sys/types.h >
<
#include sys/socket.h >
<
#include netinet/in.h >
int main() {
register int s;
register int bytes;
struct sockaddr_in sa;
char buffer[BUFSIZ+1];
sa.sin_family = AF_INET;
sa.sin_port = htons(13);
sa.sin_addr.s_addr = htonl((((((192 8) | 43) << << 8) | 244) << 8) | 18);
if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) {
perror("connect");
close(s);
return 2;
}
83
Chapter 13 Sockets
close(s);
return 0;
}
Go ahead, enter it in your editor, save it as daytime.c, then compile and run it:
In this case, the date was June 19, 2001, the time was 02:29:25 UTC. Naturally, your results will vary.
13.5.1.3.1 bind
Ports are like extensions to a phone line: After you dial a number, you dial the extension to get to a specific person or
department.
There are 65535 IP ports, but a server usually processes requests that come in on only one of them. It is like telling
the phone room operator that we are now at work and available to answer the phone at a specific extension. We use
bind(2) to tell sockets which port we want to serve.
Beside specifying the port in addr, the server may include its IP address. However, it can just use the symbolic
constant INADDR_ANY to indicate it will serve all requests to the specified port regardless of what its IP address is.
This symbol, along with several similar ones, is declared in netinet/in.h
Suppose we were writing a server for the daytime protocol over TCP/IP. Recall that it uses port 13. Our
sockaddr_in structure would look like this:
84
Chapter 13 Sockets
0 1 2 3
0 0 2 0 13
4 0
8 0
12 0
13.5.1.3.2 listen
To continue our office phone analogy, after you have told the phone central operator what extension you will be at,
you now walk into your office, and make sure your own phone is plugged in and the ringer is turned on. Plus, you
make sure your call waiting is activated, so you can hear the phone ring even while you are talking to someone.
The server ensures all of that with the listen(2) function.
In here, the backlog variable tells sockets how many incoming requests to accept while you are busy processing the
last request. In other words, it determines the maximum size of the queue of pending connections.
13.5.1.3.3 accept
After you hear the phone ringing, you accept the call by answering the call. You have now established a connection
with your client. This connection remains active until either you or your client hang up.
The server accepts the connection by using the accept(2) function.
Note that this time addrlen is a pointer. This is necessary because in this case it is the socket that fills out addr, the
sockaddr_in structure.
The return value is an integer. Indeed, the accept returns a new socket. You will use this new socket to communicate
with the client.
What happens to the old socket? It continues to listen for more requests (remember the backlog variable we passed
to listen?) until we close it.
Now, the new socket is meant only for communications. It is fully connected. We cannot pass it to listen again,
trying to accept additional connections.
85
Chapter 13 Sockets
/*
* daytimed - a port 13 server
*
* Programmed by G. Adam Stanislav
* June 19, 2001
*/
<
#include stdio.h >
<
#include time.h >
<
#include unistd.h >
<
#include sys/types.h >
<
#include sys/socket.h >
<
#include netinet/in.h >
#define BACKLOG 4
int main() {
register int s, c;
int b;
struct sockaddr_in sa;
time_t t;
struct tm *tm;
FILE *client;
sa.sin_family = AF_INET;
sa.sin_port = htons(13);
if (INADDR_ANY)
sa.sin_addr.s_addr = htonl(INADDR_ANY);
86
Chapter 13 Sockets
switch (fork()) {
case -1:
perror("fork");
return 3;
break;
default:
close s;
return 0;
break;
case 0:
break;
}
listen(s, BACKLOG);
for (;;) {
b = sizeof sa;
return 6;
}
tm = gmtime(&t);
fprintf(client, "%.4i-%.2i-%.2iT%.2i:%.2i:%.2iZ\n",
tm->tm_year + 1900,
tm->tm_mon + 1,
tm->tm_mday,
87
Chapter 13 Sockets
tm->tm_hour,
tm->tm_min,
tm->tm_sec);
fclose(client);
}
}
We start by creating a socket. Then we fill out the sockaddr_in structure in sa. Note the conditional use of
INADDR_ANY:
if (INADDR_ANY)
sa.sin_addr.s_addr = htonl(INADDR_ANY);
Its value is 0. Since we have just used bzero on the entire structure, it would be redundant to set it to 0 again. But if
we port our code to some other system where INADDR_ANY is perhaps not a zero, we need to assign it to
sa.sin_addr.s_addr. Most modern C compilers are clever enough to notice that INADDR_ANY is a constant.
As long as it is a zero, they will optimize the entire conditional statement out of the code.
After we have called bind successfully, we are ready to become a daemon: We use fork to create a child process. In
both, the parent and the child, the s variable is our socket. The parent process will not need it, so it calls close, then
it returns 0 to inform its own parent it had terminated successfully.
Meanwhile, the child process continues working in the background. It calls listen and sets its backlog to 4. It does
not need a large value here because daytime is not a protocol many clients request all the time, and because it can
process each request instantly anyway.
Finally, the daemon starts an endless loop, which performs the following steps:
1. Call accept. It waits here until a client contacts it. At that point, it receives a new socket, c, which it can use to
communicate with this particular client.
2. It uses the C function fdopen to turn the socket from a low-level file descriptor to a C-style FILE pointer. This
will allow the use of fprintf later on.
3. It checks the time, and prints it in the ISO 8601 format to the client “file”. It then uses fclose to close the
file. That will automatically close the socket as well.
We can generalize this, and use it as a model for many other servers:
88
Chapter 13 Sockets
Start
Daemon
Bind Port Process
Initialize Daemon
Exit
Accept
Serve
Close Accepted
Socket
This flowchart is good for sequential servers, i.e., servers that can serve one client at a time, just as we were able to
with our daytime server. This is only possible whenever there is no real “conversation” going on between the client
and the server: As soon as the server detects a connection to the client, it sends out some data and closes the
connection. The entire operation may take nanoseconds, and it is finished.
The advantage of this flowchart is that, except for the brief moment after the parent forks and before it exits, there is
always only one process active: Our server does not take up much memory and other system resources.
Note that we have added initialize daemon in our flowchart. We did not need to initialize our own daemon, but this is
89
Chapter 13 Sockets
a good place in the flow of the program to set up any signal handlers, open any files we may need, etc.
Just about everything in the flow chart can be used literally on many different servers. The serve entry is the
exception. We think of it as a “black box”, i.e., something you design specifically for your own server, and just “plug
it into the rest.”
Not all protocols are that simple. Many receive a request from the client, reply to it, then receive another request
from the same client. Because of that, they do not know in advance how long they will be serving the client. Such
servers usually start a new process for each client. While the new process is serving its client, the daemon can
continue listening for more connections.
Now, go ahead, save the above source code as daytimed.c (it is customary to end the names of daemons with the
letter d). After you have compiled it, try running it:
% ./daytimed
bind: Permission denied
%
What happened here? As you will recall, the daytime protocol uses port 13. But all ports below 1024 are reserved to
the superuser (otherwise, anyone could start a daemon pretending to serve a commonly used port, while causing a
security breach).
Try again, this time as the superuser:
# ./daytimed
#
# ./daytimed
Every port can only be bound by one program at a time. Our first attempt was indeed successful: It started the child
daemon and returned quietly. It is still running and will continue to run until you either kill it, or any of its system
calls fail, or you reboot the system.
Fine, we know it is running in the background. But is it working? How do we know it is a proper daytime server?
Simple:
% telnet localhost 13
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
90
Chapter 13 Sockets
telnet tried the new IPv6, and failed. It retried with IPv4 and succeeded. The daemon works.
If you have access to another Unix system via telnet, you can use it to test accessing the server remotely. My
computer does not have a static IP address, so this is what I did:
% who
Trying 216.127.220.143...
Connected to r47.bfm.org.
Escape character is ’^]’.
2001-06-19T21:31:11Z
Connection closed by foreign host.
%
% telnet r47.bfm.org 13
Trying 216.127.220.143...
Connected to r47.bfm.org.
Escape character is ’^]’.
2001-06-19T21:31:40Z
Connection closed by foreign host.
%
By the way, telnet prints the Connection closed by foreign host message after our daemon has closed the socket. This
shows us that, indeed, using fclose(client); in our code works as advertised.
91
Chapter 13 Sockets
13.6.1 gethostbyname
While there is no way to pass the domain name directly to any of the sockets functions, the FreeBSD C library comes
with the gethostbyname(3) and gethostbyname2(3) functions, declared in netdb.h.
Both return a pointer to the hostent structure, with much information about the domain. For our purposes, the
h_addr_list[0] field of the structure points at h_length bytes of the correct address, already stored in the
network byte order.
This allows us to create a much more flexible—and much more useful—version of our daytime program:
/*
* daytime.c
*
* Programmed by G. Adam Stanislav
* 19 June 2001
*/
<
#include stdio.h >
<
#include string.h >
<
#include sys/types.h >
<
#include sys/socket.h >
<
#include netinet/in.h >
<
#include netdb.h >
int main(int argc, char *argv[]) {
register int s;
register int bytes;
struct sockaddr_in sa;
struct hostent *he;
char buf[BUFSIZ+1];
char *host;
92
Chapter 13 Sockets
sa.sin_family = AF_INET;
sa.sin_port = htons(13);
>
bcopy(he- h_addr_list[0],&sa.sin_addr, he- h_length); >
if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) {
perror("connect");
return 3;
}
close(s);
return 0;
}
We now can type a domain name (or an IP address, it works both ways) on the command line, and the program will
try to connect to its daytime server. Otherwise, it will still default to time.nist.gov. However, even in this case we
will use gethostbyname rather than hard coding 192.43.244.18. That way, even if its IP address changes in the
future, we will still find it.
Since it takes virtually no time to get the time from your local server, you could run daytime twice in a row: First to
get the time from time.nist.gov, the second time from your own system. You can then compare the results and
see how exact your system clock is:
As you can see, my system was two seconds ahead of the NIST time.
93
Chapter 13 Sockets
13.6.2 getservbyname
Sometimes you may not be sure what port a certain service uses. The getservbyname(3) function, also declared in
netdb.h comes in very handy in those cases:
The servent structure contains the s_port, which contains the proper port, already in network byte order.
Had we not known the correct port for the daytime service, we could have found it this way:
You usually do know the port. But if you are developing a new protocol, you may be testing it on an unofficial port.
Some day, you will register the protocol and its port (if nowehere else, at least in your /etc/services, which is
where getservbyname looks). Instead of returning an error in the above code, you just use the temporary port
number. Once you have listed the protocol in /etc/services, your software will find its port without you having to
rewrite the code.
94
Chapter 13 Sockets
Start
Daemon
Bind Port Process
Initialize Daemon
Exit
Server
Accept Process
Close Top Socket
Close Accepted
Socket
Serve
Close Accepted
Socket
Process Signals
Exit
We moved the serve from the daemon process to its own server process. However, because each child process
inherits all open files (and a socket is treated just like a file), the new process inherits not only the “accepted
95
Chapter 13 Sockets
handle,” i.e., the socket returned by the accept call, but also the top socket, i.e., the one opened by the top process
right at the beginning.
However, the server process does not need this socket and should close it immediately. Similarly, the daemon
process no longer needs the accepted socket, and not only should, but must close it—otherwise, it will run out of
available file descriptors sooner or later.
After the server process is done serving, it should close the accepted socket. Instead of returning to accept, it now
exits.
Under Unix, a process does not really exit. Instead, it returns to its parent. Typically, a parent process waits for its
child process, and obtains a return value. However, our daemon process cannot simply stop and wait. That would
defeat the whole purpose of creating additional processes. But if it never does wait, its children will become
zombies—no loger functional but still roaming around.
For that reason, the daemon process needs to set signal handlers in its initialize daemon phase. At least a SIGCHLD
signal has to be processed, so the daemon can remove the zombie return values from the system and release the
system resources they are taking up.
That is why our flowchart now contains a process signals box, which is not connected to any other box. By the way,
many servers also process SIGHUP, and typically interpret as the signal from the superuser that they should reread
their configuration files. This allows us to change settings without having to kill and restart these servers.
96
Chapter 14 IPv6 Internals
14.1.1 IPv6
14.1.1.1 Conformance
The IPv6 related functions conforms, or tries to conform to the latest set of IPv6 specifications. For future reference
we list some of the relevant documents below (NOTE: this is not a complete list - this is too hard to maintain...).
For details please refer to specific chapter in the document, RFCs, manpages, or comments in the source code.
Conformance tests have been performed on the KAME STABLE kit at TAHI project. Results can be viewed at
http://www.tahi.org/report/KAME/ (http://www.tahi.org/report/KAME/). We also attended Univ. of New Hampshire
IOL tests (http://www.iol.unh.edu/) in the past, with our past snapshots.
97
Chapter 14 IPv6 Internals
98
Chapter 14 IPv6 Internals
99
Chapter 14 IPv6 Internals
1. when there was no neighbor cache entry, node received unsolicited RS/NS/NA/redirect packet without link-layer
address
2. neighbor cache handling on medium without link-layer address (we need a neighbor cache entry for IsRouter bit)
For first case, we implemented workaround based on discussions on IETF ipngwg mailing list. For more details, see
the comments in the source code and email thread started from (IPng 7155), dated Feb 6 1999.
IPv6 on-link determination rule (RFC2461) is quite different from assumptions in BSD network code. At this
moment, no on-link determination rule is supported where default router list is empty (RFC2461, section 5.2, last
sentence in 2nd paragraph - note that the spec misuse the word "host" and "node" in several places in the section).
To avoid possible DoS attacks and infinite loops, only 10 options on ND packet is accepted now. Therefore, if you
have 20 prefix options attached to RA, only the first 10 prefixes will be recognized. If this troubles you, please ask it
on FREEBSD-CURRENT mailing list and/or modify nd6_maxndopt in sys/netinet6/nd6.c. If there are high
demands we may provide sysctl knob for the variable.
100
Chapter 14 IPv6 Internals
In the kernel, an interface index for link-local scoped address is embedded into 2nd 16bit-word (3rd and 4th byte) in
IPv6 address. For example, you may see something like:
fe80:1::200:f8ff:fe01:6317
in the routing table and interface address structure (struct in6_ifaddr). The address above is a link-local unicast
address which belongs to a network interface whose interface identifier is 1. The embedded index enables us to
identify IPv6 link local addresses over multiple interfaces effectively and with only a little code change.
Routing daemons and configuration programs, like route6d(8) and ifconfig(8), will need to manipulate the
"embedded" scope index. These programs use routing sockets and ioctls (like SIOCGIFADDR_IN6) and the kernel
API will return IPv6 addresses with 2nd 16bit-word filled in. The APIs are for manipulating kernel internal structure.
Programs that use these APIs have to be prepared about differences in kernels anyway.
When you specify scoped address to the command line, NEVER write the embedded form (such as ff02:1::1 or
fe80:2::fedc). This is not supposed to work. Always use standard form, like ff02::1 or fe80::fedc, with command line
option for specifying interface (like ping6 -I ne0 ff02::1). In general, if a command does not have command
line option to specify outgoing interface, that command is not ready to accept scoped address. This may seem to be
opposite from IPv6’s premise to support "dentist office" situation. We believe that specifications need some
improvements for this.
Some of the userland tools support extended numeric IPv6 syntax, as documented in
draft-ietf-ipngwg-scopedaddr-format-00.txt. You can specify outgoing link, by using name of the
outgoing interface like "fe80::1%ne0". This way you will be able to specify link-local scoped address without much
trouble.
To use this extension in your program, you’ll need to use getaddrinfo(3), and getnameinfo(3) with
NI_WITHSCOPEID. The implementation currently assumes 1-to-1 relationship between a link and an interface,
which is stronger than what specs say.
101
Chapter 14 IPv6 Internals
Internet6:
Destination Gateway Flags Netif Expire
fe80:1::%ed0/64 link#1 UC ed0
fe80:2::%ep0/64 link#2 UC ep0
Interfaces that has no IEEE802 address (pseudo interfaces like tunnel interfaces, or ppp interfaces) will borrow
IEEE802 address from other interfaces, such as ethernet interfaces, whenever possible. If there is no IEEE802
hardware attached, last-resort pseudorandom value, which is from MD5(hostname), will be used as source of
link-local address. If it is not suitable for your usage, you will need to configure the link-local address manually.
If an interface is not capable of handling IPv6 (such as lack of multicast support), link-local address will not be
assigned to that interface. See section 2 for details.
Each interface joins the solicited multicast address and the link-local all-nodes multicast addresses (e.g.
fe80::1:ff01:6317 and ff02::1, respectively, on the link the interface is attached). In addition to a link-local address,
the loopback address (::1) will be assigned to the loopback interface. Also, ::1/128 and ff01::/32 are automatically
added to routing table, and loopback interface joins node-local multicast group ff01::1.
102
Chapter 14 IPv6 Internals
RFC2462 has validation rule against incoming RA prefix information option, in 5.5.3 (e). This is to protect hosts
from malicious (or misconfigured) routers that advertise very short prefix lifetime. There was an update from Jim
Bound to ipngwg mailing list (look for "(ipng 6712)" in the archive) and it is implemented Jim’s update.
See 23.5.1.2 in the document for relationship between DAD and autoconfiguration.
• v6 in v6
• v6 in v4
• v4 in v6
• v4 in v4
are available. Use gifconfig(8) to assign physical (outer) source and destination address to gif interfaces.
Configuration that uses same address family for inner and outer IP header (v4 in v4, or v6 in v6) is dangerous. It is
very easy to configure interfaces and routing tables to perform infinite level of tunneling. Please be warned.
gif can be configured to be ECN-friendly. See 23.5.4.5 for ECN-friendliness of tunnels, and gif(4) for how to
configure.
If you would like to configure an IPv4-in-IPv6 tunnel with gif interface, read gif(4) carefully. You will need to
remove IPv6 link-local address automatically assigned to the gif interface.
103
Chapter 14 IPv6 Internals
1. If the source address is explicitly specified by the user (e.g. via the advanced API), the specified address is used.
2. If there is an address assigned to the outgoing interface (which is usually determined by looking up the routing
table) that has the same scope as the destination address, the address is used.
This is the most typical case.
3. If there is no address that satisfies the above condition, choose a global address assigned to one of the interfaces
on the sending node.
4. If there is no address that satisfies the above condition, and destination address is site local scope, choose a site
local address assigned to one of the interfaces on the sending node.
5. If there is no address that satisfies the above condition, choose the address associated with the routing table entry
for the destination. This is the last resort, which may cause scope violation.
For instance, ::1 is selected for ff01::1, fe80:1::200:f8ff:fe01:6317 for fe80:1::2a0:24ff:feab:839b (note that
embedded interface index - described in 23.5.1.3 - helps us choose the right source address. Those embedded indices
will not be on the wire). If the outgoing interface has multiple address for the scope, a source is selected longest
match basis (rule 3). Suppose 3ffe:501:808:1:200:f8ff:fe01:6317 and 3ffe:2001:9:124:200:f8ff:fe01:6317 are given to
the outgoing interface. 3ffe:501:808:1:200:f8ff:fe01:6317 is chosen as the source for the destination 3ffe:501:800::1.
Note that the above rule is not documented in the IPv6 spec. It is considered "up to implementation" item. There are
some cases where we do not use the above rule. One example is connected TCP session, and we use the address kept
in tcb as the source. Another example is source address for Neighbor Advertisement. Under the spec (RFC2461
7.2.2) NA’s source should be the target address of the corresponding NS’s target. In this case we follow the spec
rather than the above longest-match rule.
For new connections (when rule 1 does not apply), deprecated addresses (addresses with preferred lifetime = 0) will
not be chosen as source address if other choices are available. If no other choices are available, deprecated address
will be used as a last resort. If there are multiple choice of deprecated addresses, the above scope rule will be used to
choose from those deprecated addresses. If you would like to prohibit the use of deprecated address for some reason,
configure net.inet6.ip6.use_deprecated to 0. The issue related to deprecated address is described in RFC2462 5.5.4
(NOTE: there is some debate underway in IETF ipngwg on how to use "deprecated" address).
104
Chapter 14 IPv6 Internals
% netstat -s -p ip6
ip6:
(snip)
1 with data size < data length
So, kernel does not send an ICMPv6 error unless the erroneous packet is an actual Jumbo Payload, that is, its packet
size is more than 65,535 bytes. As described above, currently no physical interface with such a huge MTU is
supported, so it rarely returns an ICMPv6 error.
TCP/UDP over jumbogram is not supported at this moment. This is because we have no medium (other than
loopback) to test this. Contact us if you need this.
IPsec does not work on jumbograms. This is due to some specification twists in supporting AH with jumbograms
(AH header size influences payload length, and this makes it real hard to authenticate inbound packet with jumbo
payload option as well as AH).
There are fundamental issues in *BSD support for jumbograms. We would like to address those, but we need more
time to finalize these. To name a few:
• mbuf pkthdr.len field is typed as "int" in 4.4BSD, so it will not hold jumbogram with len > 2G on 32bit
architecture CPUs. If we would like to support jumbogram properly, the field must be expanded to hold 4G + IPv6
header + link-layer header. Therefore, it must be expanded to at least int64_t (u_int32_t is NOT enough).
105
Chapter 14 IPv6 Internals
• We mistakingly use "int" to hold packet length in many places. We need to convert them into larger integral type.
It needs a great care, as we may experience overflow during packet length computation.
• We mistakingly check for ip6_plen field of IPv6 header for packet payload length in various places. We should be
checking mbuf pkthdr.len instead. ip6_input() will perform sanity check on jumbo payload option on input, and
we can safely use mbuf pkthdr.len afterwards.
• TCP code needs a careful update in bunch of places, of course.
14.1.1.9 ICMPv6
After RFC2463 was published, IETF ipngwg has decided to disallow ICMPv6 error packet against ICMPv6 redirect,
to prevent ICMPv6 storm on a network medium. This is already implemented into the kernel.
14.1.1.10 Applications
For userland programming, we support IPv6 socket API as specified in RFC2553, RFC2292 and upcoming internet
drafts.
TCP/UDP over IPv6 is available and quite stable. You can enjoy telnet(1), ftp(1), rlogin(1), rsh(1), ssh(1), etc. These
applications are protocol independent. That is, they automatically chooses IPv4 or IPv6 according to DNS.
106
Chapter 14 IPv6 Internals
ICMPv6 should contain the original packet as long as possible up to 1280. UDP6/IP6 port unreach, for instance,
should contain all extension headers and the *unchanged* UDP6 and IP6 headers. So, all IP6 functions except TCP
never convert network byte order into host byte order, to save the original packet.
tcp_input(), udp6_input() and icmp6_input() can’t assume that IP6 header is preceding the transport headers due to
extension headers. So, in6_cksum() was implemented to handle packets whose IP6 header and transport header is not
continuous. TCP/IP6 nor UDP6/IP6 header structure don’t exist for checksum calculation.
To process IP6 header, extension headers and transport headers easily, network drivers are now required to store
packets in one internal mbuf or one or more external mbufs. A typical old driver prepares two internal mbufs for 96 -
204 bytes data, however, now such packet data is stored in one external mbuf.
netstat -s -p ip6 tells you whether or not your driver conforms such requirement. In the following example,
"cce0" violates the requirement. (For more information, refer to Section 2.)
Mbuf statistics:
317 one mbuf
two or more mbuf::
lo0 = 8
cce0 = 10
3282 one ext mbuf
0 two or more ext mbuf
Each input function calls IP6_EXTHDR_CHECK in the beginning to check if the region between IP6 and its header
is continuous. IP6_EXTHDR_CHECK calls m_pullup() only if the mbuf has M_LOOP flag, that is, the packet
comes from the loopback interface. m_pullup() is never called for packets coming from physical network interfaces.
Both IP and IP6 reassemble functions never call m_pullup().
107
Chapter 14 IPv6 Internals
The following sections will give you more details, and how you can configure the behavior.
Comments on listening side:
It looks that RFC2553 talks too little on wildcard bind issue, especially on the port space issue, failure mode and
relationship between AF_INET/INET6 wildcard bind. There can be several separate interpretation for this RFC
which conform to it but behaves differently. So, to implement portable application you should assume nothing about
the behavior in the kernel. Using getaddrinfo(3) is the safest way. Port number space and wildcard bind issues were
discussed in detail on ipv6imp mailing list, in mid March 1999 and it looks that there’s no concrete consensus
(means, up to implementers). You may want to check the mailing list archives.
If a server application would like to accept IPv4 and IPv6 connections, there will be two alternatives.
One is using AF_INET and AF_INET6 socket (you’ll need two sockets). Use getaddrinfo(3) with AI_PASSIVE into
ai_flags, and socket(2) and bind(2) to all the addresses returned. By opening multiple sockets, you can accept
connections onto the socket with proper address family. IPv4 connections will be accepted by AF_INET socket, and
IPv6 connections will be accepted by AF_INET6 socket.
Another way is using one AF_INET6 wildcard bind socket. Use getaddrinfo(3) with AI_PASSIVE into ai_flags and
with AF_INET6 into ai_family, and set the 1st argument hostname to NULL. And socket(2) and bind(2) to the
address returned. (should be IPv6 unspecified addr). You can accept either of IPv4 and IPv6 packet via this one
socket.
To support only IPv6 traffic on AF_INET6 wildcard binded socket portably, always check the peer address when a
connection is made toward AF_INET6 listening socket. If the address is IPv4 mapped address, you may want to
reject the connection. You can check the condition by using IN6_IS_ADDR_V4MAPPED() macro.
To resolve this issue more easily, there is system dependent setsockopt(2) option, IPV6_BINDV6ONLY, used like
below.
int on;
When this call succeed, then this socket only receive IPv6 packets.
Comments on initiating side:
108
Chapter 14 IPv6 Internals
Advise to application implementers: to implement a portable IPv6 application (which works on multiple IPv6
kernels), we believe that the following is the key to the success:
• By default, AF_INET6 socket will grab IPv4 connections in certain condition, and can initiate connection to IPv4
destination embedded in IPv4 mapped IPv6 address.
• You can disable it on entire system with sysctl like below.
sysctl -w net.inet6.ip6.mapped_addr=0
109
Chapter 14 IPv6 Internals
int on;
Wildcard AF_INET6 socket grabs IPv4 connection if and only if the following conditions are satisfied:
14.1.1.13 sockaddr_storage
When RFC2553 was about to be finalized, there was discussion on how struct sockaddr_storage members are named.
One proposal is to prepend "__" to the members (like "__ss_len") as they should not be touched. The other proposal
was that don’t prepend it (like "ss_len") as we need to touch those members directly. There was no clear consensus
on it.
As a result, RFC2553 defines struct sockaddr_storage as follows:
struct sockaddr_storage {
u_char __ss_len; /* address length */
u_char __ss_family; /* address family */
/* and bunch of padding */
};
struct sockaddr_storage {
u_char ss_len; /* address length */
u_char ss_family; /* address family */
/* and bunch of padding */
};
110
Chapter 14 IPv6 Internals
In December 1999, it was agreed that RFC2553bis should pick the latter (XNET) definition.
Current implementation conforms to XNET definition, based on RFC2553bis discussion.
If you look at multiple IPv6 implementations, you will be able to see both definitions. As an userland programmer,
the most portable way of dealing with it is to:
1. ensure ss_family and/or ss_len are available on the platform, by using GNU autoconf,
2. have -Dss_family=__ss_family to unify all occurrences (including header file) into __ss_family, or
3. never touch __ss_family. cast to sockaddr * and use sa_family like:
struct sockaddr_storage ss;
family = ((struct sockaddr *)&ss)->sa_family
1. mbuf clustering requirement. In this stable release, we changed MINCLSIZE into MHLEN+1 for all the
operating systems in order to make all the drivers behave as we expect.
2. multicast. If ifmcstat(8) yields no multicast group for a interface, that interface has to be patched.
If any of the driver don’t support the requirements, then the driver can’t be used for IPv6 and/or IPsec
communication. If you find any problem with your card using IPv6/IPsec, then, please report it to
<[email protected]>.
(NOTE: In the past we required all PCMCIA drivers to have a call to in6_ifattach(). We have no such requirement
any more)
14.1.3 Translator
We categorize IPv4/IPv6 translator into 4 types:
• Translator A --- It is used in the early stage of transition to make it possible to establish a connection from an IPv6
host in an IPv6 island to an IPv4 host in the IPv4 ocean.
111
Chapter 14 IPv6 Internals
• Translator B --- It is used in the early stage of transition to make it possible to establish a connection from an IPv4
host in the IPv4 ocean to an IPv6 host in an IPv6 island.
• Translator C --- It is used in the late stage of transition to make it possible to establish a connection from an IPv4
host in an IPv4 island to an IPv6 host in the IPv6 ocean.
• Translator D --- It is used in the late stage of transition to make it possible to establish a connection from an IPv6
host in the IPv6 ocean to an IPv4 host in an IPv4 island.
TCP relay translator for category A is supported. This is called "FAITH". We also provide IP header translator for
category A. (The latter is not yet put into FreeBSD 4.x yet.)
14.1.4 IPsec
IPsec is mainly organized by three components.
1. Policy Management
2. Key Management
3. AH and ESP handling
112
Chapter 14 IPv6 Internals
• IPsec tunnel is not combined with GIF generic tunneling interface. It needs a great care because we may create an
infinite loop between ip_output() and tunnelifp->if_output(). Opinion varies if it is better to unify them, or not.
• MTU and Don’t Fragment bit (IPv4) considerations need more checking, but basically works fine.
• Authentication model for AH tunnel must be revisited. We’ll need to improve the policy management engine,
eventually.
113
Chapter 14 IPv6 Internals
• old IPsec AH
• null crypto checksum (no document, just for debugging)
• keyed MD5 with 128bit crypto checksum (rfc1828.txt)
• keyed SHA1 with 128bit crypto checksum (no document)
• HMAC MD5 with 128bit crypto checksum (rfc2085.txt)
• HMAC SHA1 with 128bit crypto checksum (no document)
• new IPsec AH
• null crypto checksum (no document, just for debugging)
• keyed MD5 with 96bit crypto checksum (no document)
• keyed SHA1 with 96bit crypto checksum (no document)
• HMAC MD5 with 96bit crypto checksum (rfc2403.txt)
• HMAC SHA1 with 96bit crypto checksum (rfc2404.txt)
114
Chapter 14 IPv6 Internals
• old IPsec AH
• HMAC MD5 with 128bit crypto checksum + 64bit replay prevention (rfc2085.txt)
• keyed SHA1 with 160bit crypto checksum + 32bit padding (rfc1852.txt)
IPsec (in kernel) and IKE (in userland as "racoon") has been tested at several interoperability test events, and it is
known to interoperate with many other implementations well. Also, current IPsec implementation as quite wide
coverage for IPsec crypto algorithms documented in RFC (we cover algorithms without intellectual property issues
only).
115
Chapter 14 IPv6 Internals
encapsulate decapsulate
--- ---
RFC2401 copy all TOS bits drop TOS bits on outer
from inner to outer. (use inner TOS bits as is)
ECN forbidden copy TOS bits except for ECN drop TOS bits on outer
(masked with 0xfc) from inner (use inner TOS bits as is)
to outer. set ECN bits to 0.
ECN allowed copy TOS bits except for ECN use inner TOS bits with some
CE (masked with 0xfe) from change. if outer ECN CE bit
inner to outer. is 1, enable ECN CE bit on
set ECN CE bit to 0. the inner.
• if both IPsec tunnel endpoint are capable of ECN-friendly behavior, you’d better configure both end to "ECN
allowed" (sysctl value 1).
• if the other end is very strict about TOS bit, use "RFC2401" (sysctl value -1).
• in other cases, use "ECN forbidden" (sysctl value 0).
The default behavior is "ECN forbidden" (sysctl value 0).
For more information, please refer to:
http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt (http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt),
RFC2481 (Explicit Congestion Notification), src/sys/netinet6/{ah,esp}_input.c
(Thanks goes to Kenjiro Cho <[email protected]> for detailed analysis)
14.1.4.6 Interoperability
Here are (some of) platforms that KAME code have tested IPsec/IKE interoperability in the past. Note that both ends
may have modified their implementation, so use the following list just for reference purposes.
116
Chapter 14 IPv6 Internals
Altiga, Ashley-laurent (vpcom.com), Data Fellows (F-Secure), Ericsson ACC, FreeS/WAN, HITACHI, IBM AIX,
IIJ, Intel, Microsoft WinNT, NIST (linux IPsec + plutoplus), Netscreen, OpenBSD, RedCreek, Routerware, SSH,
Secure Computing, Soliton, Toshiba, VPNet, Yamaha RT100i
117
VIII. Network Filesystems
Chapter 15 AFS
AFS, NFS, SANs etc]
119
IX. Terminal Handling
Chapter 16 Syscons
Syscons, tty, PCVT, serial console, screen savers, etc
121
X. Sound
Chapter 17 OSS
OSS, waveforms, etc
123
XI. Device Drivers
Chapter 18 Writing FreeBSD Device Drivers
This chapter was written by Murray Stokely <[email protected]> with selections from a variety of sources
including the intro(4) man page by Jörg Wunsch <[email protected]>.
18.1 Introduction
This chapter provides a brief introduction to writing device drivers for FreeBSD. A device in this context is a term
used mostly for hardware-related stuff that belongs to the system, like disks, printers, or a graphics display with its
keyboard. A device driver is the software component of the operating system that controls a specific device. There
are also so-called pseudo-devices where a device driver emulates the behaviour of a device in software without any
particular underlying hardware. Device drivers can be compiled into the system statically or loaded on demand
through the dynamic kernel linker facility ‘kld’.
Most devices in a Unix-like operating system are accessed through device-nodes, sometimes also called special files.
These files are usually located under the directory /dev in the file system hierarchy. Until devfs is fully integrated
into FreeBSD, each device node must be created statically and independent of the existence of the associated device
driver. Most device nodes on the system are created by running MAKEDEV.
Device drivers can roughly be broken down into two categories; character and network device drivers.
/*
* KLD Skeleton
* Inspired by Andrew Reiter’s Daemonnews article
125
Chapter 18 Writing FreeBSD Device Drivers
*/
#include <sys/types.h>
#include <sys/module.h>
#include <sys/systm.h> /* uprintf */
#include <sys/errno.h>
#include <sys/param.h> /* defines used in kernel.h */
#include <sys/kernel.h> /* types used in module initialization */
/*
* Load handler that deals with the loading and unloading of a KLD.
*/
static int
skel_loader(struct module *m, int what, void *arg)
{
int err = 0;
switch (what) {
case MOD_LOAD: /* kldload */
uprintf("Skeleton KLD loaded.\n");
break;
case MOD_UNLOAD:
uprintf("Skeleton KLD unloaded.\n");
break;
default:
err = EINVAL;
break;
}
return(err);
}
18.2.1 Makefile
FreeBSD provides a makefile include that you can use to quickly compile your kernel addition.
SRCS=skeleton.c
KMOD=skeleton
.include <bsd.kmod.mk>
126
Chapter 18 Writing FreeBSD Device Drivers
Simply running make with this makefile will create a file skeleton.ko that can be loaded into your system by
typing :
# kldload -v ./skeleton.ko
/*
* Simple ‘echo’ pseudo-device KLD
*
127
Chapter 18 Writing FreeBSD Device Drivers
* Murray Stokely
*/
#include <sys/types.h>
#include <sys/module.h>
#include <sys/systm.h> /* uprintf */
#include <sys/errno.h>
#include <sys/param.h> /* defines used in kernel.h */
#include <sys/kernel.h> /* types used in module initialization */
#include <sys/conf.h> /* cdevsw struct */
#include <sys/uio.h> /* uio struct */
#include <sys/malloc.h>
#define BUFFERSIZE 256
/* Function prototypes */
d_open_t echo_open;
d_close_t echo_close;
d_read_t echo_read;
d_write_t echo_write;
128
Chapter 18 Writing FreeBSD Device Drivers
/* vars */
static dev_t sdev;
static int len;
static int count;
static t_echo *echomsg;
MALLOC_DECLARE(M_ECHOBUF);
MALLOC_DEFINE(M_ECHOBUF, "echobuffer", "buffer for echo module");
/*
* This function acts is called by the kld[un]load(2) system calls to
* determine what actions to take when a module is loaded or unloaded.
*/
static int
echo_loader(struct module *m, int what, void *arg)
{
int err = 0;
switch (what) {
case MOD_LOAD: /* kldload */
sdev = make_dev(&echo_cdevsw,
0,
UID_ROOT,
GID_WHEEL,
0600,
"echo");
/* kmalloc memory for use by this driver */
/* malloc(256,M_ECHOBUF,M_WAITOK); */
MALLOC(echomsg, t_echo *, sizeof(t_echo), M_ECHOBUF, M_WAITOK);
printf("Echo device loaded.\n");
break;
case MOD_UNLOAD:
destroy_dev(sdev);
FREE(echomsg,M_ECHOBUF);
printf("Echo device unloaded.\n");
break;
default:
err = EINVAL;
break;
}
return(err);
}
129
Chapter 18 Writing FreeBSD Device Drivers
int
echo_open(dev_t dev, int oflags, int devtype, struct proc *p)
{
int err = 0;
int
echo_close(dev_t dev, int fflag, int devtype, struct proc *p)
{
uprintf("Closing device \"echo.\"\n");
return(0);
}
/*
* The read function just takes the buf that was saved via
* echo_write() and returns it to userland for accessing.
* uio(9)
*/
int
echo_read(dev_t dev, struct uio *uio, int ioflag)
{
int err = 0;
int amt;
/* How big is this read operation? Either as big as the user wants,
or as big as the remaining data */
amt = MIN(uio->uio_resid, (echomsg->len - uio->uio_offset > 0) ? echomsg->len - uio-
>uio_offset : 0);
if ((err = uiomove(echomsg->msg + uio->uio_offset,amt,uio)) != 0) {
uprintf("uiomove failed!\n");
}
return err;
}
/*
* echo_write takes in a character string and saves it
* to buf for later accessing.
*/
int
130
Chapter 18 Writing FreeBSD Device Drivers
if (err != 0) {
uprintf("Write failed: bad address!\n");
}
count++;
return(err);
}
DEV_MODULE(echo,echo_loader,NULL);
To install this driver you will first need to make a node on your filesystem with a command such as :
# mknod /dev/echo c 33 0
With this driver loaded you should now be able to type something like :
131
Chapter 18 Writing FreeBSD Device Drivers
132
Chapter 19 ISA device drivers
This chapter was written by Sergey Babkin <[email protected] > Modifications for the handbook made by
Murray Stokely <[email protected] >, Wylie Stilwell <[email protected]>, and Valentino Vaschetto
<[email protected]>.
19.1 Synopsis
This chapter introduces the issues relevant to writing a driver for an ISA device. The pseudo-code presented here is
rather detailed and reminiscent of the real code but is still only pseudo-code. It avoids the details irrelevant to the
subject of the discussion. The real-life examples can be found in the source code of real drivers. In particular the
drivers "ep" and "aha" are good sources of information.
#include <sys/module.h>
#include <sys/bus.h>
#include <machine/bus.h>
#include <machine/resource.h>
#include <sys/rman.h>
#include <isa/isavar.h>
#include <isa/pnpvar.h>
They describe the things specific to the ISA and generic bus subsystem.
The bus subsystem is implemented in an object-oriented fashion, its main structures are accessed by associated
method functions.
The list of bus methods implemented by an ISA driver is like one for any other bus. For a hypothetical driver named
"xxx" they would be:
• static void xxx_isa_identify (driver_t *, device_t); Normally used for bus drivers, not device
drivers. But for ISA devices this method may have special use: if the device provides some device-specific
(non-PnP) way to auto-detect devices this routine may implement it.
• static int xxx_isa_probe (device_t dev); Probe for a device at a known (or PnP) location. This
routine can also accommodate device-specific auto-detection of parameters for partially configured devices.
133
Chapter 19 ISA device drivers
{ 0, 0 }
};
Here struct xxx_softc is a device-specific structure that contains private driver data and descriptors for the driver’s
resources. The bus code automatically allocates one softc descriptor per device as needed.
134
Chapter 19 ISA device drivers
If the driver is for a device which supports PnP then a table of supported PnP IDs must be defined. The table consists
of a list of PnP IDs supported by this driver and human-readable descriptions of the hardware types and models
having these IDs. It looks like:
If the driver does not support PnP devices it still needs an empty PnP ID table, like:
135
Chapter 19 ISA device drivers
• device_set_desc(dev, desc) Set the description. This makes the device description point to the string desc
which may not be deallocated or changed after that.
• device_set_desc_copy(dev, desc) Set the description. The description is copied into an internal
dynamically allocated buffer, so the string desc may be changed afterwards without adverse effects.
• void *device_get_softc(dev) Get pointer to the device descriptor (struct xxx_softc) associated with this
device.
• u_int32_t device_get_flags(dev) Get the flags specified for the device in the configuration file.
A convenience function device_printf(dev, fmt, ...) may be used to print the messages from the device
driver. It automatically prepends the unitname and colon to the message.
The device_t methods are implemented in the file kern/bus_subr.c.
The values of port, IRQ and so on are converted to the resource values associated with the device. They are optional,
depending on the device needs and abilities for auto-configuration. For example, some devices don’t need DRQ at all
and some allow the driver to read the IRQ setting from the device configuration ports. If a machine has multiple ISA
buses the exact bus may be specified in the configuration line, like "isa0" or "isa1", otherwise the device would be
searched for on all the ISA buses.
"sensitive" is a resource requesting that this device must be probed before all non-sensitive devices. It is supported
but does not seem to be used in any current driver.
For legacy ISA devices in many cases the drivers are still able to detect the configuration parameters. But each device
to be configured in the system must have a config line. If two devices of some type are installed in the system but
there is only one configuration line for the corresponding driver, ie:
136
Chapter 19 ISA device drivers
If a driver supports both auto-identified and legacy devices and both kinds are installed at once in one machine then
it’s enough to describe in the config file the legacy devices only. The auto-identified devices will be added
automatically.
When an ISA bus is auto-configured the events happen as follows:
All the drivers’ identify routines (including the PnP identify routine which identifies all the PnP devices) are called in
random order. As they identify the devices they add them to the list on the ISA bus. Normally the drivers’ identify
routines associate their drivers with the new devices. The PnP identify routine does not know about the other drivers
yet so it does not associate any with the new devices it adds.
The PnP devices are put to sleep using the PnP protocol to prevent them from being probed as legacy devices.
The probe routines of non-PnP devices marked as "sensitive" are called. If probe for a device went successfully, the
attach routine is called for it.
The probe and attach routines of all non-PNP devices are called likewise.
The PnP devices are brought back from the sleep state and assigned the resources they request: I/O and memory
address ranges, IRQs and DRQs, all of them not conflicting with the attached legacy devices.
Then for each PnP device the probe routines of all the present ISA drivers are called. The first one that claims the
device gets attached. It is possible that multiple drivers would claim the device with different priority, the
highest-priority driver wins. The probe routines must call ISA_PNP_PROBE() to compare the actual PnP ID with the
list of the IDs supported by the driver and if the ID is not in the table return failure. That means that absolutely every
driver, even the ones not supporting any PnP devices must call ISA_PNP_PROBE(), at least with an empty PnP ID
table to return failure on unknown PnP devices.
The probe routine returns a positive value (the error code) on error, zero or negative value on success.
The negative return values are used when a PnP device supports multiple interfaces. For example, an older
compatibility interface and a newer advanced interface which are supported by different drivers. Then both drivers
would detect the device. The driver which returns a higher value in the probe routine takes precedence (in other
words, the driver returning 0 has highest precedence, returning -1 is next, returning -2 is after it and so on). In result
the devices which support only the old interface will be handled by the old driver (which should return -1 from the
probe routine) while the devices supporting the new interface as well will be handled by the new driver (which
should return 0 from the probe routine). If multiple drivers return the same value then the one called first wins. So if
a driver returns value 0 it may be sure that it won the priority arbitration.
The device-specific identify routines can also assign not a driver but a class of drivers to the device. Then all the
drivers in the class are probed for this device, like the case with PnP. This feature is not implemented in any existing
driver and is not considered further in this document.
Because the PnP devices are disabled when probing the legacy devices they will not be attached twice (once as
legacy and once as PnP). But in case of device-dependent identify routines it’s the responsibility of the driver to
make sure that the same device won’t be attached by the driver twice: once as legacy user-configured and once as
auto-identified.
137
Chapter 19 ISA device drivers
Another practical consequence for the auto-identified devices (both PnP and device-specific) is that the flags can not
be passed to them from the kernel configuration file. So they must either not use the flags at all or use the flags from
the device unit 0 for all the auto-identified devices or use the sysctl interface instead of flags.
Other unusual configurations may be accommodated by accessing the configuration resources directly with functions
of families resource_query_*() and resource_*_value(). Their implementations are located in
kern/subr_bus.h. The old IDE disk driver i386/isa/wd.c contains examples of such use. But the standard means of
configuration must always be preferred. Leave parsing the configuration resources to the bus configuration code.
19.5 Resources
The information that a user enters into the kernel configuration file is processed and passed to the kernel as
configuration resources. This information is parsed by the bus configuration code and transformed into a value of
structure device_t and the bus resources associated with it. The drivers may access the configuration resources
directly using functions resource_* for more complex cases of configuration. But generally it’s not needed nor
recommended, so this issue is not discussed further.
The bus resources are associated with each device. They are identified by type and number within the type. For the
ISA bus the following types are defined:
IRQ: 0-1
DRQ: 0-1
MEMORY: 0-3
IOPORT: 0-7
All the resources are represented as ranges, with a start value and count. For IRQ and DRQ resources the count
would be normally equal to 1. The values for memory refer to the physical addresses.
Three types of activities can be performed on resources:
138
Chapter 19 ISA device drivers
• set/get
• allocate/release
• activate/deactivate
Setting sets the range used by the resource. Allocation reserves the requested range that no other driver would be able
to reserve it (and checking that no other driver reserved this range already). Activation makes the resource accessible
to the driver doing whatever is necessary for that (for example, for memory it would be mapping into the kernel
virtual address space).
The functions to manipulate resources are:
• int bus_set_resource(device_t dev, int type, int rid, u_long start, u_long count)
Set a range for a resource. Returns 0 if successful, error code otherwise. Normally the only reason this function
would return an error is value of type, rid, start or count out of permitted range.
• int bus_get_resource(device_t dev, int type, int rid, u_long *startp, u_long
*countp)
Get the range of resource. Returns 0 if successful, error code if the resource is not defined yet.
Convenience functions to get only the start or count. Return 0 in case of error, so if the resource start has 0 among
the legitimate values it would be impossible to tell if the value is 0 or an error occurred. Luckily, no ISA resources
for add-on drivers may have a start value equal 0.
• struct resource * bus_alloc_resource(device_t dev, int type, int *rid, u_long start,
u_long end, u_long count, u_int flags)
139
Chapter 19 ISA device drivers
Allocate a resource as a range of count values not allocated by anyone else, somewhere between start and end.
Alas, alignment is not supported. If the resource was not set yet it’s automatically created. The special values of
start 0 and end ~0 (all ones) means that the fixed values previously set by bus_set_resource() must be used
instead: start and count as themselves and end=(start+count), in this case if the resource was not defined before
then an error is returned. Although rid is passed by reference it’s not set anywhere by the resource allocation code
of the ISA bus. (The other buses may use a different approach and modify it).
Flags are a bitmap, the flags interesting for the caller are:
• Release the resource, r is the handle returned by bus_alloc_resource(). Returns 0 on success, error code
otherwise.
• int bus_activate_resource(device_t dev, int type, int rid, struct resource *r) int
bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
• Activate or deactivate resource. Return 0 on success, error code otherwise. If the resource is time-shared and
currently activated by another driver then EBUSY is returned.
• int bus_setup_intr(device_t dev, struct resource *r, int flags, driver_intr_t
*handler, void *arg, void **cookiep) int bus_teardown_intr(device_t dev, struct
resource *r, void *cookie)
• Associate or de-associate the interrupt handler with a device. Return 0 on success, error code otherwise.
• r - the activated resource handler describing the IRQ
flags - the interrupt priority level, one of:
• INTR_TYPE_TTY - terminals and other likewise character-type devices. To mask them use spltty().
• (INTR_TYPE_TTY | INTR_TYPE_FAST) - terminal type devices with small input buffer, critical to the data
loss on input (such as the old-fashioned serial ports). To mask them use spltty().
• INTR_TYPE_BIO - block-type devices, except those on the CAM controllers. To mask them use splbio().
• INTR_TYPE_CAM - CAM (Common Access Method) bus controllers. To mask them use splcam().
• INTR_TYPE_NET - network interface controllers. To mask them use splimp().
140
Chapter 19 ISA device drivers
• INTR_TYPE_MISC - miscellaneous devices. There is no other way to mask them than by splhigh() which
masks all interrupts.
When an interrupt handler executes all the other interrupts matching its priority level will be masked. The only
exception is the MISC level for which no other interrupts are masked and which is not masked by any other interrupt.
• handler - pointer to the handler function, the type driver_intr_t is defined as "void driver_intr_t(void *)"
• arg - the argument passed to the handler to identify this particular device. It is cast from void* to any real type by
the handler. The old convention for the ISA interrupt handlers was to use the unit number as argument, the new
(recommended) convention is using a pointer to the device softc structure.
• cookie[p] - the value received from setup() is used to identify the handler when passed to teardown()
A number of methods is defined to operate on the resource handlers (struct resource *). Those of interest to the
device driver writers are:
• u_long rman_get_start(r) u_long rman_get_end(r) Get the start and end of allocated resource range.
• void *rman_get_virtual(r) Get the virtual address of activated memory resource.
141
Chapter 19 ISA device drivers
In the case (b) just the address of the data is sent to the device, and the device uses DMA to actually access the data
in the main memory. Two limitations are present: First, ISA cards can only access memory below 16MB. Second, the
contiguous pages in virtual address space may not be contiguous in physical address space, so the device may have to
do scatter/gather operations. The bus subsystem provides ready solutions for some of these problems, the rest has to
be done by the drivers themselves.
Two structures are used for DMA memory allocation, bus_dma_tag_t and bus_dmamap_t. Tag describes the
properties required for the DMA memory. Map represents a memory block allocated according to these properties.
Multiple maps may be associated with the same tag.
Tags are organized into a tree-like hierarchy with inheritance of the properties. A child tag inherits all the
requirements of its parent tag or may make them more strict but never more loose.
Normally one top-level tag (with no parent) is created for each device unit. If multiple memory areas with different
requirements are needed for each device then a tag for each of them may be created as a child of the parent tag.
The tags can be used to create a map in two ways.
First, a chunk of contiguous memory conformant with the tag requirements may be allocated (and later may be
freed). This is normally used to allocate relatively long-living areas of memory for communication with the device.
Loading of such memory into a map is trivial: it’s always considered as one chunk in the appropriate physical
memory range.
Second, an arbitrary area of virtual memory may be loaded into a map. Each page of this memory will be checked for
conformance to the map requirement. If it conforms then it’s left at it’s original location. If it is not then a fresh
conformant "bounce page" is allocated and used as intermediate storage. When writing the data from the
non-conformant original pages they will be copied to their bounce pages first and then transferred from the bounce
pages to the device. When reading the data would go from the device to the bounce pages and then copied to their
non-conformant original pages. The process of copying between the original and bounce pages is called
synchronization. This is normally used on per-transfer basis: buffer for each transfer would be loaded, transfer done
and buffer unloaded.
The functions working on the DMA memory are:
• parent - parent tag, or NULL to create a top-level tag alignment - required physical alignment of the memory
area to be allocated for this tag. Use value 1 for "no specific alignment". Applies only to the future
bus_dmamem_alloc() but not bus_dmamap_create() calls. boundary - physical address boundary that
must not be crossed when allocating the memory. Use value 0 for "no boundary". Applies only to the future
142
Chapter 19 ISA device drivers
bus_dmamem_alloc() but not bus_dmamap_create() calls. Must be power of 2. If the memory is planned
to be used in non-cascaded DMA mode (i.e. the DMA addresses will be supplied not by the device itself but by
the ISA DMA controller) then the boundary must be no larger than 64KB (64*1024) due to the limitations of
the DMA hardware.
• lowaddr, highaddr - the names are slighlty misleading; these values are used to limit the permitted range of
physical addresses used to allocate the memory. The exact meaning varies depending on the planned future use:
• For bus_dmamem_alloc() all the addresses from 0 to lowaddr-1 are considered permitted, the higher ones
are forbidden.
• For bus_dmamap_create() all the addresses outside the inclusive range [lowaddr; highaddr] are considered
accessible. The addresses of pages inside the range are passed to the filter function which decides if they are
accessible. If no filter function is supplied then all the range is considered unaccessible.
• For the ISA devices the normal values (with no filter function) are:
lowaddr = BUS_SPACE_MAXADDR_24BIT
highaddr = BUS_SPACE_MAXADDR
• filter, filterarg - the filter function and its argument. If NULL is passed for filter then the whole range [lowaddr,
highaddr] is considered unaccessible when doing bus_dmamap_create(). Otherwise the physical address of
each attempted page in range [lowaddr; highaddr] is passed to the filter function which decides if it is
accessible. The prototype of the filter function is: int filterfunc(void *arg, bus_addr_t paddr) It
must return 0 if the page is accessible, non-zero otherwise.
• maxsize - the maximal size of memory (in bytes) that may be allocated through this tag. In case it’s difficult to
estimate or could be arbitrarily big, the value for ISA devices would be BUS_SPACE_MAXSIZE_24BIT.
• nsegments - maximal number of scatter-gather segments supported by the device. If unrestricted then the value
BUS_SPACE_UNRESTRICTED should be used. This value is recommended for the parent tags, the actual
restrictions would then be specified for the descendant tags. Tags with nsegments equal to
BUS_SPACE_UNRESTRICTED may not be used to actually load maps, they may be used only as parent tags.
The practical limit for nsegments seems to be about 250-300, higher values will cause kernel stack overflow.
But anyway the hardware normally can’t support that many scatter-gather buffers.
• maxsegsz - maximal size of a scatter-gather segment supported by the device. The maximal value for ISA device
would be BUS_SPACE_MAXSIZE_24BIT.
• flags - a bitmap of flags. The only interesting flags are:
• BUS_DMA_ALLOCNOW - requests to allocate all the potentially needed bounce pages when creating the tag
143
Chapter 19 ISA device drivers
• BUS_DMA_ISA - mysterious flag used only on Alpha machines. It is not defined for the i386 machines.
Probably it should be used by all the ISA drivers for Alpha machines but it looks like there are no such
drivers yet.
Allocate an area of contiguous memory described by the tag. The size of memory to be allocated is tag’s maxsize.
Returns 0 on success, the error code otherwise. The result still has to be loaded by bus_dmamap_load() before
used to get the physical address of the memory.
144
Chapter 19 ISA device drivers
Create a map for the tag, to be used in bus_dmamap_load() later. Returns 0 on success, the error code otherwise.
Load a buffer into the map (the map must be previously created by bus_dmamap_create() or
bus_dmamem_alloc()). All the pages of the buffer are checked for conformance to the tag requirements and for
those not conformant the bounce pages are allocated. An array of physical segment descriptors is built and passed
to the callback routine. This callback routine is then expected to handle it in some way. The number of bounce
buffers in the system is limited, so if the bounce buffers are needed but not immediately available the request will
be queued and the callback will be called when the bounce buffers will become available. Returns 0 if the callback
was executed immediately or EINPROGRESS if the request was queued for future execution. In the latter case the
synchronization with queued callback routine is the responsibility of the driver.
145
Chapter 19 ISA device drivers
• dmat - tag
• map - loaded map
Synchronise a loaded buffer with its bounce pages before and after physical transfer to or from device. This is the
function that does all the necessary copying of data between the original buffer and its mapped version. The
buffers must be synchronized both before and after doing the transfer.
• dmat - tag
• map - loaded map
• op - type of synchronization operation to perform:
146
Chapter 19 ISA device drivers
As of now PREREAD and POSTWRITE are null operations but that may change in the future, so they must not be
ignored in the driver. Synchronization is not needed for the memory obtained from bus_dmamem_alloc().
Before calling the callback function from bus_dmamap_load() the segment array is stored in the stack. And it gets
pre-allocated for the maximal number of segments allowed by the tag. Because of this the practical limit for the
number of segments on i386 architecture is about 250-300 (the kernel stack is 4KB minus the size of the user
structure, size of a segment array entry is 8 bytes, and some space must be left). Because the array is allocated based
on the maximal number this value must not be set higher than really needed. Fortunately, for most of hardware the
maximal supported number of segments is much lower. But if the driver wants to handle buffers with a very large
number of scatter-gather segments it should do that in portions: load part of the buffer, transfer it to the device, load
next part of the buffer, and so on.
Another practical consequence is that the number of segments may limit the size of the buffer. If all the pages in the
buffer happen to be physically non-contiguous then the maximal supported buffer size for that fragmented case
would be (nsegments * page_size). For example, if a maximal number of 10 segments is supported then on i386
maximal guaranteed supported buffer size would be 40K. If a higher size is desired then special tricks should be used
in the driver.
If the hardware does not support scatter-gather at all or the driver wants to support some buffer size even if it’s
heavily fragmented then the solution is to allocate a contiguous buffer in the driver and use it as intermediate storage
if the original buffer does not fit.
Below are the typical call sequences when using a map depend on the use of the map. The characters -> are used to
show the flow of time.
For a buffer which stays practically fixed during all the time between attachment and detachment of a device:
bus_dmamem_alloc -> bus_dmamap_load -> ...use buffer... -> -> bus_dmamap_unload -> bus_dmamem_free
For a buffer that changes frequently and is passed from outside the driver:
bus_dmamap_create ->
-> bus_dmamap_load -> bus_dmamap_sync(PRE...) -> do transfer ->
-> bus_dmamap_sync(POST...) -> bus_dmamap_unload ->
...
-> bus_dmamap_load -> bus_dmamap_sync(PRE...) -> do transfer ->
-> bus_dmamap_sync(POST...) -> bus_dmamap_unload ->
-> bus_dmamap_destroy
When loading a map created by bus_dmamem_alloc() the passed address and size of the buffer must be the same
as used in bus_dmamem_alloc(). In this case it is guaranteed that the whole buffer will be mapped as one segment
(so the callback may be based on this assumption) and the request will be executed immediately (EINPROGRESS
will never be returned). All the callback needs to do in this case is to save the physical address.
A typical example would be:
147
Chapter 19 ISA device drivers
static void
alloc_callback(void *arg, bus_dma_segment_t *seg, int nseg, int error)
{
*(bus_addr_t *)arg = seg[0].ds_addr;
}
...
int error;
struct somedata {
....
};
struct somedata *vsomedata; /* virtual address */
bus_addr_t psomedata; /* physical bus-relative address */
bus_dma_tag_t tag_somedata;
bus_dmamap_t map_somedata;
...
error=bus_dma_tag_create(parent_tag, alignment,
boundary, lowaddr, highaddr, /*filter*/ NULL, /*filterarg*/ NULL,
/*maxsize*/ sizeof(struct somedata), /*nsegments*/ 1,
/*maxsegsz*/ sizeof(struct somedata), /*flags*/ 0,
&tag_somedata);
if(error)
return error;
Looks a bit long and complicated but that’s the way to do it. The practical consequence is: if multiple memory areas
are allocated always together it would be a really good idea to combine them all into one structure and allocate as
one (if the alignment and boundary limitations permit).
When loading an arbitrary buffer into the map created by bus_dmamap_create() special measures must be taken
to synchronize with the callback in case it would be delayed. The code would look like:
{
int s;
int error;
148
Chapter 19 ISA device drivers
s = splsoftvm();
error = bus_dmamap_load(
dmat,
dmamap,
buffer_ptr,
buffer_len,
callback,
/*callback_arg*/ buffer_descriptor,
/*flags*/0);
if (error == EINPROGRESS) {
/*
* Do whatever is needed to ensure synchronization
* with callback. Callback is guaranteed not to be started
* until we do splx() or tsleep().
*/
}
splx(s);
}
19.7 DMA
The Direct Memory Access (DMA) is implemented in the ISA bus through the DMA controller (actually, two of
them but that’s an irrelevant detail). To make the early ISA devices simple and cheap the logic of the bus control and
address generation was concentrated in the DMA controller. Fortunately, FreeBSD provides a set of functions that
mostly hide the annoying details of the DMA controller from the device drivers.
The simplest case is for the fairly intelligent devices. Like the bus master devices on PCI they can generate the bus
cycles and memory addresses all by themselves. The only thing they really need from the DMA controller is bus
arbitration. So for this purpose they pretend to be cascaded slave DMA controllers. And the only thing needed from
149
Chapter 19 ISA device drivers
the system DMA controller is to enable the cascaded mode on a DMA channel by calling the following function
when attaching the driver:
void isa_dmacascade(int channel_number)
All the further activity is done by programming the device. When detaching the driver no DMA-related functions
need to be called.
For the simpler devices things get more complicated. The functions used are:
150
Chapter 19 ISA device drivers
• flags - a bitmask determining the type of operation to be done. The direction bits B_READ and B_WRITE are
mutually exclusive.
• B_READ - read from the ISA bus into memory
• B_WRITE - write from the memory to the ISA bus
• B_RAW - if set then the DMA controller will remember the buffer and after the end of transfer will
automatically re-initialize itself to repeat transfer of the same buffer again (of course, the driver may change the
data in the buffer before initiating another transfer in the device). If not set then the parameters will work only
for one transfer, and isa_dmastart() will have to be called again before initiating the next transfer. Using
B_RAW makes sense only if the bounce buffer is not used.
Synchronize the memory after device reports that transfer is done. If that was a read operation with a bounce
buffer then the data will be copied from the bounce buffer to the original buffer. Arguments are the same as for
isa_dmastart(). Flag B_RAW is permitted but it does not affect isa_dmadone() in any way.
Returns the number of bytes left in the current transfer to be transferred. In case the flag B_READ was set in
isa_dmastart() the number returned will never be equal to zero. At the end of transfer it will be automatically
reset back to the length of buffer. The normal use is to check the number of bytes left after the device signals that
the transfer is completed. If the number of bytes is not 0 then probably something went wrong with that transfer.
151
Chapter 19 ISA device drivers
19.8 xxx_isa_probe
This function probes if a device is present. If the driver supports auto-detection of some part of device configuration
(such as interrupt vector or memory address) this auto-detection must be done in this routine.
As for any other bus, if the device can not be detected or is detected but failed the self-test or some other problem
happened then it returns a positive value of error. The value ENXIO must be returned if the device is not present.
Other error values may mean other conditions. Zero or negative values mean success. Most of the drivers return zero
as success.
The negative return values are used when a PnP device supports multiple interfaces. For example, an older
compatibility interface and a newer advanced interface which are supported by different drivers. Then both drivers
would detect the device. The driver which returns a higher value in the probe routine takes precedence (in other
words, the driver returning 0 has highest precedence, one returning -1 is next, one returning -2 is after it and so on).
In result the devices which support only the old interface will be handled by the old driver (which should return -1
from the probe routine) while the devices supporting the new interface as well will be handled by the new driver
(which should return 0 from the probe routine).
The device descriptor struct xxx_softc is allocated by the system before calling the probe routine. If the probe routine
returns an error the descriptor will be automatically deallocated by the system. So if a probing error occurs the driver
must make sure that all the resources it used during probe are deallocated and that nothing keeps the descriptor from
being safely deallocated. If the probe completes successfully the descriptor will be preserved by the system and later
passed to the routine xxx_isa_attach(). If a driver returns a negative value it can’t be sure that it will have the
highest priority and its attach routine will be called. So in this case it also must release all the resources before
returning and if necessary allocate them again in the attach routine. When xxx_isa_probe() returns 0 releasing the
resources before returning is also a good idea, a well-behaved driver should do so. But in case if there is some
problem with releasing the resources the driver is allowed to keep resources between returning 0 from the probe
routine and execution of the attach routine.
A typical probe routine starts with getting the device descriptor and unit:
Then check for the PnP devices. The check is carried out by a table containing the list of PnP IDs supported by this
driver and human-readable descriptions of the device models corresponding to these IDs.
pnperror=ISA_PNP_PROBE(device_get_parent(dev), dev,
xxx_pnp_ids); if(pnperror == ENXIO) return ENXIO;
152
Chapter 19 ISA device drivers
The logic of ISA_PNP_PROBE is the following: If this card (device unit) was not detected as PnP then ENOENT
will be returned. If it was detected as PnP but its detected ID does not match any of the IDs in the table then ENXIO
is returned. Finally, if it has PnP support and it matches on of the IDs in the table, 0 is returned and the appropriate
description from the table is set by device_set_desc().
If a driver supports only PnP devices then the condition would look like:
if(pnperror != 0)
return pnperror;
No special treatment is required for the drivers which don’t support PnP because they pass an empty PnP ID table
and will always get ENXIO if called on a PnP card.
The probe routine normally needs at least some minimal set of resources, such as I/O port number to find the card
and probe it. Depending on the hardware the driver may be able to discover the other necessary resources
automatically. The PnP devices have all the resources pre-set by the PnP subsystem, so the driver does not need to
discover them by itself.
Typically the minimal information required to get access to the device is the I/O port number. Then some devices
allow to get the rest of information from the device configuration registers (though not all devices do that). So first
we try to get the port start value:
sc->port0 = bus_get_resource_start(dev,
SYS_RES_IOPORT, 0 /*rid*/); if(sc->port0 == 0) return ENXIO;
The base port address is saved in the structure softc for future use. If it will be used very often then calling the
resource function each time would be prohibitively slow. If we don’t get a port we just return an error. Some device
drivers can instead be clever and try to probe all the possible ports, like this:
/* table of all possible base I/O port addresses for this device */
static struct xxx_allports {
u_short port; /* port address */
short used; /* flag: if this port is already used by some unit */
} xxx_allports = {
{ 0x300, 0 },
{ 0x320, 0 },
{ 0x340, 0 },
{ 0, 0 } /* end of table */
};
...
int port, i;
...
153
Chapter 19 ISA device drivers
/* found it */
xxx_allports[i].used = 1;
/* do probe on a known port */
return xxx_really_probe(dev, port);
}
return ENXIO; /* port is unknown or already used */
}
Of course, normally the driver’s identify() routine should be used for such things. But there may be one valid
reason why it may be better to be done in probe(): if this probe would drive some other sensitive device crazy. The
probe routines are ordered with consideration of the "sensitive" flag: the sensitive devices get probed first and the rest
of devices later. But the identify() routines are called before any probes, so they show no respect to the sensitive
devices and may upset them.
Now, after we got the starting port we need to set the port count (except for PnP devices) because the kernel does not
have this information in the configuration file.
154
Chapter 19 ISA device drivers
return ENXIO;
Finally allocate and activate a piece of port address space (special values of start and end mean "use those we set by
bus_set_resource()"):
sc->port0_rid = 0;
sc->port0_r = bus_alloc_resource(dev, SYS_RES_IOPORT,
&sc->port0_rid,
/*start*/ 0, /*end*/ ~0, /*count*/ 0, RF_ACTIVE);
if(sc->port0_r == NULL)
return ENXIO;
Now having access to the port-mapped registers we can poke the device in some way and check if it reacts like it is
expected to. If it does not then there is probably some other device or no device at all at this address.
Normally drivers don’t set up the interrupt handlers until the attach routine. Instead they do probes in the polling
mode using the DELAY() function for timeout. The probe routine must never hang forever, all the waits for the
device must be done with timeouts. If the device does not respond within the time it’s probably broken or
misconfigured and the driver must return error. When determining the timeout interval give the device some extra
time to be on the safe side: although DELAY() is supposed to delay for the same amount of time on any machine it
has some margin of error, depending on the exact CPU.
If the probe routine really wants to check that the interrupts really work it may configure and probe the interrupts too.
But that’s not recommended.
The fucntion xxx_probe_ports() may also set the device description depending on the exact model of device it
discovers. But if there is only one supported device model this can be as well done in a hardcoded way. Of course,
for the PnP devices the PnP support sets the description from the table automatically.
if(pnperror)
device_set_desc(dev, "Our device model 1234");
Then the probe routine should either discover the ranges of all the resources by reading the device configuration
registers or make sure that they were set explicitly by the user. We will consider it with an example of on-board
memory. The probe routine should be as non-intrusive as possible, so allocation and check of functionality of the rest
of resources (besides the ports) would be better left to the attach routine.
155
Chapter 19 ISA device drivers
The memory address may be specified in the kernel configuration file or on some devices it may be pre-configured in
non-volatile configuration registers. If both sources are available and different, which one should be used? Probably
if the user bothered to set the address explicitly in the kernel configuration file they know what they’re doing and this
one should take precedence. An example of implementation could be:
if(sc->mem0_p == 0)
/* can’t get it from device config registers either */
goto bad;
} else {
if(xxx_set_mem0_address_on_device(sc) 0) <
goto bad; /* device does not support that address */
}
if(sc->mem0_size == 0) {
/* suppose this is a very old model of device without
* auto-configuration features and the user gave no preference,
* so assume the minimalistic case
* (of course, the real value will vary with the driver)
*/
sc->mem0_size = 8*1024;
}
if(xxx_set_mem0_size_on_device(sc) 0) <
goto bad; /* device does not support that size */
156
Chapter 19 ISA device drivers
xxx_free_resources(sc);
return 0;
Finally, handle the troublesome situations. All the resources should be deallocated before returning. We make use of
the fact that before the structure softc is passed to us it gets zeroed out, so we can find out if some resource was
allocated: then its descriptor is non-zero.
bad:
xxx_free_resources(sc);
if(error)
return error;
else /* exact error is unknown */
return ENXIO;
That would be all for the probe routine. Freeing of resources is done from multiple places, so it’s moved to a function
which may look like:
static void
xxx_free_resources(sc)
struct xxx_softc *sc;
{
/* check every resource and free if not zero */
/* interrupt handler */
if(sc->intr_r) {
bus_teardown_intr(sc->dev, sc->intr_r, sc->intr_cookie);
bus_release_resource(sc->dev, SYS_RES_IRQ, sc->intr_rid,
sc->intr_r);
sc->intr_r = 0;
}
157
Chapter 19 ISA device drivers
sc->data_p = 0;
}
if(sc->data) { /* sc->data_map may be legitimately equal to 0 */
/* the map will also be freed */
bus_dmamem_free(sc->data_tag, sc->data, sc->data_map);
sc->data = 0;
}
if(sc->data_tag) {
bus_dma_tag_destroy(sc->data_tag);
sc->data_tag = 0;
}
if(sc->parent_tag) {
bus_dma_tag_destroy(sc->parent_tag);
sc->parent_tag = 0;
}
19.9 xxx_isa_attach
The attach routine actually connects the driver to the system if the probe routine returned success and the system had
chosen to attach that driver. If the probe routine returned 0 then the attach routine may expect to receive the device
structure softc intact, as it was set by the probe routine. Also if the probe routine returns 0 it may expect that the
attach routine for this device shall be called at some point in the future. If the probe routine returns a negative value
then the driver may make none of these assumptions.
The attach routine returns 0 if it completed successfully or error code otherwise.
158
Chapter 19 ISA device drivers
The attach routine starts just like the probe routine, with getting some frequently used data into more accessible
variables.
Then allocate and activate all the necessary resources. Because normally the port range will be released before
returning from probe, it has to be allocated again. We expect that the probe routine had properly set all the resource
ranges, as well as saved them in the structure softc. If the probe routine had left some resource allocated then it does
not need to be allocated again (which would be considered an error).
sc->port0_rid = 0;
sc->port0_r = bus_alloc_resource(dev, SYS_RES_IOPORT, &sc->port0_rid,
/*start*/ 0, /*end*/ ~0, /*count*/ 0, RF_ACTIVE);
if(sc->port0_r == NULL)
return ENXIO;
/* on-board memory */
sc->mem0_rid = 0;
sc->mem0_r = bus_alloc_resource(dev, SYS_RES_MEMORY, &sc->mem0_rid,
/*start*/ 0, /*end*/ ~0, /*count*/ 0, RF_ACTIVE);
if(sc->mem0_r == NULL)
goto bad;
The DMA request channel (DRQ) is allocated likewise. To initialize it use functions of the isa_dma*() family. For
example:
isa_dmacascade(sc->drq0);
The interrupt request line (IRQ) is a bit special. Besides allocation the driver’s interrupt handler should be associated
with it. Historically in the old ISA drivers the argument passed by the system to the interrupt handler was the device
unit number. But in modern drivers the convention suggests passing the pointer to structure softc. The important
reason is that when the structures softc are allocated dynamically then getting the unit number from softc is easy
while getting softc from unit number is difficult. Also this convention makes the drivers for different buses look more
uniform and allows them to share the code: each bus gets its own probe, attach, detach and other bus-specific routines
while the bulk of the driver code may be shared among them.
sc->intr_rid = 0;
sc->intr_r = bus_alloc_resource(dev, SYS_RES_MEMORY, &sc->intr_rid,
159
Chapter 19 ISA device drivers
if(sc->intr_r == NULL)
goto bad;
/*
* XXX_INTR_TYPE is supposed to be defined depending on the type of
* the driver, for example as INTR_TYPE_CAM for a CAM driver
*/
error = bus_setup_intr(dev, sc->intr_r, XXX_INTR_TYPE,
(driver_intr_t *) xxx_intr, (void *) sc, &sc->intr_cookie);
if(error)
goto bad;
If the device needs to make DMA to the main memory then this memory should be allocated like described before:
error=bus_dma_tag_create(NULL, /*alignment*/ 4,
/*boundary*/ 0, /*lowaddr*/ BUS_SPACE_MAXADDR_24BIT,
/*highaddr*/ BUS_SPACE_MAXADDR, /*filter*/ NULL, /*filterarg*/ NULL,
/*maxsize*/ BUS_SPACE_MAXSIZE_24BIT,
/*nsegments*/ BUS_SPACE_UNRESTRICTED,
/*maxsegsz*/ BUS_SPACE_MAXSIZE_24BIT, /*flags*/ 0,
&sc->parent_tag);
if(error)
goto bad;
160
Chapter 19 ISA device drivers
After all the necessary resources are allocated the device should be initialized. The initialization may include testing
that all the expected features are functional.
if(xxx_initialize(sc) < 0)
goto bad;
The bus subsystem will automatically print on the console the device description set by probe. But if the driver wants
to print some extra information about the device it may do so, for example:
If the initialization routine experiences any problems then printing messages about them before returning error is also
recommended.
The final step of the attach routine is attaching the device to its functional subsystem in the kernel. The exact way to
do it depends on the type of the driver: a character device, a block device, a network device, a CAM SCSI bus device
and so on.
If all went well then return success.
error = xxx_attach_subsystem(sc);
if(error)
goto bad;
161
Chapter 19 ISA device drivers
return 0;
Finally, handle the troublesome situations. All the resources should be deallocated before returning an error. We
make use of the fact that before the structure softc is passed to us it gets zeroed out, so we can find out if some
resource was allocated: then its descriptor is non-zero.
bad:
xxx_free_resources(sc);
if(error)
return error;
else /* exact error is unknown */
return ENXIO;
19.10 xxx_isa_detach
If this function is present in the driver and the driver is compiled as a loadable module then the driver gets the ability
to be unloaded. This is an important feature if the hardware supports hot plug. But the ISA bus does not support hot
plug, so this feature is not particularly important for the ISA devices. The ability to unload a driver may be useful
when debugging it, but in many cases installation of the new version of the driver would be required only after the
old version somehow wedges the system and reboot will be needed anyway, so the efforts spent on writing the detach
routine may not be worth it. Another argument is that unloading would allow upgrading the drivers on a production
machine seems to be mostly theoretical. Installing a new version of a driver is a dangerous operation which should
never be performed on a production machine (and which is not permitted when the system is running in secure
mode). Still the detach routine may be provided for the sake of completeness.
The detach routine returns 0 if the driver was successfully detached or the error code otherwise.
The logic of detach is a mirror of the attach. The first thing to do is to detach the driver from its kernel subsystem. If
the device is currently open then the driver has two choices: refuse to be detached or forcibly close and proceed with
detach. The choice used depends on the ability of the particular kernel subsystem to do a forced close and on the
preferences of the driver’s author. Generally the forced close seems to be the preferred alternative.
error = xxx_detach_subsystem(sc);
if(error)
return error;
162
Chapter 19 ISA device drivers
Next the driver may want to reset the hardware to some consistent state. That includes stopping any ongoing
transfers, disabling the DMA channels and interrupts to avoid memory corruption by the device. For most of the
drivers this is exactly what the shutdown routine does, so if it is included in the driver we can as well just call it.
xxx_isa_shutdown(dev);
And finally release all the resources and return success.
xxx_free_resources(sc);
return 0;
19.11 xxx_isa_shutdown
This routine is called when the system is about to be shut down. It is expected to bring the hardware to some
consistent state. For most of the ISA devices no special action is required, so the function is not really necessary
because the device will be re-initialized on reboot anyway. But some devices have to be shut down with a special
procedure, to make sure that they will be properly detected after soft reboot (this is especially true for many devices
with proprietary identification protocols). In any case disabling DMA and interrupts in the device registers and
stopping any ongoing transfers is a good idea. The exact action depends on the hardware, so we don’t consider it here
in any details.
xxx_intr
The interrupt handler is called when an interrupt is received which may be from this particular device. The ISA bus
does not support interrupt sharing (except some special cases) so in practice if the interrupt handler is called then the
interrupt almost for sure came from its device. Still the interrupt handler must poll the device registers and make sure
that the interrupt was generated by its device. If not it should just return.
The old convention for the ISA drivers was getting the device unit number as an argument. It is obsolete, and the new
drivers receive whatever argument was specified for them in the attach routine when calling bus_setup_intr().
By the new convention it should be the pointer to the structure softc. So the interrupt handler commonly starts as:
static void
xxx_intr(struct xxx_softc *sc)
{
It runs at the interrupt priority level specified by the interrupt type parameter of bus_setup_intr(). That means
that all the other interrupts of the same type as well as all the software interrupts are disabled.
163
Chapter 19 ISA device drivers
while(xxx_interrupt_pending(sc)) {
xxx_process_interrupt(sc);
xxx_acknowledge_interrupt(sc);
}
The interrupt handler has to acknowledge interrupt to the device only but not to the interrupt controller, the system
takes care of the latter.
164
Chapter 20 PCI Devices
This chapter will talk about the FreeBSD mechanisms for writing a device driver for a device on a PCI bus.
/*
* Simple KLD to play with the PCI functions.
*
* Murray Stokely
*/
#include <sys/types.h>
#include <sys/module.h>
#include <sys/systm.h> /* uprintf */
#include <sys/errno.h>
#include <sys/param.h> /* defines used in kernel.h */
#include <sys/kernel.h> /* types used in module initialization */
#include <sys/conf.h> /* cdevsw struct */
#include <sys/uio.h> /* uio struct */
#include <sys/malloc.h>
#include <sys/bus.h> /* structs, prototypes for pci bus stuff */
/* Function prototypes */
d_open_t mypci_open;
d_close_t mypci_close;
d_read_t mypci_read;
d_write_t mypci_write;
165
Chapter 20 PCI Devices
mypci_write,
noioctl,
nopoll,
nommap,
nostrategy,
"mypci",
36, /* reserved for lkms - /usr/src/sys/conf/majors */
nodump,
nopsize,
D_TTY,
-1
};
/* vars */
static dev_t sdev;
int
mypci_open(dev_t dev, int oflags, int devtype, struct proc *p)
{
int err = 0;
int
mypci_close(dev_t dev, int fflag, int devtype, struct proc *p)
{
int err=0;
int
mypci_read(dev_t dev, struct uio *uio, int ioflag)
{
int err = 0;
uprintf("mypci read!\n");
return err;
}
166
Chapter 20 PCI Devices
int
mypci_write(dev_t dev, struct uio *uio, int ioflag)
{
int err = 0;
uprintf("mypci write!\n");
return(err);
}
/*
* Return identification string if this is device is ours.
*/
static int
mypci_probe(device_t dev)
{
uprintf("MyPCI Probe\n"
"Vendor ID : 0x%x\n"
"Device ID : 0x%x\n",pci_get_vendor(dev),pci_get_device(dev));
if (pci_get_vendor(dev) == 0x11c1) {
uprintf("We’ve got the Winmodem, probe successful!\n");
return 0;
}
return ENXIO;
}
static int
mypci_attach(device_t dev)
{
uprintf("MyPCI Attach for : deviceID : 0x%x\n",pci_get_vendor(dev));
sdev = make_dev(&mypci_cdevsw,
0,
UID_ROOT,
GID_WHEEL,
0600,
"mypci");
uprintf("Mypci device loaded.\n");
return ENXIO;
}
167
Chapter 20 PCI Devices
/* Detach device. */
static int
mypci_detach(device_t dev)
{
uprintf("Mypci detach!\n");
return 0;
}
static int
mypci_shutdown(device_t dev)
{
uprintf("Mypci shutdown!\n");
return 0;
}
/*
* Device suspend routine.
*/
static int
mypci_suspend(device_t dev)
{
uprintf("Mypci suspend!\n");
return 0;
}
/*
* Device resume routine.
*/
static int
mypci_resume(device_t dev)
{
uprintf("Mypci resume!\n");
return 0;
}
168
Chapter 20 PCI Devices
DEVMETHOD(device_shutdown, mypci_shutdown),
DEVMETHOD(device_suspend, mypci_suspend),
DEVMETHOD(device_resume, mypci_resume),
{ 0, 0 }
};
Additional Resources
sc->bar0id = 0x10;
169
Chapter 20 PCI Devices
sc->bar1id = 0x14;
sc->bar1res = bus_alloc_resource(dev, SYS_RES_MEMORY, &(sc->bar1id),
0, ~0, 1, RF_ACTIVE);
if (sc->bar1res == NULL) {
uprintf("Memory allocation of PCI base register 1 failed!\n");
error = ENXIO;
goto fail2;
}
sc->bar0_bt = rman_get_bustag(sc->bar0res);
sc->bar0_bh = rman_get_bushandle(sc->bar0res);
sc->bar1_bt = rman_get_bustag(sc->bar1res);
sc->bar1_bh = rman_get_bushandle(sc->bar1res);
Handles for each base address register are kept in the softc structure so that they can be used to write to the device
later.
These handles can then be used to read or write from the device registers with the bus_space_* functions. For
example, a driver might contain a shorthand function to read from a board specific register like this :
uint16_t
board_read(struct ni_softc *sc, uint16_t address) {
return bus_space_read_2(sc->bar1_bt, sc->bar1_bh, address);
}
void
board_write(struct ni_softc *sc, uint16_t address, uint16_t value) {
bus_space_write_2(sc->bar1_bt, sc->bar1_bh, address, value);
}
These functions exist in 8bit, 16bit, and 32bit versions and you should use bus_space_{read|write}_{1|2|4}
accordingly.
170
Chapter 20 PCI Devices
20.2.2 Interrupts
Interrupts are allocated from the object-oriented bus code in a way similar to the memory resources. First an IRQ
resource must be allocated from the parent bus, and then the interrupt handler must be setup to deal with this IRQ.
Again, a sample from a device attach() function says more than words.
sc->irqid = 0x0;
sc->irqres = bus_alloc_resource(dev, SYS_RES_IRQ, &(sc->irqid),
0, ~0, 1, RF_SHAREABLE | RF_ACTIVE);
if (sc->irqres == NULL) {
uprintf("IRQ allocation failed!\n");
error = ENXIO;
goto fail3;
}
sc->irq_bt = rman_get_bustag(sc->irqres);
sc->irq_bh = rman_get_bushandle(sc->irqres);
20.2.3 DMA
On the PC, peripherals that want to do bus-mastering DMA must deal with physical addresses. This is a problem
since FreeBSD uses virtual memory and deals almost exclusively with virtual addresses. Fortunately, there is a
function, vtophys() to help.
#include <vm/vm.h>
#include <vm/pmap.h>
#define vtophys(virtual_address) (...)
The solution is a bit different on the alpha however, and what we really want is a function called vtobus().
#if defined(__alpha__)
171
Chapter 20 PCI Devices
172
Chapter 21 Common Access Method SCSI
Controllers
This chapter was written by Sergey Babkin <[email protected] > Modifications for the handbook made by
Murray Stokely <[email protected] >.
21.1 Synopsis
This document assumes that the reader has a general understanding of device drivers in FreeBSD and of the SCSI
protocol. Much of the information in this document was extracted from the drivers :
• Peripheral Modules - a driver for peripheral devices (disk, tape, CDROM, etc.)
• SCSI Interface Modules (SIM) - a Host Bus Adapter drivers for connecting to an I/O bus such as SCSI or IDE.
173
Chapter 21 Common Access Method SCSI Controllers
A peripheral driver receives requests from the OS, converts them to a sequence of SCSI commands and passes these
SCSI commands to a SCSI Interface Module. The SCSI Interface Module is responsible for passing these commands
to the actual hardware (or if the actual hardware is not SCSI but, for example, IDE then also converting the SCSI
commands to the native commands of the hardware).
Because we are interested in writing a SCSI adapter driver here, from this point on we will consider everything from
the SIM standpoint.
A typical SIM driver needs to include the following CAM-related header files:
#include <cam/cam.h>
#include <cam/cam_ccb.h>
#include <cam/cam_sim.h>
#include <cam/cam_xpt_sim.h>
#include <cam/cam_debug.h>
#include <cam/scsi/scsi_all.h>
The first thing each SIM driver must do is register itself with the CAM subsystem. This is done during the driver’s
xxx_attach() function (here and further xxx_ is used to denote the unique driver name prefix). The
xxx_attach() function itself is called by the system bus auto-configuration code which we don’t describe here.
This is achieved in multiple steps: first it’s necessary to allocate the queue of requests associated with this SIM:
Here SIZE is the size of the queue to be allocated, maximal number of requests it could contain. It’s the number of
requests that the SIM driver can handle in parallel on one SCSI card. Commonly it can be calculated as:
174
Chapter 21 Common Access Method SCSI Controllers
Note that if we are not able to create a SIM descriptor we free the devq also because we can do nothing else with it
and we want to conserve memory.
If a SCSI card has multiple SCSI buses on it then each bus requires its own cam_sim structure.
An interesting question is what to do if a SCSI card has more than one SCSI bus, do we need one devq structure per
card or per SCSI bus? The answer given in the comments to the CAM code is: either way, as the driver’s author
prefers.
The arguments are :
Finally we register the SCSI buses associated with our SCSI adapter:
175
Chapter 21 Common Access Method SCSI Controllers
If there is one devq structure per SCSI bus (i.e. we consider a card with multiple buses as multiple cards with one bus
each) then the bus number will always be 0, otherwise each bus on the SCSI card should be get a distinct number.
Each bus needs its own separate structure cam_sim.
After that our controller is completely hooked to the CAM system. The value of devq can be discarded now: sim will
be passed as an argument in all further calls from CAM and devq can be derived from it.
CAM provides the framework for such asynchronous events. Some events originate from the lower levels (the SIM
drivers), some events originate from the peripheral drivers, some events originate from the CAM subsystem itself.
Any driver can register callbacks for some types of the asynchronous events, so that it would be notified if these
events occur.
A typical example of such an event is a device reset. Each transaction and event identifies the devices to which it
applies by the means of "path". The target-specific events normally occur during a transaction with this device. So
the path from that transaction may be re-used to report this event (this is safe because the event path is copied in the
event reporting routine but not deallocated nor passed anywhere further). Also it’s safe to allocate paths dynamically
at any time including the interrupt routines, although that incurs certain overhead, and a possible problem with this
approach is that there may be no free memory at that time. For a bus reset event we need to define a wildcard path
including all devices on the bus. So we can create the path for the future bus reset events in advance and avoid
problems with the future memory shortage:
if(xpt_create_path(&path, /*periph*/NULL,
cam_sim_path(sim), CAM_TARGET_WILDCARD,
CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
xpt_bus_deregister(cam_sim_path(sim));
cam_sim_free(sim, /*free_devq*/TRUE);
error; /* some code to handle the error */
}
softc->wpath = path;
softc->sim = sim;
176
Chapter 21 Common Access Method SCSI Controllers
If the driver can’t allocate this path it won’t be able to work normally, so in that case we dismantle that SCSI bus.
And we save the path pointer in the softc structure for future use. After that we save the value of sim (or we can also
discard it on the exit from xxx_probe() if we wish).
That’s all for a minimalistic initialization. To do things right there is one more issue left.
For a SIM driver there is one particularly interesting event: when a target device is considered lost. In this case
resetting the SCSI negotiations with this device may be a good idea. So we register a callback for this event with
CAM. The request is passed to CAM by requesting CAM action on a CAM control block for this type of request:
Now we take a look at the xxx_action() and xxx_poll() driver entry points.
Do some action on request of the CAM subsystem. Sim describes the SIM for the request, CCB is the request itself.
CCB stands for "CAM Control Block". It is a union of many specific instances, each describing arguments for some
type of transactions. All of these instances share the CCB header where the common part of arguments is stored.
CAM supports the SCSI controllers working in both initiator ("normal") mode and target (simulating a SCSI device)
mode. Here we only consider the part relevant to the initiator mode.
There are a few function and macros (in other words, methods) defined to access the public data in the struct sim:
177
Chapter 21 Common Access Method SCSI Controllers
The type of request is stored in ccb->ccb_h.func_code. So generally xxx_action() consists of a big switch:
switch(ccb_h->func_code) {
case ...:
...
default:
ccb_h->status = CAM_REQ_INVALID;
xpt_done(ccb);
break;
}
As can be seen from the default case (if an unknown command was received) the return code of the command is set
into ccb->ccb_h.status and the completed CCB is returned back to CAM by calling xpt_done(ccb).
xpt_done() does not have to be called from xxx_action(): For example an I/O request may be enqueued inside
the SIM driver and/or its SCSI controller. Then when the device would post an interrupt signaling that the processing
of this request is complete xpt_done() may be called from the interrupt handling routine.
Actually, the CCB status is not only assigned as a return code but a CCB has some status all the time. Before CCB is
passed to the xxx_action() routine it gets the status CCB_REQ_INPROG meaning that it’s in progress. There are
a surprising number of status values defined in /sys/cam/cam.h which should be able to represent the status of a
request in great detail. More interesting yet, the status is in fact a "bitwise or" of an enumerated status value (the
lower 6 bits) and possible additional flag-like bits (the upper bits). The enumerated values will be discussed later in
more detail. The summary of them can be found in the Errors Summary section. The possible status flags are:
• CAM_DEV_QFRZN - if the SIM driver gets a serious error (for example, the device does not respond to the
selection or breaks the SCSI protocol) when processing a CCB it should freeze the request queue by calling
xpt_freeze_simq(), return the other enqueued but not processed yet CCBs for this device back to the CAM
queue, then set this flag for the troublesome CCB and call xpt_done(). This flag causes the CAM subsystem to
unfreeze the queue after it handles the error.
• CAM_AUTOSNS_VALID - if the device returned an error condition and the flag CAM_DIS_AUTOSENSE is not
set in CCB the SIM driver must execute the REQUEST SENSE command automatically to extract the sense
(extended error information) data from the device. If this attempt was successful the sense data should be saved in
the CCB and this flag set.
• CAM_RELEASE_SIMQ - like CAM_DEV_QFRZN but used in case there is some problem (or resource shortage)
with the SCSI controller itself. Then all the future requests to the controller should be stopped by
178
Chapter 21 Common Access Method SCSI Controllers
xpt_freeze_simq(). The controller queue will be restarted after the SIM driver overcomes the shortage and
informs CAM by returning some CCB with this flag set.
• CAM_SIM_QUEUED - when SIM puts a CCB into its request queue this flag should be set (and removed when
this CCB gets dequeued before being returned back to CAM). This flag is not used anywhere in the CAM code
now, so its purpose is purely diagnostic.
The function xxx_action() is not allowed to sleep, so all the synchronization for resource access must be done
using SIM or device queue freezing. Besides the aforementioned flags the CAM subsystem provides functions
xpt_selease_simq() and xpt_release_devq() to unfreeze the queues directly, without passing a CCB to
CAM.
The CCB header contains the following fields:
179
Chapter 21 Common Access Method SCSI Controllers
180
Chapter 21 Common Access Method SCSI Controllers
Then allocate whatever data structures (such as card-dependent hardware control block) we need to process this
request. If we can’t then freeze the SIM queue and remember that we have a pending operation, return the CCB
back and ask CAM to re-queue it. Later when the resources become available the SIM queue must be unfrozen by
returning a ccb with the CAM_SIMQ_RELEASE bit set in its status. Otherwise, if all went well, link the CCB
with the hardware control block (HCB) and mark it as queued.
struct xxx_hcb *hcb = allocate_hcb(softc, unit, bus);
if(hcb == NULL) {
softc->flags |= RESOURCE_SHORTAGE;
xpt_freeze_simq(sim, /*count*/1);
ccb_h->status = CAM_REQUEUE_REQ;
xpt_done(ccb);
return;
}
Then set up the SCSI command. The command storage may be specified in the CCB in many interesting ways,
specified by the CCB flags. The command buffer can be contained in CCB or pointed to, in the latter case the
pointer may be physical or virtual. Since the hardware commonly needs physical address we always convert the
address to the physical one.
A NOT-QUITE RELATED NOTE: Normally this is done by a call to vtophys(), but for the PCI device (which
account for most of the SCSI controllers now) drivers’ portability to the Alpha architecture the conversion must be
done by vtobus() instead due to special Alpha quirks. [IMHO it would be much better to have two separate
functions, vtop() and ptobus() then vtobus() would be a simple superposition of them.] In case if a physical
address is requested it’s OK to return the CCB with the status CAM_REQ_INVALID, the current drivers do that.
But it’s also possible to compile the Alpha-specific piece of code, as in this example (there should be a more direct
way to do that, without conditional compilation in the drivers). If necessary a physical address can be also
converted or mapped back to a virtual address but with big pain, so we don’t do that.
if(ccb_h->flags & CAM_CDB_POINTER) {
/* CDB is a pointer */
181
Chapter 21 Common Access Method SCSI Controllers
if (dir == CAM_DIR_NONE)
goto end_data;
Then we check if the data is in one chunk or in a scatter-gather list, and the addresses are physical or virtual. The
SCSI controller may be able to handle only a limited number of chunks of limited length. If the request hits this
limitation we return an error. We use a special function to return the CCB to handle in one place the HCB resource
shortages. The functions to add chunks are driver-dependent, and here we leave them without detailed
implementation. See description of the SCSI command (CDB) handling for the details on the address-translation
issues. If some variation is too difficult or impossible to implement with a particular card it’s OK to return the
status CAM_REQ_INVALID. Actually, it seems like the scatter-gather ability is not used anywhere in the CAM
code now. But at least the case for a single non-scattered virtual buffer must be implemented, it’s actively used by
CAM.
int rv;
initialize_hcb_for_data(hcb);
182
Chapter 21 Common Access Method SCSI Controllers
183
Chapter 21 Common Access Method SCSI Controllers
If the controller is able to run REQUEST SENSE command all by itself then the value of the flag
CAM_DIS_AUTOSENSE should also be passed to it, to prevent automatic REQUEST SENSE if the CAM
subsystem does not want it.
The only thing left is to set up the timeout, pass our hcb to the hardware and return, the rest will be done by the
interrupt handler (or timeout handler).
ccb_h->timeout_ch = timeout(xxx_timeout, (caddr_t) hcb,
(ccb_h->timeout * hz) / 1000); /* convert milliseconds to ticks */
put_hcb_into_hardware_queue(hcb);
return;
ccb->ccb_h.ccb_hcb = 0;
if(hcb != NULL) {
untimeout(xxx_timeout, (caddr_t) hcb, ccb->ccb_h.timeout_ch);
/* we’re about to free a hcb, so the shortage has ended */
if(softc->flags & RESOURCE_SHORTAGE) {
softc->flags &= ~RESOURCE_SHORTAGE;
status |= CAM_RELEASE_SIMQ;
}
free_hcb(hcb); /* also removes hcb from any internal lists */
}
ccb->ccb_h.status = status |
(ccb->ccb_h.status & ~(CAM_STATUS_MASK|CAM_SIM_QUEUED));
xpt_done(ccb);
}
184
Chapter 21 Common Access Method SCSI Controllers
/* The SCSI bus reset may take a long time, in this case its completion
* should be checked by interrupt or timeout. But for simplicity
* we assume here that it’s really fast.
*/
reset_scsi_bus(softc);
185
Chapter 21 Common Access Method SCSI Controllers
ccb->ccb_h.status = CAM_REQ_CMP;
xpt_done(ccb);
if(abort_ccb->ccb_h.func_code != XPT_SCSI_IO) {
ccb->ccb_h.status = CAM_UA_ABORT;
xpt_done(ccb);
return;
}
Then it’s necessary to find this CCB in our queue. This can be done by walking the list of all our hardware control
blocks in search for one associated with this CCB:
struct xxx_hcb *hcb, *h;
hcb = NULL;
186
Chapter 21 Common Access Method SCSI Controllers
if(hcb == NULL) {
/* no such CCB in our queue */
ccb->ccb_h.status = CAM_PATH_INVALID;
xpt_done(ccb);
return;
}
hcb=found_hcb;
Now we look at the current processing status of the HCB. It may be either sitting in the queue waiting to be sent to
the SCSI bus, being transferred right now, or disconnected and waiting for the result of the command, or actually
completed by hardware but not yet marked as done by software. To make sure that we don’t get in any races with
hardware we mark the HCB as being aborted, so that if this HCB is about to be sent to the SCSI bus the SCSI
controller will see this flag and skip it.
int hstatus;
abort_again:
hstatus = get_hcb_status(hcb);
switch(hstatus) {
case HCB_SITTING_IN_QUEUE:
remove_hcb_from_hardware_queue(hcb);
/* FALLTHROUGH */
case HCB_COMPLETED:
/* this is an easy case */
free_hcb_and_ccb_done(hcb, abort_ccb, CAM_REQ_ABORTED);
break;
187
Chapter 21 Common Access Method SCSI Controllers
If the CCB is being transferred right now we would like to signal to the SCSI controller in some
hardware-dependent way that we want to abort the current transfer. The SCSI controller would set the SCSI
ATTENTION signal and when the target responds to it send an ABORT message. We also reset the timeout to
make sure that the target is not sleeping forever. If the command would not get aborted in some reasonable time
like 10 seconds the timeout routine would go ahead and reset the whole SCSI bus. Because the command will be
aborted in some reasonable time we can just return the abort request now as successfully completed, and mark the
aborted CCB as aborted (but not mark it as done yet).
case HCB_BEING_TRANSFERRED:
untimeout(xxx_timeout, (caddr_t) hcb, abort_ccb->ccb_h.timeout_ch);
abort_ccb->ccb_h.timeout_ch =
timeout(xxx_timeout, (caddr_t) hcb, 10 * hz);
abort_ccb->ccb_h.status = CAM_REQ_ABORTED;
/* ask the controller to abort that HCB, then generate
* an interrupt and stop
*/
if(signal_hardware_to_abort_hcb_and_stop(hcb) < 0) {
/* oops, we missed the race with hardware, this transaction
* got off the bus before we aborted it, try again */
goto abort_again;
}
break;
If the CCB is in the list of disconnected then set it up as an abort request and re-queue it at the front of hardware
queue. Reset the timeout and report the abort request to be completed.
case HCB_DISCONNECTED:
untimeout(xxx_timeout, (caddr_t) hcb, abort_ccb->ccb_h.timeout_ch);
abort_ccb->ccb_h.timeout_ch =
timeout(xxx_timeout, (caddr_t) hcb, 10 * hz);
put_abort_message_into_hcb(hcb);
put_hcb_at_the_front_of_hardware_queue(hcb);
break;
}
ccb->ccb_h.status = CAM_REQ_CMP;
xpt_done(ccb);
return;
That’s all for the ABORT request, although there is one more issue. Because the ABORT message cleans all the
ongoing transactions on a LUN we have to mark all the other active transactions on this LUN as aborted. That
should be done in the interrupt routine, after the transaction gets aborted.
Implementing the CCB abort as a function may be quite a good idea, this function can be re-used if an I/O
transaction times out. The only difference would be that the timed out transaction would return the status
CAM_CMD_TIMEOUT for the timed out request. Then the case XPT_ABORT would be small, like that:
188
Chapter 21 Common Access Method SCSI Controllers
case XPT_ABORT:
struct ccb *abort_ccb;
abort_ccb = ccb->cab.abort_ccb;
if(abort_ccb->ccb_h.func_code != XPT_SCSI_IO) {
ccb->ccb_h.status = CAM_UA_ABORT;
xpt_done(ccb);
return;
}
if(xxx_abort_ccb(abort_ccb, CAM_REQ_ABORTED) < 0)
/* no such CCB in our queue */
ccb->ccb_h.status = CAM_PATH_INVALID;
else
ccb->ccb_h.status = CAM_REQ_CMP;
xpt_done(ccb);
return;
189
Chapter 21 Common Access Method SCSI Controllers
Two sets of negotiated parameters are supported, the user settings and the current settings. The user settings are
not really used much in the SIM drivers, this is mostly just a piece of memory where the upper levels can store
(and later recall) its ideas about the parameters. Setting the user parameters does not cause re-negotiation of the
transfer rates. But when the SCSI controller does a negotiation it must never set the values higher than the user
parameters, so it’s essentially the top boundary.
The current settings are, as the name says, current. Changing them means that the parameters must be
re-negotiated on the next transfer. Again, these "new current settings" are not supposed to be forced on the device,
just they are used as the initial step of negotiations. Also they must be limited by actual capabilities of the SCSI
controller: for example, if the SCSI controller has 8-bit bus and the request asks to set 16-bit wide transfers this
parameter must be silently truncated to 8-bit transfers before sending it to the device.
One caveat is that the bus width and synchronous parameters are per target while the disconnection and tag
enabling parameters are per lun.
The recommended implementation is to keep 3 sets of negotiated (bus width and synchronous transfer) parameters:
cts = &ccb->cts;
targ = ccb_h->target_id;
lun = ccb_h->target_lun;
flags = cts->flags;
if(flags & CCB_TRANS_USER_SETTINGS) {
if(flags & CCB_TRANS_SYNC_RATE_VALID)
softc->user_sync_period[targ] = cts->sync_period;
if(flags & CCB_TRANS_SYNC_OFFSET_VALID)
softc->user_sync_offset[targ] = cts->sync_offset;
if(flags & CCB_TRANS_BUS_WIDTH_VALID)
softc->user_bus_width[targ] = cts->bus_width;
190
Chapter 21 Common Access Method SCSI Controllers
Then when the next I/O request will be processed it will check if it has to re-negotiate, for example by calling the
function target_negotiated(hcb). It can be implemented like this:
int
target_negotiated(struct xxx_hcb *hcb)
{
struct softc *softc = hcb->softc;
int targ = hcb->targ;
191
Chapter 21 Common Access Method SCSI Controllers
narrow asynchronous mode, the goal and current values must be initialized to the maximal values supported by
controller.
ccg = &ccb->ccg;
size_mb = ccg->volume_size
/ ((1024L * 1024L) / ccg->block_size);
extended = check_cards_EEPROM_for_extended_geometry(softc);
192
Chapter 21 Common Access Method SCSI Controllers
This gives the general idea, the exact calculation depends on the quirks of the particular BIOS. If BIOS provides
no way set the "extended translation" flag in EEPROM this flag should normally be assumed equal to 1. Other
popular geometries are:
128 heads, 63 sectors - Symbios controllers
16 heads, 63 sectors - old controllers
Some system BIOSes and SCSI BIOSes fight with each other with variable success, for example a combination of
Symbios 875/895 SCSI and Phoenix BIOS can give geometry 128/63 after power up and 255/63 after a hard reset
or soft reboot.
• XPT_PATH_INQ - path inquiry, in other words get the SIM driver and SCSI controller (also known as HBA - Host
Bus Adapter) properties
The properties are returned in the instance "struct ccb_pathinq cpi" of the union ccb:
• version_num - the SIM driver version number, now all drivers use 1
• hba_inquiry - bitmask of features supported by the controller:
• PI_MDP_ABLE - supports MDP message (something from SCSI3?)
• PI_WIDE_32 - supports 32 bit wide SCSI
• PI_WIDE_16 - supports 16 bit wide SCSI
• PI_SDTR_ABLE - can negotiate synchronous transfer rate
• PI_LINKED_CDB - supports linked commands
• PI_TAG_ABLE - supports tagged commands
• PI_SOFT_RST - supports soft reset alternative (hard reset and soft reset are mutually exclusive within a SCSI
bus)
• target_sprt - flags for target mode support, 0 if unsupported
• hba_misc - miscellaneous controller features:
• PIM_SCANHILO - bus scans from high ID to low ID
• PIM_NOREMOVE - removable devices not included in scan
• PIM_NOINITIATOR - initiator role not supported
193
Chapter 21 Common Access Method SCSI Controllers
After setting the values set the status to CAM_REQ_CMP and mark the CCB as done.
21.3 Polling
The poll function is used to simulate the interrupts when the interrupt subsystem is not functioning (for example,
when the system has crashed and is creating the system dump). The CAM subsystem sets the proper interrupt level
before calling the poll routine. So all it needs to do is to call the interrupt routine (or the other way around, the poll
194
Chapter 21 Common Access Method SCSI Controllers
routine may be doing the real action and the interrupt routine would just call the poll routine). Why bother about a
separate function then ? Because of different calling conventions. The xxx_poll routine gets the struct cam_sim
pointer as its argument when the PCI interrupt routine by common convention gets pointer to the struct xxx_softc
and the ISA interrupt routine gets just the device unit number. So the poll routine would normally look as:
static void
xxx_poll(struct cam_sim *sim)
{
xxx_intr((struct xxx_softc *)cam_sim_softc(sim)); /* for PCI device */
}
or
static void
xxx_poll(struct cam_sim *sim)
{
xxx_intr(cam_sim_unit(sim)); /* for ISA device */
}
static void
ahc_async(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg)
195
Chapter 21 Common Access Method SCSI Controllers
switch (code) {
case AC_LOST_DEVICE:
targ = xpt_path_target_id(path);
if(targ <= OUR_MAX_SUPPORTED_TARGET) {
clean_negotiations(softc, targ);
/* send indication to CAM */
neg.bus_width = 8;
neg.sync_period = neg.sync_offset = 0;
neg.valid = (CCB_TRANS_BUS_WIDTH_VALID
| CCB_TRANS_SYNC_RATE_VALID | CCB_TRANS_SYNC_OFFSET_VALID);
xpt_async(AC_TRANSFER_NEG, path, &neg);
}
break;
default:
break;
}
21.5 Interrupts
The exact type of the interrupt routine depends on the type of the peripheral bus (PCI, ISA and so on) to which the
SCSI controller is connected.
The interrupt routines of the SIM drivers run at the interrupt level splcam. So splcam() should be used in the driver
to synchronize activity between the interrupt routine and the rest of the driver (for a multiprocessor-aware driver
things get yet more interesting but we ignore this case here). The pseudo-code in this document happily ignores the
problems of synchronization. The real code must not ignore them. A simple-minded approach is to set splcam() on
the entry to the other routines and reset it on return thus protecting them by one big critical section. To make sure that
the interrupt level will be always restored a wrapper function can be defined, like:
static void
xxx_action(struct cam_sim *sim, union ccb *ccb)
{
int s;
s = splcam();
xxx_action1(sim, ccb);
splx(s);
}
static void
xxx_action1(struct cam_sim *sim, union ccb *ccb)
{
... process the request ...
196
Chapter 21 Common Access Method SCSI Controllers
This approach is simple and robust but the problem with it is that interrupts may get blocked for a relatively long
time and this would negatively affect the system’s performance. On the other hand the functions of the spl() family
have rather high overhead, so vast amount of tiny critical sections may not be good either.
The conditions handled by the interrupt routine and the details depend very much on the hardware. We consider the
set of "typical" conditions.
First, we check if a SCSI reset was encountered on the bus (probably caused by another SCSI controller on the same
SCSI bus). If so we drop all the enqueued and disconnected requests, report the events and re-initialize our SCSI
controller. It is important that during this initialization the controller won’t issue another reset or else two controllers
on the same SCSI bus could ping-pong resets forever. The case of fatal controller error/hang could be handled in the
same place, but it will probably need also sending RESET signal to the SCSI bus to reset the status of the
connections with the SCSI devices.
int fatal=0;
struct ccb_trans_settings neg;
struct cam_path *path;
if( detected_scsi_reset(softc)
|| (fatal = detected_fatal_controller_error(softc)) ) {
int targ, lun;
struct xxx_hcb *h, *hh;
197
Chapter 21 Common Access Method SCSI Controllers
If interrupt is not caused by a controller-wide condition then probably something has happened to the current
hardware control block. Depending on the hardware there may be other non-HCB-related events, we just do not
consider them here. Then we analyze what happened to this HCB:
hcb = get_current_hcb(softc);
if(hcb == NULL) {
/* either stray interrupt or something went very wrong
* or this is something hardware-dependent
198
Chapter 21 Common Access Method SCSI Controllers
*/
handle as necessary;
return;
}
targ = hcb->target;
hcb_status = get_status_of_current_hcb(softc);
First we check if the HCB has completed and if so we check the returned SCSI status.
if(hcb_status == COMPLETED) {
scsi_status = get_completion_status(hcb);
Then look if this status is related to the REQUEST SENSE command and if so handle it in a simple way.
Else the command itself has completed, pay more attention to details. If auto-sense is not disabled for this CCB and
the command has failed with sense data then run REQUEST SENSE command to receive that data.
hcb->ccb->csio.scsi_status = scsi_status;
calculate_residue(hcb);
199
Chapter 21 Common Access Method SCSI Controllers
One typical thing would be negotiation events: negotiation messages received from a SCSI target (in answer to our
negotiation attempt or by target’s initiative) or the target is unable to negotiate (rejects our negotiation messages or
does not answer them).
switch(hcb_status) {
case TARGET_REJECTED_WIDE_NEG:
/* revert to 8-bit bus */
softc->current_bus_width[targ] = softc->goal_bus_width[targ] = 8;
/* report the event */
neg.bus_width = 8;
neg.valid = CCB_TRANS_BUS_WIDTH_VALID;
xpt_async(AC_TRANSFER_NEG, hcb->ccb.ccb_h.path_id, &neg);
continue_current_hcb(softc);
return;
case TARGET_ANSWERED_WIDE_NEG:
{
int wd;
wd = get_target_bus_width_request(softc);
if(wd <= softc->goal_bus_width[targ]) {
/* answer is acceptable */
softc->current_bus_width[targ] =
softc->goal_bus_width[targ] = neg.bus_width = wd;
wd = get_target_bus_width_request(softc);
wd = min (wd, OUR_BUS_WIDTH);
wd = min (wd, softc->user_bus_width[targ]);
200
Chapter 21 Common Access Method SCSI Controllers
if(wd != softc->current_bus_width[targ]) {
/* the bus width has changed */
softc->current_bus_width[targ] =
softc->goal_bus_width[targ] = neg.bus_width = wd;
Then we handle any errors that could have happened during auto-sense in the same simple-minded way as before.
Otherwise we look closer at the details again.
switch(hcb_status) {
The next event we consider is unexpected disconnect. Which is considered normal after an ABORT or BUS DEVICE
RESET message and abnormal in other cases.
case UNEXPECTED_DISCONNECT:
if(requested_abort(hcb)) {
/* abort affects all commands on that target+LUN, so
* mark all disconnected HCBs on that target+LUN as aborted too
*/
for(h = softc->first_discon_hcb[hcb->target][hcb->lun];
h != NULL; h = hh) {
hh=h->next;
free_hcb_and_ccb_done(h, h->ccb, CAM_REQ_ABORTED);
}
ccb_status = CAM_REQ_ABORTED;
} else if(requested_bus_device_reset(hcb)) {
int lun;
201
Chapter 21 Common Access Method SCSI Controllers
/* send event */
xpt_async(AC_SENT_BDR, hcb->ccb->ccb_h.path_id, NULL);
If the target refuses to accept tags we notify CAM about that and return back all commands for this LUN:
case TAGS_REJECTED:
/* report the event */
neg.flags = 0 & ~CCB_TRANS_TAG_ENB;
neg.valid = CCB_TRANS_TQ_VALID;
xpt_async(AC_TRANSFER_NEG, hcb->ccb.ccb_h.path_id, &neg);
ccb_status = CAM_MSG_REJECT_REC;
/* request the further code to freeze the queue */
hcb->ccb->ccb_h.status |= CAM_DEV_QFRZN;
lun_to_freeze = hcb->lun;
break;
Then we check a number of other conditions, with processing basically limited to setting the CCB status:
case SELECTION_TIMEOUT:
ccb_status = CAM_SEL_TIMEOUT;
/* request the further code to freeze the queue */
hcb->ccb->ccb_h.status |= CAM_DEV_QFRZN;
lun_to_freeze = CAM_LUN_WILDCARD;
break;
case PARITY_ERROR:
ccb_status = CAM_UNCOR_PARITY;
202
Chapter 21 Common Access Method SCSI Controllers
break;
case DATA_OVERRUN:
case ODD_WIDE_TRANSFER:
ccb_status = CAM_DATA_RUN_ERR;
break;
default:
/* all other errors are handled in a generic way */
ccb_status = CAM_REQ_CMP_ERR;
/* request the further code to freeze the queue */
hcb->ccb->ccb_h.status |= CAM_DEV_QFRZN;
lun_to_freeze = CAM_LUN_WILDCARD;
break;
}
Then we check if the error was serious enough to freeze the input queue until it gets proceeded and do so if it is:
if(targ == h->targ
&& (lun_to_freeze == CAM_LUN_WILDCARD || lun_to_freeze == h->lun) )
free_hcb_and_ccb_done(h, h->ccb, CAM_REQUEUE_REQ);
}
}
free_hcb_and_ccb_done(hcb, hcb->ccb, ccb_status);
schedule_next_hcb(softc);
return;
This concludes the generic interrupt handling although specific controllers may require some additions.
203
Chapter 21 Common Access Method SCSI Controllers
• CAM_RESRC_UNAVAIL - some resource is temporarily unavailable and the SIM driver can not generate an event
when it will become available. An example of this resource would be some intra-controller hardware resource for
which the controller does not generate an interrupt when it becomes available.
• CAM_UNCOR_PARITY - unrecovered parity error occurred
• CAM_DATA_RUN_ERR - data overrun or unexpected data phase (going in other direction than specified in
CAM_DIR_MASK) or odd transfer length for wide transfer
• CAM_SEL_TIMEOUT - selection timeout occurred (target does not respond)
• CAM_CMD_TIMEOUT - command timeout occurred (the timeout function ran)
• CAM_SCSI_STATUS_ERROR - the device returned error
• CAM_AUTOSENSE_FAIL - the device returned error and the REQUEST SENSE COMMAND failed
• CAM_MSG_REJECT_REC - MESSAGE REJECT message was received
• CAM_SCSI_BUS_RESET - received SCSI bus reset
• CAM_REQ_CMP_ERR - "impossible" SCSI phase occurred or something else as weird or just a generic error if
further detail is not available
• CAM_UNEXP_BUSFREE - unexpected disconnect occurred
• CAM_BDR_SENT - BUS DEVICE RESET message was sent to the target
• CAM_UNREC_HBA_ERROR - unrecoverable Host Bus Adapter Error
• CAM_REQ_TOO_BIG - the request was too large for this controller
• CAM_REQUEUE_REQ - this request should be re-queued to preserve transaction ordering. This typically occurs
when the SIM recognizes an error that should freeze the queue and must place other queued requests for the target
at the sim level back into the XPT queue. Typical cases of such errors are selection timeouts, command timeouts
and other like conditions. In such cases the troublesome command returns the status indicating the error, the and
the other commands which have not be sent to the bus yet get re-queued.
• CAM_LUN_INVALID - the LUN ID in the request is not supported by the SCSI controller
• CAM_TID_INVALID - the target ID in the request is not supported by the SCSI controller
204
Chapter 21 Common Access Method SCSI Controllers
here too). Also we should reset the whole SCSI bus if a device reset request got stuck. So after all the timeout
function would look like:
static void
xxx_timeout(void *arg)
{
struct xxx_hcb *hcb = (struct xxx_hcb *)arg;
struct xxx_softc *softc;
struct ccb_hdr *ccb_h;
softc = hcb->softc;
ccb_h = &hcb->ccb->ccb_h;
When we abort a request all the other disconnected requests to the same target/LUN get aborted too. So there appears
a question, should we return them with status CAM_REQ_ABORTED or CAM_CMD_TIMEOUT ? The current
drivers use CAM_CMD_TIMEOUT. This seems logical because if one request got timed out then probably
something really bad is happening to the device, so if they would not be disturbed they would time out by themselves.
205
Chapter 22 USB Devices
This chapter was written by Nick Hibma <[email protected] >. Modifications made for the handbook by
Murray Stokely <[email protected] >.
22.1 Introduction
The Universal Serial Bus (USB) is a new way of attaching devices to personal computers. The bus architecture
features two-way communication and has been developed as a response to devices becoming smarter and requiring
more interaction with the host. USB support is included in all current PC chipsets and is therefore available in all
recently built PCs. Apple’s introduction of the USB-only iMac has been a major incentive for hardware
manufacturers to produce USB versions of their devices. The future PC specifications specify that all legacy
connectors on PCs should be replaced by one or more USB connectors, providing generic plug and play capabilities.
Support for USB hardware was available at a very early stage in NetBSD and was developed by Lennart Augustsson
for the NetBSD project. The code has been ported to FreeBSD and we are currently maintaining a shared code base.
For the implementation of the USB subsystem a number of features of USB are important.
Lennart Augustsson has done most of the implementation of the USB support for the NetBSD project. Many thanks
for this incredible amount of work. Many thanks also to Ardy and Dirk for their comments and proofreading of this
paper.
• Devices connect to ports on the computer directly or on devices called hubs, forming a treelike device structure.
• The devices can be connected and disconnected at run time.
• Devices can suspend themselves and trigger resumes of the host system
• As the devices can be powered from the bus, the host software has to keep track of power budgets for each hub.
• Different quality of service requirements by the different device types together with the maximum of 126 devices
that can be connected to the same bus, require proper scheduling of transfers on the shared bus to take full
advantage of the 12Mbps bandwidth available. (over 400Mbps with USB 2.0)
• Devices are intelligent and contain easily accessible information about themselves
The development of drivers for the USB subsystem and devices connected to it is supported by the specifications that
have been developed and will be developed. These specifications are publicly available from the USB home pages.
Apple has been very strong in pushing for standards based drivers, by making drivers for the generic classes
available in their operating system MacOS and discouraging the use of separate drivers for each new device. This
chapter tries to collate essential information for a basic understanding of the present implementation of the USB
stack in FreeBSD/NetBSD. It is recommended however to read it together with the relevant specifications mentioned
in the references below.
206
Chapter 22 USB Devices
207
Chapter 22 USB Devices
provide an interrupt pipe that reports changes happening at its ports. There are currently two specifications for host
controllers available: Universal Host Controller Interface (http://developer.intel.com/design/USB/UHCI11D.htm)
(UHCI; Intel) and Open Host Controller Interface (http://www.compaq.com/productinfo/development/openhci.html)
(OHCI; Compaq, Microsoft, National Semiconductor). The UHCI specification has been designed to reduce
hardware complexity byrequiring the host controller driver to supply a complete schedule of the transfers for each
frame. OHCI type controllers are much more independent by providing a more abstract interface doing alot of work
themselves.
22.2.1 UHCI
The UHCI host controller maintains a framelist with 1024 pointers to per frame data structures. It understands two
different data types: transfer descriptors (TD) and queue heads (QH). Each TD represents a packet to be
communicated to or from a device endpoint. QHs are a means to groupTDs (and QHs) together.
Each transfer consists of one or more packets. The UHCI driver splits large transfers into multiple packets. For every
transfer, apart from isochronous transfers, a QH is allocated. For every type of transfer these QHs are collected at a
QH for that type. Isochronous transfers have to be executed first because of the fixed latency requirement and are
directly referred to by the pointer in the framelist. The last isochronous TD refers to the QH for interrupt transfers for
that frame. All QHs for interrupt transfers point at the QH for control transfers, which in turn points at the QH for
bulk transfers. The following diagram gives a graphical overview of this:
This results in the following schedule being run in each frame. After fetching the pointer for the current frame from
the framelist the controller first executes the TDs for all the isochronous packets in that frame. The last of these TDs
refers to the QH for the interrupt transfers for thatframe. The host controller will then descend from that QH to the
QHs for the individual interrupt transfers. After finishing that queue, the QH for the interrupt transfers will refer the
controller to the QH for all control transfers. It will execute all the subqueues scheduled there, followed by all the
transfers queued at the bulk QH. To facilitate the handling of finished or failed transfers different types of interrupts
are generatedby the hardware at the end of each frame. In the last TD for a transfer the Interrupt-On Completion bit
is set by the HC driver to flag an interrupt when the transfer has completed. An error interrupt is flagged if a TD
reaches its maximum error count. If the short packet detect bit is set in a TD and less than the set packet length is
transferred this interrupt is flagged to notify the controller driver of the completed transfer. It is the host controller
driver’s task to find out which transfer has completed or produced an error. When called the interrupt service routine
will locate all the finished transfers and call their callbacks.
See for a more elaborate description the UHCI specification. (http://developer.intel.com/design/USB/UHCI11D.htm)
22.2.2 OHCI
Programming an OHCI host controller is much simpler. The controller assumes that a set of endpoints is available,
and is aware of scheduling priorities and the ordering of the types of transfers in a frame. The main data structure
used by the host controller is the endpoint descriptor (ED) to which aqueue of transfer descriptors (TDs) is attached.
208
Chapter 22 USB Devices
The ED contains the maximum packet size allowed for an endpoint and the controller hardware does the splitting
into packets. The pointers to the data buffers are updated after each transfer and when the start and end pointer are
equal, the TD is retired to the done-queue. The four types of endpoints have their own queues. Control and bulk
endpoints are queued each at their own queue. Interrupt EDs are queued in a tree, with the level in the tree defining
the frequency at which they run.
framelist interruptisochronous control bulk
The schedule being run by the host controller in each frame looks as follows. The controller will first run the
non-periodic control and bulk queues, up to a time limit set by the HC driver. Then the interrupt transfers for that
frame number are run, by using the lower five bits of the frame number as an index into level 0 of the tree of
interrupts EDs. At the end of this tree the isochronous EDs are connected and these are traversed subsequently. The
isochronous TDs contain the frame number of the first frame the transfer should be run in. After all the periodic
transfers have been run, the control and bulk queues are traversed again. Periodically the interrupt service routine is
called to process the done queue and call the callbacks for each transfer and reschedule interrupt and isochronous
endpoints.
See for a more elaborate description the OHCI specification
(http://www.compaq.com/productinfo/development/openhci.html). Services layer The middle layer provides access
to the device in a controlled way and maintains resources inuse by the different drivers and the services layer. The
layer takes care of the following aspects:
209
Chapter 22 USB Devices
Within each interface 0 or more endpoints can be specified. Endpoints are the unidirectional access points for
communicating with a device. They provide buffers to temporarily store incoming or outgoing data from the device.
Each endpoint has a unique address within a configuration, the endpoint’s number plus its direction. The default
endpoint, endpoint 0, is not part of any interface and available in all configurations. It is managed by the services
layer and not directly available to device drivers.
Level 0 Level 1 Level 2 Slot 0
Slot 3 Slot 2 Slot 1
(Only 4 out of 32 slots shown)
This hierarchical configuration information is described in the device by a standard set of descriptors (see section 9.6
of the USB specification [ 2]). They can be requested through the Get Descriptor Request. The services layer caches
these descriptors to avoid unnecessary transferson the USB bus. Access to the descriptors is provided through
function calls.
• Device descriptors: General information about the device, like Vendor, Product and Revision Id, supported device
class, subclass and protocol if applicable, maximum packet size for the default endpoint, etc.
• Configuration descriptors: The number of interfaces in this configuration, suspend and resume functionality
supported and power requirements.
• Interface descriptors: interface class, subclass and protocol if applicable, number of alternate settings for the
interface and the number of endpoints.
• Endpoint descriptors: Endpoint address, direction and type, maximum packet size supported and polling frequency
if type is interrupt endpoint. There is no descriptor for thedefault endpoint (endpoint 0) and it is never counted in
an interface descriptor.
• String descriptors: In the other descriptors string indices are supplied for some fields.These can be used to retrieve
descriptive strings, possibly in multiple languages.
Class specifications can add their own descriptor types that are available through the GetDescriptor Request.
Pipes Communication to end points on a device flows through so-called pipes. Drivers submit transfers to endpoints
to a pipe and provide a callback to be called on completion or failure of the transfer (asynchronous transfers) or wait
for completion (synchronous transfer). Transfers to an endpoint are serialised in the pipe. A transfer can either
complete, fail or time-out (if a time-out has been set). There are two types of time-outs for transfers. Time-outs can
happen due to time-out on the USBbus (milliseconds). These time-outs are seen as failures and can be due to
disconnection of the device. A second form of time-out is implemented in software and is triggered when a transfer
does not complete within a specified amount of time (seconds). These are caused by a device acknowledging
negatively (NAK) the transferred packets. The cause for this is the device not being ready to receive data, buffer
under- or overrun or protocol errors.
If a transfer over a pipe is larger than the maximum packet size specified in the associated endpoint descriptor, the
host controller (OHCI) or the HC driver (UHCI) will split the transfer into packets of maximum packet size, with the
210
Chapter 22 USB Devices
211
Chapter 22 USB Devices
address 0. The services layer will proceed to retrieve the various descriptors through the default pipe. After that it
will send a Set Address request to move the device away from the default device address (address 0). Multiple device
drivers might be able to support the device. For example a modem driver might beable to support an ISDN TA
through the AT compatibility interface. A driver for that specific model of the ISDN adapter might however be able
to provide much better support for this device. To support this flexibility, the probes return priorities indicating their
level of support. Support for a specific revision of a product ranks the highest and the generic driver the lowest
priority. It might also be that multiple drivers could attach to one device if there are multiple interfaceswithin one
configuration. Each driver only needs to support a subset of the interfaces.
The probing for a driver for a newly attached device checks first for device specific drivers. If notfound, the probe
code iterates over all supported configurations until a driver attaches in a configuration. To support devices with
multiple drivers on different interfaces, the probe iteratesover all interfaces in a configuration that have not yet been
claimed by a driver. Configurations that exceed the power budget for the hub are ignored. During attach the driver
should initialise the device to its proper state, but not reset it, as this will make the device disconnect itself from the
bus and restart the probing process for it. To avoid consuming unnecessary bandwidth should not claim the interrupt
pipe at attach time, but should postpone allocating the pipe until the file is opened and the data is actually used.
When the file is closed the pipe should be closed again, eventhough the device might still be attached.
212
Chapter 22 USB Devices
From these pages a growing number of deviceclass specifications are available. These specifications specify what a
compliant device should look like from a driver perspective, basic functionality it needs to provide and the protocol
that is to be used over the communication channels. The USB specification [ 2] includes the description of the Hub
Class. A class specification for Human Interface Devices (HID) has been created to cater for keyboards, tablets,
bar-code readers, buttons, knobs, switches, etc. A third example is the class specification for mass storage devices.
For a full list of device classes see the developers sectionon the USB home pages [ 1].
For many devices the protocol information has not yet been published however. Information on the protocol being
used might be available from the company making the device. Some companies will require you to sign a Non
-Disclosure Agreement (NDA) before giving you the specifications. This in most cases precludes making the driver
open source.
Another good source of information is the Linux driver sources, as a number of companies have started to provide
drivers for Linux for their devices. It is always a good idea to contact the authors of those drivers for their source of
information.
Example: Human Interface Devices The specification for the Human Interface Devices like keyboards, mice, tablets,
buttons, dials,etc. is referred to in other device class specifications and is used in many devices.
For example audio speakers provide endpoints to the digital to analogue converters and possibly an extra pipe for a
microphone. They also provide a HID endpoint in a separate interface for the buttons and dials on the front of the
device. The same is true for the monitor control class. It is straightforward to build support for these interfaces
through the available kernel and userland libraries together with the HID class driver or the generic driver. Another
device that serves as an example for interfaces within one configuration driven by different device drivers is a cheap
keyboard with built-in legacy mouse port. To avoid having the cost of including the hardware for a USB hub in the
device, manufacturers combined the mouse data received from the PS/2 port on the back of the keyboard and the
keypresses from the keyboard into two separate interfaces in the same configuration. The mouse and keyboard
drivers each attach to the appropriate interface and allocate the pipes to the two independent endpoints.
Example: Firmware download Many devices that have been developed are based on a general purpose processor with
anadditional USB core added to it. Because the development of drivers and firmware for USB devices is still very
new, many devices require the downloading of the firmware after they have been connected.
The procedure followed is straightforward. The device identifies itself through a vendor and product Id. The first
driver probes and attaches to it and downloads the firmware into it. After that the device soft resets itself and the
driver is detached. After a short pause the devicere announces its presence on the bus. The device will have changed
its vendor/product/revision Id to reflect the fact that it has been supplied with firmware and as a consequence a
second driver will probe it and attach to it.
An example of these types of devices is the ActiveWire I/O board, based on the EZ-USB chip. For this chip a generic
firmware downloader is available. The firmware downloaded into the ActiveWire board changes the revision Id. It
will then perform a soft reset of the USB part of the EZ-USB chip to disconnect from the USB bus and again
reconnect.
Example: Mass Storage Devices Support for mass storage devices is mainly built around existing protocols. The
213
Chapter 22 USB Devices
Iomega USB Zipdrive is based on the SCSI version of their drive. The SCSI commands and status messages are
wrapped in blocks and transferred over the bulk pipes to and from the device, emulating a SCSI controller over the
USB wire. ATAPI and UFI commands are supported in a similar fashion.
The Mass Storage Specification supports 2 different types of wrapping of the command block.The initial attempt was
based on sending the command and status through the default pipe and using bulk transfers for the data to be moved
between the host and the device. Based on experience a second approach was designed that was based on wrapping
the command and status blocks and sending them over the bulk out and in endpoint. The specification specifies
exactly what has to happen when and what has to be done in case an error condition is encountered. The biggest
challenge when writing drivers for these devices is to fit USB based protocol into theexisting support for mass
storage devices. CAM provides hooks to do this in a fairly straight forward way. ATAPI is less simple as historically
the IDE interface has never had many different appearances.
The support for the USB floppy from Y-E Data is again less straightforward as a new command set has been
designed.
214
Chapter 23 NewBus
This chapter will talk about the FreeBSD NewBus architecture.
215
XII. Architectures
Chapter 24 x86 Assembly Language
Programming
This chapter was written by G. Adam Stanislav. Whiz Kid Technomagic (http://www.whizkidtech.net/)
24.1 Synopsis
Assembly language programing under Unix is highly undocumented. It is generally assumed that no one would ever
want to use it because various Unix systems run on different microprocessors, so everything should be written in C
for portability.
In reality, C portability is quite a myth. Even C programs need to be modified when ported from one Unix to another,
regardless of what processor each runs on. Typically, such a program is full of conditional statements depending on
the system it is compiled for.
Even if we believe that all of Unix software should be written in C, or some other high-level language, we still need
assembly language programmers: Who else would write the section of C library that accesses the kernel?
In this chapter I will attempt to show you how you can use assembly language writing Unix programs, specifically
under FreeBSD.
This chapter does not explain the basics of assembly language. There are enough resources about that (for a complete
online course in assembly language, see Randall Hyde’s Art of Assembly Language (http://webster.cs.ucr.edu/); or if
you prefer a printed book, take a look at Jeff Duntemann’s Assembly Language Step-by-Step
(http://www.int80h.org/cgi-bin/isbn?isbn=0471375233)). However, once the chapter is finished, any assembly
language programmer will be able to write programs for FreeBSD quickly and efficiently.
Copyright © 2000-2001 G. Adam Stanislav. All rights reserved.
217
Chapter 24 x86 Assembly Language Programming
The other is /usr/ports/devel/nasm. It uses the Intel syntax. Its main advantage is that it can assemble code for many
operating systems. It needs to be installed separately, but is completely free.
This chapter uses nasm syntax because most assembly language programmers coming to FreeBSD from other
operating systems will find it easier to understand. And, because, quite frankly, that is what I am used to.
This convention is very convenient, and quite superior to the Microsoft convention used by MS DOS. Why? Because
the Unix convention allows any program written in any language to access the kernel.
An assembly language program can do that as well. For example, we could open a file:
kernel:
int 80h ; Call kernel
ret
open:
push dword mode
push dword flags
push dword path
mov eax, 5
call kernel
add esp, byte 12
ret
This is a very clean and portable way of coding. If you need to port the code to a Unix system which uses a different
interrupt, or a different way of passing parameters, all you need to change is the kernel procedure.
218
Chapter 24 x86 Assembly Language Programming
But assembly language programmers like to shave off cycles. The above example requires a call/ret combination.
We can eliminate it by pushing an extra dword:
open:
push dword mode
push dword flags
push dword path
mov eax, 5
push eax ; Or any other dword
int 80h
add esp, byte 16
The 5 that we have placed in EAX identifies the kernel function, in this case open.
open:
mov eax, 5
mov ebx, path
mov ecx, flags
mov edx, mode
int 80h
This convention has a great disadvantage over the Unix way, at least as far as assembly language programming is
concerned: Every time you make a kernel call you must push the registers, then pop them later. This makes your
code bulkier and slower. Nevertheless, FreeBSD gives you a choice.
If you do choose the Linux convention, you must let the system know about it. After your program is assembled and
linked, you need to brand the executable:
219
Chapter 24 x86 Assembly Language Programming
Note: Not only do FreeBSD and Linux use different calling conventions, they sometimes use different numbers
for the same functions.
220
Chapter 24 x86 Assembly Language Programming
For example, to open a file, we need to push the mode first, then flags, then the address at which the path is
stored.
If successful, open() returns a non-negative integer, termed a file descriptor. It returns -1 on failure, and sets errno to
indicate the error.
The assembly language programmer new to Unix and FreeBSD will immediately ask the puzzling question: Where
is errno and how do I get to it?
Note: The information presented in the man pages applies to C programs. The assembly language programmer
needs additional information.
221
Chapter 24 x86 Assembly Language Programming
Note: I am aware of one system call that returns the value in EDX: SYS_fork. All others I have worked with use
EAX. But I have not worked with them all yet.
Tip: If you cannot find the answer here or anywhere else, study libc source code and see how it interfaces with
the kernel.
222
Chapter 24 x86 Assembly Language Programming
%ifdef LINUX
%define SYS_execve 11
%else
%define SYS_execve 59
%endif
%ifdef LINUX
%macro system 0
call kernel
%endmacro
align 4
kernel:
push ebx
push ecx
push edx
push esi
push edi
push ebp
pop ebp
pop edi
pop esi
pop edx
pop ecx
223
Chapter 24 x86 Assembly Language Programming
pop ebx
or eax, eax
js .errno
clc
ret
.errno:
neg eax
stc
ret
%else
%macro system 0
int 80h
%endmacro
%endif
sys.open:
sys.close:
[etc...]
224
Chapter 24 x86 Assembly Language Programming
int 80h
ret
Your Linux library will require more different functions. But even here you can group system calls using the same
number of parameters:
sys.exit:
sys.close:
[etc... one-parameter functions]
push ebx
mov ebx, [esp+12]
int 80h
pop ebx
jmp sys.return
...
sys.return:
or eax, eax
js sys.err
clc
ret
sys.err:
neg eax
stc
ret
The library approach may seem inconvenient at first because it requires you to produce a separate file your code
depends on. But it has many advantages: For one, you only need to write it once and can use it for all your programs.
You can even let other assembly language programmers use it, or perhaps use one written by someone else. But
perhaps the greatest advantage of the library is that your code can be ported to other systems, even by other
programmers, by simply writing a new library without any changes to your code.
If you do not like the idea of having a library, you can at least place all your system calls in a separate assembly
language file and link it with your main program. Here, again, all porters have to do is create a new object file to link
with your main program.
225
Chapter 24 x86 Assembly Language Programming
Porters of your software will simply write a new include file. No library or external object file is necessary, yet your
code is portable without any need to edit the code.
Note: This is the approach we will use throughout this chapter. We will name our include file system.inc, and
add to it whenever we deal with a new system call.
%define stdin 0
%define stdout 1
%define stderr 2
%define SYS_nosys 0
%define SYS_exit 1
%define SYS_fork 2
%define SYS_read 3
%define SYS_write 4
; [etc...]
We add a short, non-global procedure with a long name, so we do not accidentally reuse the name in our code:
section .text
align 4
access.the.bsd.kernel:
int 80h
ret
%macro system 1
mov eax, %1
call access.the.bsd.kernel
%endmacro
Finally, we create macros for each syscall. These macros take no arguments.
%macro sys.exit 0
system SYS_exit
%endmacro
%macro sys.fork 0
system SYS_fork
226
Chapter 24 x86 Assembly Language Programming
%endmacro
%macro sys.read 0
system SYS_read
%endmacro
%macro sys.write 0
system SYS_write
%endmacro
; [etc...]
Go ahead, enter it into your editor and save it as system.inc. We will add more to it as we discuss more syscalls.
1: %include ’system.inc’
2:
3: section .data
4: hello db ’Hello, World!’, 0Ah
5: hbytes equ $-hello
6:
7: section .text
8: global _start
9: _start:
10: push dword hbytes
11: push dword hello
12: push dword stdout
13: sys.write
14:
15: push dword 0
16: sys.exit
Here is what it does: Line 1 includes the defines, the macros, and the code from system.inc.
Lines 3-5 are the data: Line 3 starts the data section/segment. Line 4 contains the string "Hello, World!" followed by
a new line (0Ah). Line 5 creates a constant that contains the length of the string from line 4 in bytes.
Lines 7-16 contain the code. Note that FreeBSD uses the elf file format for its executables, which requires every
program to start at the point labeled _start (or, more precisely, the linker expects that). This label has to be global.
227
Chapter 24 x86 Assembly Language Programming
Lines 10-13 ask the system to write hbytes bytes of the hello string to stdout.
Lines 15-16 ask the system to end the program with the return value of 0. The SYS_exit syscall never returns, so
the code ends there.
Note: If you have come to Unix from MS DOS assembly language background, you may be used to writing
directly to the video hardware. You will never have to worry about this in FreeBSD, or any other flavor of Unix. As
far as you are concerned, you are writing to a file known as stdout. This can be the video screen, or a telnet
terminal, or an actual file, or even the input of another program. Which one it is, is for the system to figure out.
% su
Password:your root password
# cd /usr/ports/devel/nasm
# make install
# exit
%
You may type make install clean instead of just make install if you do not want to keep nasm source
code.
Either way, FreeBSD will automatically download nasm from the Internet, compile it, and install it on your system.
Note: If your system is not FreeBSD, you need to get nasm from its home page
(http://www.web-sites.co.uk/nasm/). You can still use it to assemble FreeBSD code.
228
Chapter 24 x86 Assembly Language Programming
%include ’system.inc’
section .data
hex db ’0123456789ABCDEF’
buffer db 0, 0, ’ ’
section .text
global _start
_start:
; read a byte from stdin
push dword 1
push dword buffer
push dword stdin
sys.read
add esp, byte 12
or eax, eax
je .done
; convert it to hex
movzx eax, byte [buffer]
mov edx, eax
shr dl, 4
mov dl, [hex+edx]
mov [buffer], dl
and al, 0Fh
mov al, [hex+eax]
mov [buffer+1], al
; print it
push dword 3
push dword buffer
229
Chapter 24 x86 Assembly Language Programming
.done:
push dword 0
sys.exit
In the data section we create an array called hex. It contains the 16 hexadecimal digits in ascending order. The array
is followed by a buffer which we will use for both input and output. The first two bytes of the buffer are initially set
to 0. This is where we will write the two hexadecimal digits (the first byte also is where we will read the input). The
third byte is a space.
The code section consists of four parts: Reading the byte, converting it to a hexadecimal number, writing the result,
and eventually exiting the program.
To read the byte, we ask the system to read one byte from stdin, and store it in the first byte of the buffer. The
system returns the number of bytes read in EAX. This will be 1 while data is coming, or 0, when no more input data is
available. Therefore, we check the value of EAX. If it is 0, we jump to .done, otherwise we continue.
Note: For simplicity sake, we are ignoring the possibility of an error condition at this time.
The hexadecimal conversion reads the byte from the buffer into EAX, or actually just AL, while clearing the
remaining bits of EAX to zeros. We also copy the byte to EDX because we need to convert the upper four bits (nibble)
separately from the lower four bits. We store the result in the first two bytes of the buffer.
Next, we ask the system to write the three bytes of the buffer, i.e., the two hexadecimal digits and the blank space, to
stdout. We then jump back to the beginning of the program and process the next byte.
Once there is no more input left, we ask the system to exit our program, returning a zero, which is the traditional
value meaning the program was successful.
Go ahead, and save the code in a file named hex.asm, then type the following (the ^D means press the control key
and type D while holding the control key down):
230
Chapter 24 x86 Assembly Language Programming
Note: If you are migrating to Unix from MS DOS, you may be wondering why each line ends with 0A instead of 0D
0A. This is because Unix does not use the cr/lf convention, but a "new line" convention, which is 0A in
hexadecimal.
Can we improve this? Well, for one, it is a bit confusing because once we have converted a line of text, our input no
longer starts at the begining of the line. We can modify it to print a new line instead of a space after each 0A:
%include ’system.inc’
section .data
hex db ’0123456789ABCDEF’
buffer db 0, 0, ’ ’
section .text
global _start
_start:
mov cl, ’ ’
.loop:
; read a byte from stdin
push dword 1
push dword buffer
push dword stdin
sys.read
add esp, byte 12
or eax, eax
je .done
; convert it to hex
movzx eax, byte [buffer]
mov [buffer+2], cl
cmp al, 0Ah
jne .hex
mov [buffer+2], al
.hex:
mov edx, eax
shr dl, 4
mov dl, [hex+edx]
mov [buffer], dl
and al, 0Fh
mov al, [hex+eax]
mov [buffer+1], al
231
Chapter 24 x86 Assembly Language Programming
; print it
push dword 3
push dword buffer
push dword stdout
sys.write
add esp, byte 12
jmp short .loop
.done:
push dword 0
sys.exit
We have stored the space in the CL register. We can do this safely because, unlike Microsoft Windows, Unix system
calls do not modify the value of any register they do not use to return a value in.
That means we only need to set CL once. We have, therefore, added a new label .loop and jump to it for the next
byte instead of jumping at _start. We have also added the .hex label so we can either have a blank space or a new
line as the third byte of the buffer.
Once you have changed hex.asm to reflect these changes, type:
That looks better. But this code is quite inefficient! We are making a system call for every single byte twice (once to
read it, another time to write the output).
232
Chapter 24 x86 Assembly Language Programming
The program ends when there is no more input. But we still need to ask the kernel to write the contents of our output
buffer to stdout one last time, otherwise some of our output would make it to the output buffer, but never be sent
out. Do not forget that, or you will be wondering why some of your output is missing.
%include ’system.inc’
section .data
hex db ’0123456789ABCDEF’
section .bss
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
section .text
global _start
_start:
sub eax, eax
sub ebx, ebx
sub ecx, ecx
mov edi, obuffer
.loop:
; read a byte from stdin
call getchar
; convert it to hex
mov dl, al
shr al, 4
mov al, [hex+eax]
call putchar
mov al, dl
and al, 0Fh
mov al, [hex+eax]
call putchar
mov al, ’ ’
cmp dl, 0Ah
jne .put
mov al, dl
.put:
call putchar
233
Chapter 24 x86 Assembly Language Programming
align 4
getchar:
or ebx, ebx
jne .fetch
call read
.fetch:
lodsb
dec ebx
ret
read:
push dword BUFSIZE
mov esi, ibuffer
push esi
push dword stdin
sys.read
add esp, byte 12
mov ebx, eax
or eax, eax
je .done
sub eax, eax
ret
align 4
.done:
call write ; flush output buffer
push dword 0
sys.exit
align 4
putchar:
stosb
inc ecx
cmp ecx, BUFSIZE
je write
ret
align 4
write:
sub edi, ecx ; start of buffer
push ecx
234
Chapter 24 x86 Assembly Language Programming
push edi
push dword stdout
sys.write
add esp, byte 12
sub eax, eax
sub ecx, ecx ; buffer is empty now
ret
We now have a third section in the source code, named .bss. This section is not included in our executable file, and,
therefore, cannot be initialized. We use resb instead of db. It simply reserves the requested size of uninitialized
memory for our use.
We take advantage of the fact that the system does not modify the registers: We use registers for what, otherwise,
would have to be global variables stored in the .data section. This is also why the Unix convention of passing
parameters to system calls on the stack is superior to the Microsoft convention of passing them in the registers: We
can keep the registers for our own use.
We use EDI and ESI as pointers to the next byte to be read from or written to. We use EBX and ECX to keep count of
the number of bytes in the two buffers, so we know when to dump the output to, or read more input from, the system.
Let us see how it works now:
Not what you expected? The program did not print the output until we pressed ^D. That is easy to fix by inserting
three lines of code to write the output every time we have converted a new line to 0A. I have marked the three lines
with > (do not copy the > in your hex.asm).
%include ’system.inc’
section .data
hex db ’0123456789ABCDEF’
section .bss
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
235
Chapter 24 x86 Assembly Language Programming
section .text
global _start
_start:
sub eax, eax
sub ebx, ebx
sub ecx, ecx
mov edi, obuffer
.loop:
; read a byte from stdin
call getchar
; convert it to hex
mov dl, al
shr al, 4
mov al, [hex+eax]
call putchar
mov al, dl
and al, 0Fh
mov al, [hex+eax]
call putchar
mov al, ’ ’
cmp dl, 0Ah
jne .put
mov al, dl
.put:
call putchar
> cmp al, 0Ah
> jne .loop
> call write
jmp short .loop
align 4
getchar:
or ebx, ebx
jne .fetch
call read
.fetch:
lodsb
dec ebx
236
Chapter 24 x86 Assembly Language Programming
ret
read:
push dword BUFSIZE
mov esi, ibuffer
push esi
push dword stdin
sys.read
add esp, byte 12
mov ebx, eax
or eax, eax
je .done
sub eax, eax
ret
align 4
.done:
call write ; flush output buffer
push dword 0
sys.exit
align 4
putchar:
stosb
inc ecx
cmp ecx, BUFSIZE
je write
ret
align 4
write:
sub edi, ecx ; start of buffer
push ecx
push edi
push dword stdout
sys.write
add esp, byte 12
sub eax, eax
sub ecx, ecx ; buffer is empty now
ret
237
Chapter 24 x86 Assembly Language Programming
% ./hex
Hello, World!
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A
Here I come!
48 65 72 65 20 49 20 63 6F 6D 65 21 0A
^D %
Note: This approach to buffered input/output still contains a hidden danger. I will discuss—and fix—it later, when
I talk about the dark side of buffering.
Warning: This may be a somewhat advanced topic, mostly of interest to programmers familiar with the theory of
compilers. If you wish, you may skip to the next section, and perhaps read this later.
While our sample program does not require it, more sophisticated filters often need to look ahead. In other words,
they may need to see what the next character is (or even several characters). If the next character is of a certain value,
it is part of the token currently being processed. Otherwise, it is not.
For example, you may be parsing the input stream for a textual string (e.g., when implementing a language
compiler): If a character is followed by another character, or perhaps a digit, it is part of the token you are
processing. If it is followed by white space, or some other value, then it is not part of the current token.
This presents an interesting problem: How to return the next character back to the input stream, so it can be read
again later?
One possible solution is to store it in a character variable, then set a flag. We can modify getchar to check the flag,
and if it is set, fetch the byte from that variable instead of the input buffer, and reset the flag. But, of course, that
slows us down.
The C language has an ungetc() function, just for that purpose. Is there a quick way to implement it in our code? I
would like you to scroll back up and take a look at the getchar procedure and see if you can find a nice and fast
solution before reading the next paragraph. Then come back here and see my own solution.
The key to returning a character back to the stream is in how we are getting the characters to start with:
First we check if the buffer is empty by testing the value of EBX. If it is zero, we call the read procedure.
If we do have a character available, we use lodsb, then decrease the value of EBX. The lodsb instruction is
effectively identical to:
238
Chapter 24 x86 Assembly Language Programming
The byte we have fetched remains in the buffer until the next time read is called. We do not know when that
happens, but we do know it will not happen until the next call to getchar. Hence, to "return" the last-read byte back
to the stream, all we have to do is decrease the value of ESI and increase the value of EBX:
ungetc:
dec esi
inc ebx
ret
But, be careful! We are perfectly safe doing this if our look-ahead is at most one character at a time. If we are
examining more than one upcoming character and call ungetc several times in a row, it will work most of the time,
but not all the time (and will be tough to debug). Why?
Because as long as getchar does not have to call read, all of the pre-read bytes are still in the buffer, and our
ungetc works without a glitch. But the moment getchar calls read, the contents of the buffer change.
We can always rely on ungetc working properly on the last character we have read with getchar, but not on
anything we have read before that.
If your program reads more than one byte ahead, you have at least two choices:
If possible, modify the program so it only reads one byte ahead. This is the simplest solution.
If that option is not available, first of all determine the maximum number of characters your program needs to return
to the input stream at one time. Increase that number slightly, just to be sure, preferably to a multiple of 16—so it
aligns nicely. Then modify the .bss section of your code, and create a small "spare" buffer right before your input
buffer, something like this:
section .bss
resb 16 ; or whatever the value you came up with
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
You also need to modify your ungetc to pass the value of the byte to unget in AL:
ungetc:
dec esi
inc ebx
mov [esi], al
ret
With this modification, you can call ungetc up to 17 times in a row safely (the first call will still be within the
buffer, the remaining 16 may be either within the buffer or within the "spare").
239
Chapter 24 x86 Assembly Language Programming
The value at the top of the stack contains the number of command line arguments. It is traditionally called argc, for
"argument count."
Command line arguments follow next, all argc of them. These are typically referred to as argv, for "argument
value(s)." That is, we get argv[0], argv[1], ..., argv[argc-1]. These are not the actual arguments, but
pointers to arguments, i.e., memory addresses of the actual arguments. The arguments themselves are
NUL-terminated character strings.
The argv list is followed by a NULL pointer, which is simply a 0. There is more, but this is enough for our purposes
right now.
Note: If you have come from the MS DOS programming environment, the main difference is that each argument
is in a separate string. The second difference is that there is no practical limit on how many arguments there can
be.
Armed with this knowledge, we are almost ready for the next version of hex.asm. First, however, we need to add a
few lines to system.inc:
First, we need to add two new entries to our list of system call numbers:
%define SYS_open 5
%define SYS_close 6
%macro sys.open 0
system SYS_open
%endmacro
%macro sys.close 0
system SYS_close
%endmacro
%include ’system.inc’
240
Chapter 24 x86 Assembly Language Programming
section .data
fd.in dd stdin
fd.out dd stdout
hex db ’0123456789ABCDEF’
section .bss
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
section .text
align 4
err:
push dword 1 ; return failure
sys.exit
align 4
global _start
_start:
add esp, byte 8 ; discard argc and argv[0]
pop ecx
jecxz .init ; no more arguments
pop ecx
jecxz .init ; no more arguments
241
Chapter 24 x86 Assembly Language Programming
.init:
sub eax, eax
sub ebx, ebx
sub ecx, ecx
mov edi, obuffer
.loop:
; read a byte from input file or stdin
call getchar
; convert it to hex
mov dl, al
shr al, 4
mov al, [hex+eax]
call putchar
mov al, dl
and al, 0Fh
mov al, [hex+eax]
call putchar
mov al, ’ ’
cmp dl, 0Ah
jne .put
mov al, dl
.put:
call putchar
cmp al, dl
jne .loop
call write
jmp short .loop
align 4
getchar:
or ebx, ebx
jne .fetch
call read
.fetch:
242
Chapter 24 x86 Assembly Language Programming
lodsb
dec ebx
ret
read:
push dword BUFSIZE
mov esi, ibuffer
push esi
push dword [fd.in]
sys.read
add esp, byte 12
mov ebx, eax
or eax, eax
je .done
sub eax, eax
ret
align 4
.done:
call write ; flush output buffer
; close files
push dword [fd.in]
sys.close
; return success
push dword 0
sys.exit
align 4
putchar:
stosb
inc ecx
cmp ecx, BUFSIZE
je write
ret
align 4
write:
sub edi, ecx ; start of buffer
push ecx
push edi
243
Chapter 24 x86 Assembly Language Programming
In our .data section we now have two new variables, fd.in and fd.out. We store the input and output file
descriptors here.
In the .text section we have replaced the references to stdin and stdout with [fd.in] and [fd.out].
The .text section now starts with a simple error handler, which does nothing but exit the program with a return
value of 1. The error handler is before _start so we are within a short distance from where the errors occur.
Naturally, the program execution still begins at _start. First, we remove argc and argv[0] from the stack: They
are of no interest to us (in this program, that is).
We pop argv[1] to ECX. This register is particularly suited for pointers, as we can handle NULL pointers with
jecxz. If argv[1] is not NULL, we try to open the file named in the first argument. Otherwise, we continue the
program as before: Reading from stdin, writing to stdout. If we fail to open the input file (e.g., it does not exist),
we jump to the error handler and quit.
If all went well, we now check for the second argument. If it is there, we open the output file. Otherwise, we send the
output to stdout. If we fail to open the output file (e.g., it exists and we do not have the write permission), we,
again, jump to the error handler.
The rest of the code is the same as before, except we close the input and output files before exiting, and, as
mentioned, we use [fd.in] and [fd.out].
Our executable is now a whopping 768 bytes long.
Can we still improve it? Of course! Every program can be improved. Here are a few ideas of what we could do:
244
Chapter 24 x86 Assembly Language Programming
24.10.2 webvars
I could just show you some code that prints the environment the same way the Unix env command does. But I
thought it would be more interesting to write a simple assembly language CGI utility.
• The web server communicates with the CGI program by setting environment variables.
• The CGI program sends its output to stdout. The web server reads it from there.
• It must start with an HTTP header followed by two blank lines.
• It then prints the HTML code, or whatever other type of data it is producing.
Note: While certain environment variables use standard names, others vary, depending on the web server. That
makes webvars quite a useful diagnostic tool.
245
Chapter 24 x86 Assembly Language Programming
section .data
http db ’Content-type: text/html’, 0Ah, 0Ah
<
db ’ ?xml version="1.0" encoding="UTF-8"? ’, 0Ah >
<
db ’ !DOCTYPE html PUBLIC "-//W3C/DTD XHTML Strict//EN" ’
246
Chapter 24 x86 Assembly Language Programming
>
db ’"DTD/xhtml1-strict.dtd" ’, 0Ah
<
db ’ html xmlns="http://www.w3.org/1999/xhtml" ’
>
db ’xml.lang="en" lang="en" ’, 0Ah
< >
db ’ head ’, 0Ah
< > < >
db ’ title Web Environment /title ’, 0Ah
< >
db ’ meta name="author" content="G. Adam Stanislav" / ’, 0Ah
< >
db ’ /head ’, 0Ah, 0Ah
<
db ’ body bgcolor="#ffffff" text="#000000" link="#0000ff" ’
>
db ’vlink="#840084" alink="#0000ff" ’, 0Ah
< >
db ’ div class="webvars" ’, 0Ah
< > < >
db ’ h1 Web Environment /h1 ’, 0Ah
<> <> < >
db ’ p The following b environment variables /b are defined ’
< >
db ’on this web server: /p ’, 0Ah, 0Ah
<
db ’ table align="center" width="80" border="0" cellpadding="10" ’
>
db ’cellspacing="0" class="webvars" ’, 0Ah
httplen equ $-http
< >
left db ’ tr ’, 0Ah
<
db ’ td class="name" >< >
tt ’
leftlen equ $-left
<
middle db ’ /tt>< >
/td ’, 0Ah
<
db ’ td class="value" >< >< >
tt b ’
midlen equ $-middle
<> < >
undef db ’ i (undefined) /i ’
undeflen equ $-undef
< ><
right db ’ /b /tt >< >
/td ’, 0Ah
< >
db ’ /tr ’, 0Ah
rightlen equ $-right
< >
wrap db ’ /table ’, 0Ah
< >
db ’ /div ’, 0Ah
< >
db ’ /body ’, 0Ah
< >
db ’ /html ’, 0Ah, 0Ah
wraplen equ $-wrap
section .text
global _start
_start:
; First, send out all the http and xhtml stuff that is
; needed before we start showing the environment
push dword httplen
push dword http
push dword stdout
sys.write
247
Chapter 24 x86 Assembly Language Programming
; It may be tempting to search for the ’=’ in the env string next.
; But it is possible there is no ’=’, so we search for the
; terminating NUL first.
mov esi, edi ; Save start of string
sub ecx, ecx
not ecx ; ECX = FFFFFFFF
sub eax, eax
repne scasb
not ecx ; ECX = string length + 1
mov ebx, ecx ; Save it in EBX
248
Chapter 24 x86 Assembly Language Programming
push ecx
push esi
push dword stdout
sys.write
; Print "undefined" if 0
or ebx, ebx
jne .value
.value:
push ebx
push edi
push dword stdout
sys.write
.wrap:
; Print the rest of HTML
push dword wraplen
249
Chapter 24 x86 Assembly Language Programming
; Return success
push dword 0
sys.exit
This code produces a 1,396-byte executable. Most of it is data, i.e., the HTML mark-up we need to send out.
Assemble and link it as usual:
To use it, you need to upload webvars to your web server. Depending on how your web server is set up, you may
have to store it in a special cgi-bin directory, or perhaps rename it with a .cgi extension.
Then you need to use your browser to view its output. To see its output on my web server, please go to
http://www.int80h.org/webvars/. If curious about the additional environment variables present in a password
protected web directory, go to http://www.int80h.org/private/, using the name asm and password
programmer.
250
Chapter 24 x86 Assembly Language Programming
% mv tempfile myfile
It would be nice to have a ftuc, i.e., fast tuc, and use it like this:
% ftuc myfile
In this chapter, then, we will write ftuc in assembly language (the original tuc is in C), and study various
file-oriented kernel services in the process.
At first sight, such a file conversion is very simple: All you have to do is strip the carriage returns, right?
If you answered yes, think again: That approach will work most of the time (at least with MS DOS text files), but
will fail occasionally.
The problem is that not all non-Unix text files end their line with the carriage return / line feed sequence. Some use
carriage returns without line feeds. Others combine several blank lines into a single carriage return followed by
several line feeds. And so on.
A text file converter, then, must be able to handle any possible line endings:
251
Chapter 24 x86 Assembly Language Programming
• ordinary
• cr
• lf
Our program will start in the ordinary state. During this state, the program action depends on its input as follows:
• If the input is anything other than a carriage return or line feed, the input is simply passed on to the output. The
state remains unchanged.
• If the input is a carriage return, the state is changed to cr. The input is then discarded, i.e., no output is made.
• If the input is a line feed, the state is changed to lf. The input is then discarded.
Whenever we are in the cr state, it is because the last input was a carriage return, which was unprocessed. What our
software does in this state again depends on the current input:
• If the input is anything other than a carriage return or line feed, output a line feed, then output the input, then
change the state to ordinary.
• If the input is a carriage return, we have received two (or more) carriage returns in a row. We discard the input, we
output a line feed, and leave the state unchanged.
• If the input is a line feed, we output the line feed and change the state to ordinary. Note that this is not the same as
the first case above – if we tried to combine them, we would be outputting two line feeds instead of one.
Finally, we are in the lf state after we have received a line feed that was not preceded by a carriage return. This will
happen when our file already is in Unix format, or whenever several lines in a row are expressed by a single carriage
return followed by several line feeds, or when line ends with a line feed / carriage return sequence. Here is how we
need to handle our input in this state:
• If the input is anything other than a carriage return or line feed, we output a line feed, then output the input, then
change the state to ordinary. This is exactly the same action as in the cr state upon receiving the same kind of input.
• If the input is a carriage return, we discard the input, we output a line feed, then change the state to ordinary.
• If the input is a line feed, we output the line feed, and leave the state unchanged.
252
Chapter 24 x86 Assembly Language Programming
Note: Now that we have expressed our algorithm as a finite state machine, we could easily design a dedicated
digital electronic circuit (a "chip") to do the conversion for us. Of course, doing so would be considerably more
expensive than writing an assembly language program.
switch (state) {
default:
case REGULAR:
regular(inputchar);
break;
case CR:
cr(inputchar);
break;
case LF:
lf(inputchar);
break;
}
(output[state])(inputchar);
Yet another is to have state be a function pointer, set to point at the appropriate function:
(*state)(inputchar);
253
Chapter 24 x86 Assembly Language Programming
This is the approach we will use in our program because it is very easy to do in assembly language, and very fast,
too. We will simply keep the address of the right procedure in EBX, and then just issue:
call ebx
This is possibly faster than hardcoding the address in the code because the microprocessor does not have to fetch the
address from the memory—it is already stored in one of its registers. I said possibly because with the caching
modern microprocessors do, either way may be equally fast.
197 STD BSD { caddr_t mmap(caddr_t addr, size_t len, int prot, \
int flags, int fd, long pad, off_t pos); }
This differs slightly from what mmap(2) says. That is because mmap(2) describes the C version.
The difference is in the long pad argument, which is not present in the C version. However, the FreeBSD syscalls
add a 32-bit pad after pushing a 64-bit argument. In this case, off_t is a 64-bit value.
When we are finished working with a memory-mapped file, we unmap it with the munmap syscall:
254
Chapter 24 x86 Assembly Language Programming
Tip: For an in-depth treatment of mmap, see W. Richard Stevens’ Unix Network Programming, Volume 2, Chapter
12 (http://www.int80h.org/cgi-bin/isbn?isbn=0130810819).
This is a very straightforward call: We pass to it the address of a stat structure and the descriptor of an open file. It
will fill out the contents of the stat structure.
I do, however, have to say that I tried to declare the stat structure in the .bss section, and fstat did not like it: It set
the carry flag indicating an error. After I changed the code to allocate the structure on the stack, everything was
working fine.
201 STD BSD { int ftruncate(int fd, int pad, off_t length); }
255
Chapter 24 x86 Assembly Language Programming
24.11.6 ftuc
We now know everything we need to write ftuc. We start by adding some new lines in system.inc. First, we define
some constants and structures, somewhere at or near the beginning of the file:
256
Chapter 24 x86 Assembly Language Programming
%macro sys.mmap 0
system SYS_mmap
%endmacro
%macro sys.munmap 0
system SYS_munmap
%endmacro
%macro sys.ftruncate 0
system SYS_ftruncate
%endmacro
%macro sys.fstat 0
system SYS_fstat
%endmacro
section .data
db ’Copyright 2000 G. Adam Stanislav.’, 0Ah
db ’All rights reserved.’, 0Ah
usg db ’Usage: ftuc filename’, 0Ah
usglen equ $-usg
co db "ftuc: Can’t open file.", 0Ah
colen equ $-co
fae db ’ftuc: File access error.’, 0Ah
faelen equ $-fae
257
Chapter 24 x86 Assembly Language Programming
ftl db ’ftuc: File too long, use regular tuc instead.’, 0Ah
ftllen equ $-ftl
mae db ’ftuc: Memory allocation error.’, 0Ah
maelen equ $-mae
section .text
align 4
memerr:
push dword maelen
push dword mae
jmp short error
align 4
toolong:
push dword ftllen
push dword ftl
jmp short error
align 4
facerr:
push dword faelen
push dword fae
jmp short error
align 4
cantopen:
push dword colen
push dword co
jmp short error
align 4
usage:
push dword usglen
push dword usg
error:
push dword stderr
sys.write
push dword 1
sys.exit
align 4
global _start
258
Chapter 24 x86 Assembly Language Programming
_start:
pop eax ; argc
pop eax ; program name
pop ecx ; file to convert
jecxz usage
pop eax
or eax, eax ; Too many arguments?
jne usage
259
Chapter 24 x86 Assembly Language Programming
.loop:
lodsb
call ebx
loop .loop
; Output final lf
mov al, ah
stosb
inc edx
.filesize:
; truncate file to new size
push dword 0 ; high dword
push edx ; low dword
push eax ; pad
push ebp
sys.ftruncate
.quit:
260
Chapter 24 x86 Assembly Language Programming
push dword 0
sys.exit
align 4
ordinary:
cmp al, 0Dh
je .cr
cmp al, ah
je .lf
stosb
inc edx
ret
align 4
.cr:
mov ebx, cr
ret
align 4
.lf:
mov ebx, lf
ret
align 4
cr:
cmp al, 0Dh
je .cr
cmp al, ah
je .lf
xchg al, ah
stosb
inc edx
xchg al, ah
; fall through
.lf:
stosb
inc edx
mov ebx, ordinary
ret
261
Chapter 24 x86 Assembly Language Programming
align 4
.cr:
mov al, ah
stosb
inc edx
ret
align 4
lf:
cmp al, ah
je .lf
xchg al, ah
stosb
inc edx
xchg al, ah
stosb
inc edx
mov ebx, ordinary
ret
align 4
.cr:
mov ebx, ordinary
mov al, ah
; fall through
.lf:
stosb
inc edx
ret
Warning: Do not use this program on files stored on a disk formated by MS DOS or Windows. There seems to
be a subtle bug in the FreeBSD code when using mmap on these drives mounted under FreeBSD: If the file is over
a certain size, mmap will just fill the memory with zeros, and then copy them to the file overwriting its contents.
262
Chapter 24 x86 Assembly Language Programming
24.12.1 CSV
I will illustrate this principle with a specific real-life example I was faced with recently:
I needed to extract the 11th field of each record from a database I downloaded from a web site. The database was a
CSV file, i.e., a list of comma-separated values. That is quite a standard format for sharing data among people who
may be using different database software.
The first line of the file contains the list of various fields separated by commas. The rest of the file contains the data
listed line by line, with values separated by commas.
I tried awk, using the comma as a separator. But because several lines contained a quoted comma, awk was
extracting the wrong field from those lines.
Therefore, I needed to write my own software to extract the 11th field from the CSV file. However, going with the
Unix spirit, I only needed to write a simple filter that would do the following:
263
Chapter 24 x86 Assembly Language Programming
The code stores the options (except for the file descriptors) in EDX: The comma in DH, the new separator in DL, and
the flag for the -p option in the highest bit of EDX, so a check for its sign will give us a quick decision what to do.
Here is the code:
%include ’system.inc’
264
Chapter 24 x86 Assembly Language Programming
section .data
fd.in dd stdin
fd.out dd stdout
< > < >
usg db ’Usage: csv [-t delim ] [-c comma ] [-p] [-o <outfile>] [-i <infile>]’, 0Ah
usglen equ $-usg
iemsg db "csv: Can’t open input file", 0Ah
iemlen equ $-iemsg
oemsg db "csv: Can’t create output file", 0Ah
oemlen equ $-oemsg
section .bss
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
section .text
align 4
ierr:
push dword iemlen
push dword iemsg
push dword stderr
sys.write
push dword 1 ; return failure
sys.exit
align 4
oerr:
push dword oemlen
push dword oemsg
push dword stderr
sys.write
push dword 2
sys.exit
align 4
usage:
push dword usglen
push dword usg
push dword stderr
sys.write
push dword 3
sys.exit
align 4
265
Chapter 24 x86 Assembly Language Programming
global _start
_start:
add esp, byte 8 ; discard argc and argv[0]
mov edx, (’,’ <<8) | 9
.arg:
pop ecx
or ecx, ecx
je near .init ; no more arguments
inc ecx
mov ax, [ecx]
.o:
cmp al, ’o’
jne .i
; Make sure we are not asked for the output file twice
cmp dword [fd.out], stdout
jne usage
inc ecx
or ah, ah
jne .openoutput
pop ecx
jecxz usage
.openoutput:
push dword 420 ; file mode (644 octal)
push dword 0200h | 0400h | 01h
; O_CREAT | O_TRUNC | O_WRONLY
push ecx
sys.open
jc near oerr
266
Chapter 24 x86 Assembly Language Programming
.i:
cmp al, ’i’
jne .p
.openinput:
push dword 0 ; O_RDONLY
push ecx
sys.open
jc near ierr ; open failed
.p:
cmp al, ’p’
jne .t
or ah, ah
jne near usage
or edx, 1 << 31
jmp .arg
.t:
cmp al, ’t’ ; redefine output delimiter
jne .c
or ah, ah
je near usage
mov dl, ah
jmp .arg
267
Chapter 24 x86 Assembly Language Programming
.c:
cmp al, ’c’
jne near usage
or ah, ah
je near usage
mov dh, ah
jmp .arg
align 4
.init:
sub eax, eax
sub ebx, ebx
sub ecx, ecx
mov edi, obuffer
.firstline:
; get rid of the first line
call getchar
cmp al, 0Ah
jne .firstline
.loop:
; read a byte from stdin
call getchar
; Replace the comma with a tab (or whatever the user wants)
mov al, dl
.put:
call putchar
jmp short .loop
.quote:
cmp al, ’"’
jne .put
268
Chapter 24 x86 Assembly Language Programming
call putchar
jmp short .qloop
align 4
getchar:
or ebx, ebx
jne .fetch
call read
.fetch:
lodsb
dec ebx
ret
read:
jecxz .read
call write
.read:
push dword BUFSIZE
mov esi, ibuffer
push esi
push dword [fd.in]
sys.read
add esp, byte 12
mov ebx, eax
or eax, eax
je .done
sub eax, eax
ret
align 4
.done:
call write ; flush output buffer
269
Chapter 24 x86 Assembly Language Programming
; close files
push dword [fd.in]
sys.close
; return success
push dword 0
sys.exit
align 4
putchar:
stosb
inc ecx
cmp ecx, BUFSIZE
je write
ret
align 4
write:
jecxz .ret ; nothing to write
sub edi, ecx ; start of buffer
push ecx
push edi
push dword [fd.out]
sys.write
add esp, byte 12
sub eax, eax
sub ecx, ecx ; buffer is empty now
.ret:
ret
Much of it is taken from hex.asm above. But there is one important difference: I no longer call write whenever I
am outputing a line feed. Yet, the code can be used interactively.
I have found a better solution for the interactive problem since I first started writing this chapter. I wanted to make
sure each line is printed out separately only when needed. After all, there is no need to flush out every line when used
non-interactively.
The new solution I use now is to call write every time I find the input buffer empty. That way, when running in the
interactive mode, the program reads one line from the user’s keyboard, processes it, and sees its input buffer is
empty. It flushes its output and reads the next line.
270
Chapter 24 x86 Assembly Language Programming
.loop:
call getchar
not al ; Create a negative
call putchar
jmp short .loop
Because this filter works with raw data, it is unlikely to be used interactively.
But it could be called by image manipulation software. And, unless it calls write before each call to read, chances
are it will lock up.
Here is what might happen:
1. The image editor will load our filter using the C function popen().
2. It will read the first row of pixels from a bitmap or pixmap.
3. It will write the first row of pixels to the pipe leading to the fd.in of our filter.
4. Our filter will read each pixel from its input, turn it to a negative, and write it to its output buffer.
5. Our filter will call getchar to fetch the next pixel.
6. getchar will find an empty input buffer, so it will call read.
At this point our filter waits for the image editor to send it more data to process, while the image editor is waiting for
our filter to send it the result of the processing of the first row. But the result sits in our output buffer.
271
Chapter 24 x86 Assembly Language Programming
The filter and the image editor will continue waiting for each other forever (or, at least, until they are killed). Our
software has just entered a race condition.
This problem does not exist if our filter flushes its output buffer before asking the kernel for more input data.
272
Chapter 24 x86 Assembly Language Programming
For whatever reasons, the original author of nasm has decided to use different op codes, namely st0–st7. In other
words, there are no parentheses, and the TOS is always st0, never just st.
Tip: You can use it to get decimal places by multiplying the TOS by a power of 10 first.
The highest bit of the highest byte (byte 9) is the sign bit: If it is set, the number is negative, otherwise, it is positive.
The rest of the bits of this byte are unused/ignored.
The remaining 9 bytes store the 18 digits of the number: 2 digits per byte.
The more significant digit is stored in the high nibble (4 bits), the less significant digit in the low nibble.
That said, you might think that -1234567 would be stored in the memory like this (using hexadecimal notation):
80 00 00 00 00 00 01 23 45 67
Alas it is not! As with everything else of Intel make, even the packed decimal is little–endian.
That means our -1234567 is stored like this:
67 45 23 01 00 00 00 00 00 80
Note: The book to read—if you can find it—is Richard Startz’ 8087/80287/80387 for the IBM PC & Compatibles
(http://www.int80h.org/cgi-bin/isbn?isbn=013246604X). Though it does seem to take the fact about the
little–endian storage of the packed decimal for granted. I kid you not about the desperation of trying to figure out
what was wrong with the filter I show below before it occurred to me I should try the little–endian order even for
this type of data.
273
Chapter 24 x86 Assembly Language Programming
Our next filter will help us whenever we want to build a pinhole camera, so, we need some background in pinhole
photography before we can continue.
D = PC * sqrt(FL)
In here, D is the ideal diameter of the pinhole, FL is the focal length, and PC is a pinhole constant. According to Jay
Bender, its value is 0.04, while Kenneth Connors has determined it to be 0.037. Others have proposed other values.
Plus, this value is for the daylight only: Other types of light will require a different constant, whose value can only be
determined by experimentation.
274
Chapter 24 x86 Assembly Language Programming
It does not matter whether it is a 35–mm camera, or a 6x9cm camera, etc. As long as we know the f–number, we can
determine the proper exposure.
The f–number is easy to calculate:
F = FL / D
In other words, the f–number equals the focal length divided by the diameter of the pinhole. It also means a higher
f–number either implies a smaller pinhole or a larger focal distance, or both. That, in turn, implies, the higher the
f–number, the longer the exposure has to be.
Furthermore, while pinhole diameter and focal distance are one–dimensional measurements, both, the film and the
pinhole, are two–dimensional. That means that if you have measured the exposure at f–number A as t, then the
exposure at f–number B is:
t * (B / A)2
275
Chapter 24 x86 Assembly Language Programming
Our program needs to consider more than a single byte of input at a time. When it sees the first 1, it must understand
it is seeing the first digit of a decimal number. When it sees the 0 and the other 0, it must know it is seeing more
digits of the same number.
When it encounters the first comma, it must know it is no longer receiving the digits of the first number. It must be
able to convert the digits of the first number into the value of 100. And the digits of the second number into the value
of 150. And, of course, the digits of the third number into the numeric value of 210.
We need to decide what delimiters to accept: Do the input numbers have to be separated by a comma? If so, how do
we treat two numbers separated by something else?
Personally, I like to keep it simple. Something either is a number, so I process it. Or it is not a number, so I discard it.
I don’t like the computer complaining about me typing in an extra character when it is obvious that it is an extra
character. Duh!
Plus, it allows me to break up the monotony of computing and type in a query instead of just a number:
What is the best pinhole diameter for the focal length of 150?
276
Chapter 24 x86 Assembly Language Programming
277
Chapter 24 x86 Assembly Language Programming
The other way allows us to make ad hoc decisions: "Though I usually want you to use 0.039, this time I want
0.03872." In other words, it allows us to override the permanent choice.
This type of choice is usually done with command line parameters.
Finally, a program always needs a default. The user may not make any choices. Perhaps he does not know what to
choose. Perhaps he is "just browsing." Preferably, the default will be the value most users would choose anyway.
That way they do not need to choose. Or, rather, they can choose the default without an additional effort.
Given this system, the program may find conflicting options, and handle them this way:
1. If it finds an ad hoc choice (e.g., command line parameter), it should accept that choice. It must ignore any
permanent choice and any default.
2. Otherwise, if it finds a permanent option (e.g., an environment variable), it should accept it, and ignore the
default.
3. Otherwise, it should use the default.
278
Chapter 24 x86 Assembly Language Programming
Since our input allows for an unspecified number of focal length entries, it makes sense to use a traditional
database–style output of showing the result of the calculation for each focal length on a separate line, while
separating all values on one line by a tab character.
Optionally, we should also allow the user to specify the use of the CSV format we have studied earlier. In this case,
we will print out a line of comma–separated names describing each field of every line, then show our results as
before, but substituting a comma for the tab.
We need a command line option for the CSV format. We cannot use -c because that already means use Connors’
constant. For some strange reason, many web sites refer to CSV files as "Excel spreadsheet" (though the CSV format
predates Excel). We will, therefore, use the -e switch to inform our software we want the output in the CSV format.
We will start each line of the output with the focal length. This may sound repetitious at first, especially in the
interactive mode: The user types in the focal length, and we are repeating it.
But the user can type several focal lengths on one line. The input can also come in from a file or from the output of
another program. In that case the user does not see the input at all.
By the same token, the output can go to a file which we will want to examine later, or it could go to the printer, or
become the input of another program.
So, it makes perfect sense to start each line with the focal length as entered by the user.
No, wait! Not as entered by the user. What if the user types in something like this:
00000000150
17459765723452353453534535353530530534563507309676764423
Ha! The packed decimal FPU format lets us input 18–digit numbers. But the user has entered more than 18 digits.
How do we handle that?
Well, we could modify our code to read the first 18 digits, enter it to the FPU, then read more, multiply what we
already have on the TOS by 10 raised to the number of additional digits, then add to it.
Yes, we could do that. But in this program it would be ridiculous (in a different one it may be just the thing to do):
Even the circumference of the Earth expressed in millimeters only takes 11 digits. Clearly, we cannot build a camera
that large (not yet, anyway).
279
Chapter 24 x86 Assembly Language Programming
So, if the user enters such a huge number, he is either bored, or testing us, or trying to break into the system, or
playing games—doing anything but designing a pinhole camera.
What will we do?
We will slap him in the face, in a manner of speaking:
To achieve that, we will simply ignore any leading zeros. Once we find a non–zero digit, we will initialize a counter
to 0 and start taking three steps:
Now, while we are taking these three steps, we also need to watch out for one of two conditions:
• If the counter grows above 18, we stop appending to the buffer. We continue reading the digits and sending them
to the output.
• If, or rather when, the next input character is not a digit, we are done inputting for now.
Incidentally, we can simply discard the non–digit, unless it is a #, which we must return to the input stream. It
starts a comment, so we must see it after we are done producing output and start looking for more input.
That still leaves one possibility uncovered: If all the user enters is a zero (or several zeros), we will never find a
non–zero to display.
We can determine this has happened whenever our counter stays at 0. In that case we need to send 0 to the output,
and perform another "slap in the face":
Once we have displayed the focal length and determined it is valid (greater than 0 but not exceeding 18 digits), we
can calculate the pinhole diameter.
It is not by coincidence that pinhole contains the word pin. Indeed, many a pinhole literally is a pin hole, a hole
carefully punched with the tip of a pin.
That is because a typical pinhole is very small. Our formula gets the result in millimeters. We will multiply it by
1000, so we can output the result in microns.
At this point we have yet another trap to face: Too much precision.
280
Chapter 24 x86 Assembly Language Programming
Yes, the FPU was designed for high precision mathematics. But we are not dealing with high precision mathematics.
We are dealing with physics (optics, specifically).
Suppose we want to convert a truck into a pinhole camera (we would not be the first ones to do that!). Suppose its
box is 12 meters long, so we have the focal length of 12000. Well, using Bender’s constant, it gives us square root of
12000 multiplied by 0.04, which is 4.381780460 millimeters, or 4381.780460 microns.
Put either way, the result is absurdly precise. Our truck is not exactly 12000 millimeters long. We did not measure its
length with such a precision, so stating we need a pinhole with the diameter of 4.381780460 millimeters is, well,
deceiving. 4.4 millimeters would do just fine.
Note: I "only" used ten digits in the above example. Imagine the absurdity of going for all 18!
We need to limit the number of significant digits of our result. One way of doing it is by using an integer representing
microns. So, our truck would need a pinhole with the diameter of 4382 microns. Looking at that number, we still
decide that 4400 microns, or 4.4 millimeters is close enough.
Additionally, we can decide that no matter how big a result we get, we only want to display four siginificant digits
(or any other number of them, of course). Alas, the FPU does not offer rounding to a specific number of digits (after
all, it does not view the numbers as decimal but as binary).
We, therefore, must devise an algorithm to reduce the number of significant digits.
Here is mine (I think it is awkward—if you know a better one, please, let me know):
1. Initialize a counter to 0.
2. While the number is greater than or equal to 10000, divide it by 10 and increase the counter.
3. Output the result.
4. While the counter is greater than 0, output 0 and decrease the counter.
Note: The 10000 is only good if you want four significant digits. For any other number of significant digits, replace
10000 with 10 raised to the number of significant digits.
We will, then, output the pinhole diameter in microns, rounded off to four significant digits.
At this point, we know the focal length and the pinhole diameter. That means we have enough information to also
calculate the f–number.
We will display the f–number, rounded to four significant digits. Chances are the f–number will tell us very little. To
make it more meaningful, we can find the nearest normalized f–number, i.e., the nearest power of the square root of 2.
281
Chapter 24 x86 Assembly Language Programming
We do that by multiplying the actual f–number by itself, which, of course, will give us its square. We will then
calculate its base–2 logarithm, which is much easier to do than calculating the base–square–root–of–2 logarithm! We
will round the result to the nearest integer. Next, we will raise 2 to the result. Actually, the FPU gives us a good
shortcut to do that: We can use the fscale op code to "scale" 1, which is analogous to shifting an integer left.
Finally, we calculate the square root of it all, and we have the nearest normalized f–number.
If all that sounds overwhelming—or too much work, perhaps—it may become much clearer if you see the code. It
takes 9 op codes altogether:
The first line, fmul st0, st0, squares the contents of the TOS (top of the stack, same as st, called st0 by nasm).
The fld1 pushes 1 on the TOS.
The next line, fld st1, pushes the square back to the TOS. At this point the square is both in st and st(2) (it will
become clear why we leave a second copy on the stack in a moment). st(1) contains 1.
Next, fyl2x calculates base–2 logarithm of st multiplied by st(1). That is why we placed 1 on st(1) before.
At this point, st contains the logarithm we have just calculated, st(1) contains the square of the actual f–number
we saved for later.
frndint rounds the TOS to the nearest integer. fld1 pushes a 1. fscale shifts the 1 we have on the TOS by the
value in st(1), effectively raising 2 to st(1).
Finally, fsqrt calculates the square root of the result, i.e., the nearest normalized f–number.
We now have the nearest normalized f–number on the TOS, the base–2 logarithm rounded to the nearest integer in
st(1), and the square of the actual f–number in st(2). We are saving the value in st(2) for later.
But we do not need the contents of st(1) anymore. The last line, fstp st1, places the contents of st to st(1),
and pops. As a result, what was st(1) is now st, what was st(2) is now st(1), etc. The new st contains the
normalized f–number. The new st(1) contains the square of the actual f–number we have stored there for posterity.
At this point, we are ready to output the normalized f–number. Because it is normalized, we will not round it off to
four significant digits, but will send it out in its full precision.
The normalized f-number is useful as long as it is reasonably small and can be found on our light meter. Otherwise
we need a different method of determining proper exposure.
282
Chapter 24 x86 Assembly Language Programming
Earlier we have figured out the formula of calculating proper exposure at an arbitrary f–number from that measured
at a different f–number.
Every light meter I have ever seen can determine proper exposure at f5.6. We will, therefore, calculate an "f5.6
multiplier," i.e., by how much we need to multiply the exposure measured at f5.6 to determine the proper exposure
for our pinhole camera.
From the above formula we know this factor can be calculated by dividing our f–number (the actual one, not the
normalized one) by 5.6, and squaring the result.
Mathematically, dividing the square of our f–number by the square of 5.6 will give us the same result.
Computationally, we do not want to square two numbers when we can only square one. So, the first solution seems
better at first.
But...
5.6 is a constant. We do not have to have our FPU waste precious cycles. We can just tell it to divide the square of
the f–number by whatever 5.6 2 equals to. Or we can divide the f–number by 5.6, and then square the result. The
two ways now seem equal.
But, they are not!
Having studied the principles of photography above, we remember that the 5.6 is actually square root of 2 raised to
the fifth power. An irrational number. The square of this number is exactly 32.
Not only is 32 an integer, it is a power of 2. We do not need to divide the square of the f–number by 32. We only
need to use fscale to shift it right by five positions. In the FPU lingo it means we will fscale it with st(1) equal
to -5. That is much faster than a division.
So, now it has become clear why we have saved the square of the f–number on the top of the FPU stack. The
calculation of the f5.6 multiplier is the easiest calculation of this entire program! We will output it rounded to four
significant digits.
There is one more useful number we can calculate: The number of stops our f–number is from f5.6. This may help us
if our f–number is just outside the range of our light meter, but we have a shutter which lets us set various speeds,
and this shutter uses stops.
Say, our f–number is 5 stops from f5.6, and the light meter says we should use 1/1000 sec. Then we can set our
shutter speed to 1/1000 first, then move the dial by 5 stops.
This calculation is quite easy as well. All we have to do is to calculate the base-2 logarithm of the f5.6 multiplier we
had just calculated (though we need its value from before we rounded it off). We then output the result rounded to the
nearest integer. We do not need to worry about having more than four significant digits in this one: The result is most
likely to have only one or two digits anyway.
283
Chapter 24 x86 Assembly Language Programming
284
Chapter 24 x86 Assembly Language Programming
on it. So, when the square of the f–number is being scaled, the -5 is at st(1), precisely where fscale expects it to
be.
It is common to create certain constants from scratch instead of loading them from the memory. That is what we are
doing with -5:
fld1 ; TOS = 1
fadd st0, st0 ; TOS = 2
fadd st0, st0 ; TOS = 4
fld1 ; TOS = 1
faddp st1, st0 ; TOS = 5
fchs ; TOS = -5
We can generalize all these optimizations into one rule: Keep repeat values on the stack!
Tip: PostScript is a stack–oriented programming language. There are many more books available about
PostScript than about the FPU assembly language: Mastering PostScript will help you master the FPU.
%include ’system.inc’
section .data
align 4
ten dd 10
thousand dd 1000
tthou dd 10000
285
Chapter 24 x86 Assembly Language Programming
fd.in dd stdin
fd.out dd stdout
envar db ’PINHOLE=’ ; Exactly 8 bytes, or 2 dwords long
pinhole db ’04,’, ; Bender’s constant (0.04)
connors db ’037’, 0Ah ; Connors’ constant
< > < > <
usg db ’Usage: pinhole [-b] [-c] [-e] [-p value ] [-o outfile ] [-i infile ]’, 0Ah >
usglen equ $-usg
iemsg db "pinhole: Can’t open input file", 0Ah
iemlen equ $-iemsg
oemsg db "pinhole: Can’t create output file", 0Ah
oemlen equ $-oemsg
pinmsg db "pinhole: The PINHOLE constant must not be 0", 0Ah
pinlen equ $-pinmsg
toobig db "pinhole: The PINHOLE constant may not exceed 18 decimal places", 0Ah
biglen equ $-toobig
huhmsg db 9, ’???’
separ db 9, ’???’
sep2 db 9, ’???’
sep3 db 9, ’???’
sep4 db 9, ’???’, 0Ah
huhlen equ $-huhmsg
header db ’focal length in millimeters,pinhole diameter in microns,’
db ’F-number,normalized F-number,F-5.6 multiplier,stops ’
db ’from F-5.6’, 0Ah
headlen equ $-header
section .bss
ibuffer resb BUFSIZE
obuffer resb BUFSIZE
dbuffer resb 20 ; decimal input buffer
bbuffer resb 10 ; BCD buffer
section .text
align 4
huh:
call write
push dword huhlen
push dword huhmsg
push dword [fd.out]
sys.write
add esp, byte 12
ret
align 4
perr:
286
Chapter 24 x86 Assembly Language Programming
align 4
consttoobig:
push dword biglen
push dword toobig
push dword stderr
sys.write
push dword 5 ; return failure
sys.exit
align 4
ierr:
push dword iemlen
push dword iemsg
push dword stderr
sys.write
push dword 1 ; return failure
sys.exit
align 4
oerr:
push dword oemlen
push dword oemsg
push dword stderr
sys.write
push dword 2
sys.exit
align 4
usage:
push dword usglen
push dword usg
push dword stderr
sys.write
push dword 3
sys.exit
align 4
global _start
287
Chapter 24 x86 Assembly Language Programming
_start:
add esp, byte 8 ; discard argc and argv[0]
sub esi, esi
.arg:
pop ecx
or ecx, ecx
je near .getenv ; no more arguments
inc ecx
mov ax, [ecx]
inc ecx
.o:
cmp al, ’o’
jne .i
; Make sure we are not asked for the output file twice
cmp dword [fd.out], stdout
jne usage
or ah, ah
jne .openoutput
pop ecx
jecxz usage
.openoutput:
push dword 420 ; file mode (644 octal)
push dword 0200h | 0400h | 01h
; O_CREAT | O_TRUNC | O_WRONLY
push ecx
sys.open
jc near oerr
288
Chapter 24 x86 Assembly Language Programming
.i:
cmp al, ’i’
jne .p
.openinput:
push dword 0 ; O_RDONLY
push ecx
sys.open
jc near ierr ; open failed
.p:
cmp al, ’p’
jne .c
or ah, ah
jne .pcheck
pop ecx
or ecx, ecx
je near usage
.pcheck:
cmp ah, ’0’
jl near usage
cmp ah, ’9’
ja near usage
mov esi, ecx
289
Chapter 24 x86 Assembly Language Programming
jmp .arg
.c:
cmp al, ’c’
jne .b
or ah, ah
jne near usage
mov esi, connors
jmp .arg
.b:
cmp al, ’b’
jne .e
or ah, ah
jne near usage
mov esi, pinhole
jmp .arg
.e:
cmp al, ’e’
jne near usage
or ah, ah
jne near usage
mov al, ’,’
mov [huhmsg], al
mov [separ], al
mov [sep2], al
mov [sep3], al
mov [sep4], al
jmp .arg
align 4
.getenv:
; If ESI = 0, we did not have a -p argument,
; and need to check the environment for "PINHOLE="
or esi, esi
jne .init
.nextenv:
pop esi
or esi, esi
je .default ; no PINHOLE envar found
290
Chapter 24 x86 Assembly Language Programming
align 4
.default:
; We got here because we had no -p argument,
; and did not find the PINHOLE envar.
mov esi, pinhole
; fall through
align 4
.init:
sub eax, eax
sub ebx, ebx
sub ecx, ecx
sub edx, edx
mov edi, dbuffer+1
mov byte [dbuffer], ’0’
inc dl
.processconst:
inc cl
cmp cl, 18
ja near consttoobig
291
Chapter 24 x86 Assembly Language Programming
stosb
jmp short .constloop
align 4
.setconst:
or dl, dl
je near perr
finit
fild dword [tthou]
fld1
fild dword [ten]
fdivp st1, st0
.constdiv:
fmul st0, st2
loop .constdiv
fld1
fadd st0, st0
fadd st0, st0
fld1
faddp st1, st0
fchs
.bigloop:
call getchar
jc near done
292
Chapter 24 x86 Assembly Language Programming
.num:
; See if you got a number
cmp al, ’0’
jl .bigloop
cmp al, ’9’
ja .bigloop
.number:
cmp al, ’0’
je .number0
mov dl, 1
.number0:
or dl, dl ; Skip leading 0’s
je .nextnumber
push eax
call putchar
pop eax
inc ebp
cmp ebp, 19
jae .nextnumber
mov [dbuffer+ebp], al
.nextnumber:
call getchar
jc .work
cmp al, ’#’
je .ungetc
cmp al, ’0’
jl .work
cmp al, ’9’
ja .work
jmp short .number
293
Chapter 24 x86 Assembly Language Programming
.ungetc:
dec esi
inc ebx
.work:
; Now, do all the work
or dl, dl
je near .work0
cmp ebp, 19
jae near .toobig
call bcdload
.printdiameter:
call printnumber ; pinhole diameter
; Calculate F-number
.fnumber:
fcom st0, st6
294
Chapter 24 x86 Assembly Language Programming
fstsw ax
sahf
jb .printfnumber
fmul st0, st5
inc ebp
jmp short .fnumber
.printfnumber:
call printnumber ; F number
fscale
fld st0
jb .printfmul
inc ebp
fmul st0, st5
jmp short .fmul
.printfmul:
call printnumber ; F multiplier
295
Chapter 24 x86 Assembly Language Programming
fld1
fxch st1
fyl2x
.work0:
mov al, ’0’
call putchar
align 4
.toobig:
call huh
jmp .bigloop
align 4
done:
call write ; flush output buffer
; close files
push dword [fd.in]
sys.close
finit
; return success
push dword 0
sys.exit
align 4
skiptoeol:
; Keep reading until you come to cr, lf, or eof
call getchar
jc done
cmp al, 0Ah
jne .cr
ret
296
Chapter 24 x86 Assembly Language Programming
.cr:
cmp al, 0Dh
jne skiptoeol
ret
align 4
getchar:
or ebx, ebx
jne .fetch
call read
.fetch:
lodsb
dec ebx
clc
ret
read:
jecxz .read
call write
.read:
push dword BUFSIZE
mov esi, ibuffer
push esi
push dword [fd.in]
sys.read
add esp, byte 12
mov ebx, eax
or eax, eax
je .empty
sub eax, eax
ret
align 4
.empty:
add esp, byte 4
stc
ret
align 4
putchar:
stosb
297
Chapter 24 x86 Assembly Language Programming
inc ecx
cmp ecx, BUFSIZE
je write
ret
align 4
write:
jecxz .ret ; nothing to write
sub edi, ecx ; start of buffer
push ecx
push edi
push dword [fd.out]
sys.write
add esp, byte 12
sub eax, eax
sub ecx, ecx ; buffer is empty now
.ret:
ret
align 4
bcdload:
; EBP contains the number of chars in dbuffer
push ecx
push esi
push edi
std
.loop:
lodsw
sub ax, 3030h
shl al, 4
or al, ah
mov [edi], al
inc edi
298
Chapter 24 x86 Assembly Language Programming
loop .loop
fbld [bbuffer]
cld
pop edi
pop esi
pop ecx
sub eax, eax
ret
align 4
printnumber:
push ebp
mov al, [separ]
call putchar
.leading:
; Skip leading zeros
mov al, [ebp]
dec ebp
or al, al
jne .first
cmp ebp, bbuffer
jae .leading
299
Chapter 24 x86 Assembly Language Programming
.first:
; We have found the first non-zero.
; But it is still packed
test al, 0F0h
jz .second
push eax
shr al, 4
add al, ’0’
call putchar
pop eax
and al, 0Fh
.second:
add al, ’0’
call putchar
.next:
cmp ebp, bbuffer
jb .done
dec ebp
jmp short .next
.done:
pop ebp
or ebp, ebp
je .ret
.zeros:
mov al, ’0’
call putchar
dec ebp
jne .zeros
.ret:
300
Chapter 24 x86 Assembly Language Programming
ret
The code follows the same format as all the other filters we have seen before, with one subtle exception:
We are no longer assuming that the end of input implies the end of things to do, something we took for granted in the
character–oriented filters.
This filter does not process characters. It processes a language (albeit a very simple one, consisting only of numbers).
When we have no more input, it can mean one of two things:
• The last character we have read was a digit. We have stored it at the end of our ASCII–to–float conversion buffer. We now
need to convert the contents of that buffer into a number and write the last line of our output.
For that reason, we have modified our getchar and our read routines to return with the carry flag clear whenever we
are fetching another character from the input, or the carry flag set whenever there is no more input.
Of course, we are still using assembly language magic to do that! Take a good look at getchar. It always returns with the
carry flag clear.
Yet, our main code relies on the carry flag to tell it when to quit—and it works.
The magic is in read. Whenever it receives more input from the system, it just returns to getchar, which fetches a
character from the input buffer, clears the carry flag and returns.
But when read receives no more input from the system, it does not return to getchar at all. Instead, the add esp, byte
4 op code adds 4 to ESP, sets the carry flag, and returns.
So, where does it return to? Whenever a program uses the call op code, the microprocessor pushes the return address, i.e.,
it stores it on the top of the stack (not the FPU stack, the system stack, which is in the memory). When a program uses the
ret op code, the microprocessor pops the return value from the stack, and jumps to the address that was stored there.
But since we added 4 to ESP (which is the stack pointer register), we have effectively given the microprocessor a minor case
of amnesia: It no longer remembers it was getchar that called read.
And since getchar never pushed anything before calling read, the top of the stack now contains the return address to
whatever or whoever called getchar. As far as that caller is concerned, he called getchar, which returned with the
carry flag set!
Other than that, the bcdload routine is caught up in the middle of a Lilliputian conflict between the Big–Endians
and the Little–Endians.
It is converting the text representation of a number into that number: The text is stored in the big–endian order, but
the packed decimal is little–endian.
To solve the conflict, we use the std op code early on. We cancel it with cld later on: It is quite important we do not
call anything that may depend on the default setting of the direction flag while std is active.
Everything else in this code should be quite clear, providing you have read the entire chapter that precedes it.
301
Chapter 24 x86 Assembly Language Programming
It is a classical example of the adage that programming requires a lot of thought and only a little coding. Once we
have thought through every tiny detail, the code almost writes itself.
% pinhole
Computer,
We have found that while for the focal length of 150, our pinhole diameter should be 490 microns, or 0.49 mm, if we
go with the almost identical focal length of 156 mm, we can get away with a pinhole diameter of exactly one half of
a millimeter.
302
Chapter 24 x86 Assembly Language Programming
24.13.7 Scripting
Because we have chosen the # character to denote the start of a comment, we can treat our pinhole software as a
scripting language.
You have probably seen shell scripts that start with:
#! /bin/sh
...or...
#!/bin/sh
#! /usr/local/bin/pinhole -b -i
# Find the best pinhole diameter
# for the 120 film
### Standard
80
### Telephoto
100, 120, 140
Because 120 is a medium size film, we may name this file medium.
We can set its permissions to execute, and run it as if it were a program:
% /usr/local/bin/pinhole -b -i ./medium
303
Chapter 24 x86 Assembly Language Programming
% ./medium -c
% /usr/local/bin/pinhole -b -i ./medium -c
That gives it two conflicting options: -b and -c (Use Bender’s constant and use Connors’ constant). We have
programmed it so later options override early ones—our program will calculate everything using Connors’ constant:
We decide we want to go with Bender’s constant after all. We want to save its values as a comma–separated file:
304
Chapter 24 x86 Assembly Language Programming
140,473,296,256,2734,11
%
24.14 Caveats
Assembly language programmers who "grew up" under MS DOS and Windows often tend to take shortcuts. Reading
the keyboard scan codes and writing directly to video memory are two classical examples of practices which, under
MS DOS are not frowned upon but considered the right thing to do.
The reason? Both the PC BIOS and MS DOS are notoriously slow when performing these operations.
You may be tempted to continue similar practices in the Unix environment. For example, I have seen a web site
which explains how to access the keyboard scan codes on a popular Unix clone.
That is generally a very bad idea in Unix environment! Let me explain why.
305
Chapter 24 x86 Assembly Language Programming
If you have written program2, your input does not come from the keyboard but from the output of program1.
Similarly, your output does not go to the screen but becomes the input for program3 whose output, in turn, goes to
file1.
But there is more! Even if you made sure that your input comes from, and your output goes to, the terminal, there is
no guarantee the terminal is a PC: It may not have its video memory where you expect it, nor may its keyboard be
producing PC-style scan codes. It may be a Macintosh, or any other computer.
Now you may be shaking your head: My software is in PC assembly language, how can it run on a Macintosh? But I
did not say your software would be running on a Macintosh, only that its terminal may be a Macintosh.
Under Unix, the terminal does not have to be directly attached to the computer that runs your software, it can even be
on another continent, or, for that matter, on another planet. It is perfectly possible that a Macintosh user in Australia
connects to a Unix system in North America (or anywhere else) via telnet. The software then runs on one computer,
while the terminal is on a different computer: If you try to read the scan codes, you will get the wrong input!
Same holds true about any other hardware: A file you are reading may be on a disk you have no direct access to. A
camera you are reading images from may be on a space shuttle, connected to you via satellites.
That is why under Unix you must never make any assumptions about where your data is coming from and going to.
Always let the system handle the physical access to the hardware.
Note: These are caveats, not absolute rules. Exceptions are possible. For example, if a text editor has
determined it is running on a local machine, it may want to read the scan codes directly for improved control. I am
not mentioning these caveats to tell you what to do or what not to do, just to make you aware of certain pitfalls
that await you if you have just arrived to Unix form MS DOS. Of course, creative people often break rules, and it
is OK as long as they know they are breaking them and why.
24.15 Acknowledgements
This tutorial would never have been possible without the help of many experienced FreeBSD programmers from the
FreeBSD hackers (mailto:[email protected]) mailing list, many of whom have patiently answered my
questions, and pointed me in the right direction in my attempts to explore the inner workings of Unix system
programming in general and FreeBSD in particular.
Thomas M. Sommers opened the door for me. His How do I write "Hello, world" in FreeBSD assembler?
(http://home.ptd.net/~tms2/hello.html) web page was my first encounter with an example of assembly language
programming under FreeBSD.
Jake Burkholder has kept the door open by willingly answering all of my questions and supplying me with example
assembly language source code.
306
Chapter 24 x86 Assembly Language Programming
307
Chapter 25 Alpha
Talk about the architectural specifics of FreeBSD/alpha.
Explanation of allignment errors, how to fix, how to ignore.
Example assembly language code for FreeBSD/alpha.
308
Chapter 26 IA-64
Talk about the architectural specifics of FreeBSD/ia64.
309
XIII. Debugging
Chapter 27 Truss
various descriptions on how to debug certain aspects of the system using truss, ktrace, gdb, kgdb, etc
311
XIV. Compatibility Layers
Chapter 28 Linux
Linux, SVR4, etc
313
XV. Appendices
Bibliography
[1] Dave A Patterson and John L Hennessy, 1998, 1-55860-428-6, Morgan Kaufmann Publishers, Inc., Computer
Organization and Design: The Hardware / Software Interface, 1-2.
[2] W. Richard Stevens, 1993, 0-201-56317-7, Addison Wesley Longman, Inc., Advanced Programming in the Unix
Environment, 1-2.
[3] Marshall Kirk McKusick, Keith Bostic, Michael J Karels, and John S Quarterman, 1996, 0-201-54979-4,
Addison-Wesley Publishing Company, Inc., The Design and Implementation of the 4.4 BSD Operating System,
1-2.
[4] Aleph One, Phrack 49; "Smashing the Stack for Fun and Profit".
[5] Chrispin Cowan, Calton Pu, and Dave Maier, StackGuard; Automatic Adaptive Detection and Prevention of
Buffer-Overflow Attacks.
[6] Todd Miller and Theo de Raadt, strlcpy and strlcat -- consistent, safe string copy and concatenation..
Index D
data validation, 42
A
arguments, 37 F
frame pointer, 37
B
bounds checking
compiler-based, 39 G
library-based, 40
buffer overflow, 37, 39 gcc, 39
C J
CERT
jail, 41
security advisories, 37
chroot(), 40
315
L signals, 42
return address, 37
LIFO, 37
S
M
seteuid, 40
Morris Internet worm, 37
stack, 37
stack frame, 37
stack pointer, 37
N stack-overflow, 37
StackGuard, 39
NUL termination, 39
string copy functions
strlcat, 39
strlcpy, 39
O strncat, 39
strncpy, 39
OpenBSD, 39
P T
TrustedBSD, 41
Perl Taint mode, 42
positive filtering, 42
POSIX.1e Process Capabilities, 41
process image U
frame pointer, 37
stack pointer, 37 user IDs
effective user ID, 40
real user ID, 40
R
race conditions V
access checks, 42
file opens, 42 Von-Neuman, 37