home *** CD-ROM | disk | FTP | other *** search
/ Chip 1998 February / CHIP_2_98.iso / doc / HOWTO / mini / IO-Port-Programming < prev    next >
Text File  |  1997-03-28  |  22KB  |  489 lines

  1.  
  2.         Linux I/O port programming mini-HOWTO
  3.  
  4.         Author: Riku Saikkonen <Riku.Saikkonen@hut.fi>
  5.         Last modified: Mar 30 1997
  6.  
  7. This document is Copyright 1995-1997 Riku Saikkonen. See the normal Linux
  8. HOWTO COPYRIGHT for details.
  9.  
  10.  
  11. This HOWTO document describes programming hardware I/O ports and waiting for
  12. small periods of time in user-mode Linux programs running on an Intel x86
  13. processor. This document is a descendant of the very small IO-Port
  14. mini-HOWTO by the same author.
  15.  
  16. If you have corrections or something to add, feel free to e-mail me
  17. (Riku.Saikkonen@hut.fi)...
  18.  
  19. Changes from the previous version (Aug 26 1996):
  20. Author's e-mail address changed.
  21. Ioperm() privileges are not transferred across fork()s, as I had thought.
  22. Added pointers (URLs) to information on quite a few topics.
  23. Other minor changes.
  24.  
  25.  
  26.         I/O ports in C programs, the normal way
  27.  
  28. Routines for accessing I/O ports are in /usr/include/asm/io.h (or
  29. linux/include/asm-i386/io.h in the kernel source distribution). The routines
  30. there are inline macros, so it is enough to #include <asm/io.h>; you do not
  31. need any additional libraries.
  32.  
  33. Because of a limitation in gcc (present at least in 2.7.2.1 and below), you
  34. _have to_ compile any source code that uses these routines with optimisation
  35. turned on (gcc -O1 or higher), or alternatively #define extern to be
  36. empty before #including <asm/io.h>.
  37.  
  38. For debugging, you can use "gcc -g -O" (at least with modern versions of
  39. gcc), though optimisation can sometimes make the debugger behave a bit
  40. strangely. If this bothers you, put the routines that use I/O port access in
  41. a separate source file and compile only that with optimisation turned on.
  42.  
  43. Before you access any ports, you must give your program permission to do it.
  44. This is done by calling the ioperm(2) function (declared in unistd.h, and
  45. defined in the kernel) somewhere near the start of your program (before any
  46. I/O port accesses). The syntax is ioperm(from,num,turn_on), where from is
  47. the first port number to give access to, and num the number of consecutive
  48. ports to give access to. For example, ioperm(0x300,5,1); would give access
  49. to ports 0x300 through 0x304 (a total of 5 ports). The last argument is a
  50. Boolean value specifying whether to give access to the program to the ports
  51. (true (1)) or to remove access (false (0)). You may call ioperm() multiple
  52. times to enable multiple non-consecutive ports. See the ioperm(2) manual
  53. page for details on the syntax.
  54.  
  55. The ioperm() call requires your program to have root privileges; thus you
  56. need to either run it as the root user, or make it setuid root. You can drop
  57. the root privileges after you have called ioperm() to enable the ports you
  58. want to use. You are not required to explicitly drop your port access
  59. privileges with ioperm(...,0); at the end of your program, it is done
  60. automatically as the program exits.
  61.  
  62. A setuid() to a non-root user does not disable the port access granted by
  63. ioperm(), but a fork() does.
  64.  
  65. Ioperm() can only give access to ports 0x000 through 0x3ff; for higher
  66. ports, you need to use iopl(2) (which gives you access to all ports at
  67. once). Use the level argument 3 (i.e. "iopl(3);") to give your program
  68. access to all I/O ports (so be careful -- accessing the wrong ports can do
  69. all sorts of nasty things to your computer). Again, you need root privileges
  70. to call iopl().
  71.  
  72. Then, to actually accessing the ports... To input a byte (8 bits) from a
  73. port, call inb(port);, it returns the byte it got. To output a byte, call
  74. outb(value, port); (notice the order of the parameters). To input a word (16
  75. bits) from ports x and x+1 (one byte from each to form the word, just like
  76. the assembler instruction INW), call inw(x);. To output a word to the two
  77. ports, outw(value,x);. If you're unsure of which port instructions
  78. (byte/word) to use, you probably want inb() and outb() -- most devices are
  79. designed for bytewise port access. Note that all port instructions take at
  80. least about a microsecond to execute.
  81.  
  82. The inb_p(), outb_p(), inw_p(), and outw_p() macros work otherwise
  83. identically to the ones above, but they do an additional short (about one
  84. microsecond) delay after the port access; you can make the delay four
  85. microseconds by #defining REALLY_SLOW_IO before #including <asm/io.h>. These
  86. macros normally (unless you #define SLOW_IO_BY_JUMPING, which probably isn't
  87. accurate) use a port output to port 0x80 for their delay, so you need to
  88. give access to port 0x80 with ioperm() first (outputs to port 0x80 should
  89. not affect any part of the system). For more versatile methods of delaying,
  90. read on.
  91.  
  92. There are man pages for ioperm(), iopl(), and the above macros in reasonably
  93. recent releases of the Linux man-pages distribution.
  94.  
  95.  
  96.         An alternate method for I/O port access
  97.  
  98. Another way to access I/O ports is to open() /dev/port (a character device,
  99. major number 1, minor 4) for reading and/or writing (the stdio f*()
  100. functions have internal buffering, so avoid them). Then lseek() to the
  101. appropriate byte in the file (file position 0 = port 0, file position 1 =
  102. port 1, and so on), and read() or write() a byte or word from or to it.
  103.  
  104. Of course, for this your program needs read/write access to /dev/port. This
  105. method is probably slower than the normal method above, but does not need
  106. optimisation nor ioperm() (nor root access, if you give a non-root user or
  107. group access to /dev/port).
  108.  
  109.  
  110.         Interrupts (IRQs) and DMA access
  111.  
  112. You cannot use IRQs or DMA directly from a user-mode program. You need to
  113. write a kernel driver; see the Linux Kernel Hacker's Guide
  114. (<URL:http://www.redhat.com:8080/HyperNews/get/khg.html>) for details and
  115. the kernel source code for examples.
  116.  
  117. You also cannot disable interrupts from within a user-mode program.
  118.  
  119.  
  120.         High-resolution timing: Delays
  121.  
  122. First of all, I should say that you cannot guarantee user-mode processes to
  123. have exact control of timing because of the multi-tasking, pre-emptive
  124. nature of Linux. Your process might be scheduled out at any time for
  125. anything from about 10 milliseconds to a few seconds (on a system with very
  126. high load). However, for most applications using I/O ports, this does not
  127. really matter. To minimise this, you may want to nice your process to a
  128. high-priority value (see the nice(2) manual page).
  129.  
  130. If you want more precise timing than normal user-mode processes give you,
  131. there are some provisions for user-mode `real time' support. Linux 2.x
  132. kernels have soft real time support; see the man page for
  133. sched_setscheduler(2) for details. There is a special kernel that supports
  134. hard real time; see <URL:http://luz.cs.nmt.edu/~rtlinux/> for more
  135. information on this.
  136.  
  137. Now, let me start with the easier timing calls. For delays of multiple
  138. seconds, your best bet is probably to use sleep(3). For delays of at least
  139. tens of milliseconds (about 10 ms seems to be the minimum delay), usleep(3)
  140. should work. These functions give the CPU to other processes, so CPU time
  141. isn't wasted. See the manual pages for details.
  142.  
  143. For delays of under about 50 milliseconds (depending on the speed of your
  144. processor and machine, and the system load), giving up the CPU doesn't work
  145. because the Linux scheduler usually takes at least about 10-30 milliseconds
  146. before it returns control to your process. Due to this, in small delays,
  147. usleep(3) usually delays somewhat more than the amount that you specify in
  148. the parameters, and at least about 10 ms.
  149.  
  150. For short delays (tens of us to 50 ms or so), a versatile method is to
  151. use udelay(), defined in /usr/include/asm/delay.h (linux/include/asm-i386/
  152. delay.h). Udelay() takes the number of microseconds to delay (an unsigned
  153. long) as its sole parameter, and returns nothing. It may take up to a few
  154. microseconds more time than the parameter specifies because of the overhead
  155. in the calculation of how long to wait (see delay.h for details).
  156.  
  157. To use udelay() outside of the kernel, you need to have the unsigned long
  158. variable loops_per_sec defined with the correct value. As far as I know, the
  159. only way to get this value from the kernel is to read /proc/cpuinfo for the
  160. BogoMips value and multiply that by 500000 to get (an imprecise)
  161. loops_per_sec.
  162.  
  163. In the 2.0.x series of Linux kernels, there is a new system call,
  164. nanosleep(2) (see the man page), that should allow you to sleep or delay for
  165. short times. It uses udelay() for delays <= 2 ms if your process is set to
  166. soft real time scheduling (using sched_setscheduler(2)), otherwise it sleeps
  167. (like usleep()). You don't need a loops_per_sec variable to use nanosleep(),
  168. the system call gets the value from the kernel.
  169.  
  170. Another way of delaying small numbers of microseconds is port I/O. Inputting
  171. or outputting any byte from/to port 0x80 (see above for how to do it) should
  172. wait for almost exactly 1 microsecond independent of your processor type and
  173. speed. You can do this multiple times to wait a few microseconds. The port
  174. output should have no harmful side effects on any standard machine (and some
  175. kernel drivers use it). This is how {in|out}[bw]_p() normally do the delay
  176. (see asm/io.h).
  177.  
  178. Actually, a port I/O instruction on most ports in the 0-0x3ff range takes
  179. almost exactly 1 microsecond, so if you're, for example, using the parallel
  180. port directly, just do additional inb()s from that port to delay.
  181.  
  182. If you know the processor type and clock speed of the machine the program
  183. will be running on, you can hard-code shorter delays by running certain
  184. assembler instructions (but remember, your process might be scheduled out at
  185. any time, so the delays might well be longer every now and then). For the
  186. table below, the internal processor speed determines the number of clock
  187. cycles taken; e.g. for a 50 MHz processor (e.g. 486DX-50 or 486DX2-50), one
  188. clock cycle takes 1/50000000 seconds.
  189.  
  190. Instruction   i386 clock cycles   i486 clock cycles
  191. nop                   3                   1
  192. xchg %ax,%ax          3                   3
  193. or %ax,%ax            2                   1
  194. mov %ax,%ax           2                   1
  195. add %ax,0             2                   1
  196. (sorry, I don't know about Pentiums; probably close to the i486)
  197. (I cannot find an instruction which would use one clock cycle on an i386)
  198.  
  199. The instructions nop and xchg in the table should have no side effects. The
  200. rest may modify the flags register, but this shouldn't matter since gcc
  201. should detect it.
  202.  
  203. To use these, call asm("instruction"); in your program. Have the
  204. instructions in the syntax in the table above; to have multiple instructions
  205. in one asm(), asm("instruction ; instruction ; instruction");. The asm() is
  206. translated into inline assembler code by gcc, so there is no function call
  207. overhead.
  208.  
  209. For Pentiums, you can get the number of clock cycles elapsed since the last
  210. reboot with the following C code:
  211.    extern __inline__ unsigned long long int rdtsc()
  212.    {
  213.      unsigned long long int x;
  214.      __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
  215.      return x;
  216.    }
  217.  
  218. Shorter delays than one clock cycle are impossible in the Intel x86
  219. architecture.
  220.  
  221.  
  222.         High-resolution timing: Measuring time
  223.  
  224. For times accurate to one second, it is probably easiest to use time(2). For
  225. more accurate times, gettimeofday(2) is accurate to about a microsecond (but
  226. see above about scheduling). For Pentiums, the code fragment above is
  227. accurate to one clock cycle.
  228.  
  229. If you want your process to get a signal after some amount of time, use
  230. setitimer(2). See the manual pages of the functions for details.
  231.  
  232.  
  233.         Other programming languages
  234.  
  235. The description above concentrates on the C programming language. It should
  236. apply directly to C++ and Objective C. In assembler, you have to call
  237. ioperm() or iopl() as in C, but after that you can use the I/O port
  238. read/write instructions directly.
  239.  
  240. In other languages, unless you can insert inline assembler or C code into
  241. the program, it is probably easiest to write a simple C source file with
  242. functions for the I/O port access you need, and compile and link it in with
  243. the rest of your program. Or use /dev/port as described above.
  244.  
  245.  
  246.         Some useful ports
  247.  
  248. Here is some programming information for common ports that can be directly
  249. used for general-purpose TTL (or CMOS) logic I/O.
  250.  
  251.  
  252. The parallel port (BASE = 0x3bc for /dev/lp0, 0x378 for /dev/lp1, and 0x278
  253. for /dev/lp2): (if you only want to control something that acts like a
  254. normal printer, see the Printing-HOWTO)
  255.  
  256. In addition to the standard output-only mode described below, there is an
  257. `extended' bidirectional mode in most parallel ports. For information on
  258. this and the newer ECP/EPP modes (and the IEEE 1284 standard in general),
  259. see <URL:http://www.fapo.com/> and
  260. <URL:http://www.senet.com.au/~cpeacock/parallel.htm>. Remember that since
  261. you cannot use IRQs or DMA in a user-mode program, you will probably have to
  262. write a kernel driver to use ECP/EPP; I think someone is writing such a
  263. driver, but I don't know the details.
  264.  
  265. Port BASE+0 (Data port) controls the data signals of the port (D0 to D7 for
  266. bits 0 to 7, respectively; states: 0 = low (0 V), 1 = high (5 V)). A write
  267. to this port latches the data on the pins. A read returns the data last
  268. written in standard or extended write mode, or the data in the pins from
  269. another device in extended read mode.
  270.  
  271. Port BASE+1 (Status port) is read-only, and returns the state of the
  272. following input signals:
  273. Bits 0 and 1 are reserved.
  274. Bit 2 IRQ status (not a pin, I don't know how this works)
  275. Bit 3 ERROR (1=high)
  276. Bit 4 SLCT (1=high)
  277. Bit 5 PE (1=high)
  278. Bit 6 ACK (1=high)
  279. Bit 7 -BUSY (0=high)
  280. (I'm not sure about the high and low states.)
  281.  
  282. Port BASE+2 (Control port) is write-only (a read returns the data last
  283. written), and controls the following status signals:
  284. Bit 0 -STROBE (0=high)
  285. Bit 1 AUTO_FD_XT (1=high)
  286. Bit 2 -INIT (0=high)
  287. Bit 3 SLCT_IN (1=high)
  288. Bit 4 enables the parallel port IRQ (which occurs on the low-to-high
  289. transition of ACK) when set to 1.
  290. Bit 5 controls the extended mode direction (0 = write, 1 = read), and is
  291. completely write-only (a read returns nothing useful for this bit).
  292. Bits 6 and 7 are reserved.
  293. (Again, I am not sure about the high and low states.)
  294.  
  295. Pinout (a 25-pin female D-shell connector on the port) (i=input, o=output):
  296. 1io -STROBE, 2io D0, 3io D1, 4io D2, 5io D3, 6io D4, 7io D5, 8io D6, 9io D7,
  297. 10i ACK, 11i -BUSY, 12i PE, 13i SLCT, 14o AUTO_FD_XT, 15i ERROR, 16o -INIT,
  298. 17o SLCT_IN, 18-25 Ground
  299.  
  300. The IBM specifications say that pins 1, 14, 16, and 17 (the control outputs)
  301. have open collector drivers pulled to 5 V through 4.7 kiloohm resistors
  302. (sink 20 mA, source 0.55 mA, high-level output 5.0 V minus pullup). The rest
  303. of the pins sink 24 mA, source 15 mA, and their high-level output is min.
  304. 2.4 V. The low state for both is max. 0.5 V. Non-IBM parallel ports probably
  305. deviate from this standard. For more information on this, see
  306. <URL:http://www.hut.fi/~then/circuits/lptpower.html>.
  307.  
  308. Finally, a warning: Be careful with grounding. I've broken several parallel
  309. ports by connecting to them while the computer is turned on. It might be a
  310. good thing to use a parallel port not integrated on the motherboard for
  311. things like this. (You can usually get a second parallel port for your
  312. machine with a cheap standard `multi-IO' card; just disable the ports that
  313. you don't need, and set the parallel port address on the card to a free
  314. address. You don't need to care about the parallel port IRQs, since they
  315. aren't usually used.)
  316.  
  317.  
  318. The game (joystick) port (ports 0x200-0x207): (for controlling normal
  319. joysticks, there is a kernel-level joystick driver, see
  320. ftp://sunsite.unc.edu/pub/Linux/kernel/patches/joystick-*)
  321.  
  322. Pinout (a 15-pin female D-shell connector on the port):
  323. 1,8,9,15: +5 V (power)
  324. 4,5,12: Ground
  325. 2,7,10,14: Digital inputs BA1, BA2, BB1, and BB2, respectively
  326. 3,6,11,13: Analog inputs AX, AY, BX, and BY, respectively
  327.  
  328. The +5 V pins seem to be connected directly to the power lines in the
  329. motherboard, so they should be able to source quite a lot of power,
  330. depending on the motherboard, power supply and game port.
  331.  
  332. The digital inputs are used for the buttons of the two joysticks (joystick A
  333. and joystick B, with two buttons each) that you can connect to the port.
  334. They should be normal TTL-level inputs, and you can read their status
  335. directly from the status port (see below). A real joystick returns a low (0
  336. V) status when the button is pressed and a high (the 5 V from the power pins
  337. through an 1 Kohm resistor) status otherwise.
  338.  
  339. The so-called analog inputs actually measure resistance. The game port has a
  340. quad one-shot multivibrator (a 558 chip) connected to the four inputs. In
  341. each input, there is a 2.2 Kohm resistor between the input pin and the
  342. multivibrator output, and a 0.01 uF timing capacitor between the
  343. multivibrator output and the ground. A real joystick has a potentiometer for
  344. each axis (X and Y), wired between +5 V and the appropriate input pin (AX or
  345. AY for joystick A, or BX or BY for joystick B).
  346.  
  347. The multivibrator, when activated, sets its output lines high (5 V) and
  348. waits for each timing capacitor to reach 3.3 V before lowering the
  349. respective output line. Thus the high period duration of the multivibrator
  350. is proportional to the resistance of the potentiometer in the joystick (i.e.
  351. the position of the joystick in the appropriate axis), as follows:
  352.    R = (t - 24.2) / 0.011,
  353. where R is the resistance (ohms) of the potentiometer and t the high period
  354. duration (seconds).
  355.  
  356. Thus, to read the analog inputs, you first activate the multivibrator (with
  357. a port write; see below), then poll the state of the four axes (with
  358. repeated port reads) until they drop from high to low state, measuring their
  359. high period duration. This polling uses quite a lot of CPU time, and on a
  360. non-realtime multitasking system like (normal) Linux, the result is not very
  361. accurate because you cannot poll the port constantly (unless you use a
  362. kernel-level driver and disable interrupts while polling, but this wastes
  363. even more CPU time). If you know that the signal is going to take a long
  364. time (tens of ms) to go down, you can call usleep() before polling to give
  365. CPU time to other processes.
  366.  
  367. The only I/O port you need to access is port 0x201 (the other ports either
  368. behave identically or do nothing). Any write to this port (it doesn't matter
  369. what you write) activates the multivibrator. A read from this port returns
  370. the state of the input signals:
  371. Bit 0: AX (status (1=high) of the multivibrator output)
  372. Bit 1: AY (status (1=high) of the multivibrator output)
  373. Bit 2: BX (status (1=high) of the multivibrator output)
  374. Bit 3: BY (status (1=high) of the multivibrator output)
  375. Bit 4: BA1 (digital input, 1=high)
  376. Bit 5: BA2 (digital input, 1=high)
  377. Bit 6: BB1 (digital input, 1=high)
  378. Bit 7: BB2 (digital input, 1=high)
  379.  
  380.  
  381. The serial ports: If the device you're talking to supports something
  382. resembling RS-232, you should be able to use the serial port to talk to it.
  383. The Linux serial driver should be enough for almost all applications (you
  384. shouldn't have to program the serial port directly; you'd probably have to
  385. write a kernel driver to do that, anyway); it is quite versatile, so using
  386. non-standard bps rates and so on shouldn't be a problem.
  387.  
  388. See the termios(3) man page, the serial driver source code
  389. (/usr/src/linux/drivers/char/serial.c), and
  390. <URL:http://www.easysw.com/~mike/serial/index.html> for more information on
  391. programming serial ports on Unix systems.
  392.  
  393.  
  394. If you want good analog I/O, you can wire up ADC and/or DAC chips to the
  395. parallel port (hint: for power, use the game port connector or a spare disk
  396. drive power connector wired to outside the computer case, unless you have a
  397. low-power device and can use the parallel port itself for power), or buy an
  398. AD/DA card (most of the slower ones are controlled by I/O ports). Or, if
  399. you're satisfied with 1 or 2 channels, inaccuracy, and (probably) bad
  400. zeroing, a cheap sound card supported by the Linux sound driver should do
  401. (and it's pretty fast).
  402.  
  403. Another hint: If you're looking for printed circuit board design software
  404. for Linux, there is a free X11 application called Pcb that should do a nice
  405. job, at least if you aren't doing anything very complex. It is included in
  406. many Linux distributions, and available in
  407. ftp://sunsite.unc.edu/pub/Linux/apps/circuits/pcb-*.
  408.  
  409.  
  410.         Troubleshooting
  411.  
  412. Q1. I get segmentation faults when accessing ports.
  413.  
  414. A1. Either your program does not have root privileges, or the ioperm() call
  415.     failed for some other reason. Check the return value of ioperm(). Also,
  416.     check that you're actually accessing the ports that you enabled with
  417.     ioperm() (see question 3).
  418.  
  419. Q2. I can't find the in*(), out*() functions defined anywhere, gcc complains
  420.     about undefined references.
  421.  
  422. A2. You did not compile with optimisation turned on (-O), and thus gcc could
  423.     not resolve the macros in asm/io.h. Or you did not #include <asm/io.h>
  424.     at all.
  425.  
  426. Q3. out*() doesn't do anything, or does something weird.
  427.  
  428. A3. Check the order of the parameters; it should be outb(value,port), not
  429.     outportb(port,value) as is common in MS-DOS.
  430.  
  431. Q4. I want to control a standard RS-232 device/parallel printer/joystick...
  432.  
  433. A4. You're probably better off using existing drivers (in the Linux kernel
  434.     or an X server or somewhere else) to do it. The drivers are usually
  435.     quite versatile, so even slightly non-standard devices usually work with
  436.     them. See the information on standard ports above for pointers to
  437.     documentation for them.
  438.  
  439.  
  440.         Software example
  441.  
  442. Here's a piece of simple example code for I/O port access:
  443.  
  444. /*
  445.  * example.c: very simple example of port I/O
  446.  *
  447.  * This code does nothing useful, just a port write, a pause,
  448.  * and a port read. Compile with `gcc -O2 -o example example.c'.
  449.  */
  450.  
  451. #include <stdio.h>
  452. #include <unistd.h>
  453. #include <asm/io.h>
  454.  
  455. #define BASEPORT 0x378 /* lp1 */
  456.  
  457. int main()
  458. {
  459.   /* Get access to the ports */
  460.   if (ioperm(BASEPORT,3,1)) {perror("ioperm");exit(1);}
  461.   
  462.   /* Set the data signals (D0-7) of the port to all low (0) */
  463.   outb(0,BASEPORT);
  464.   
  465.   /* Sleep for a while (100 ms) */
  466.   usleep(100000);
  467.   
  468.   /* Read from the status port (BASE+1) and display the result */
  469.   printf("status: %d\n",inb(BASEPORT+1));
  470.  
  471.   /* We don't need the ports anymore */
  472.   if (ioperm(BASEPORT,3,0)) {perror("ioperm");exit(1);}
  473.  
  474.   exit(0);
  475. }
  476.  
  477. /* end of example.c */
  478.  
  479.  
  480.         Credits
  481.  
  482. Too many people have contributed for me to list, but thanks a lot, everyone.
  483. I have not replied to all the contributions that I've received; sorry for
  484. that, and thanks again for the help.
  485.  
  486.  
  487. End of the Linux I/O port programming mini-HOWTO.
  488.  
  489.