diff --git a/en/tutorials/ddwg/ddwg.sgml b/en/tutorials/ddwg/ddwg.sgml index a9c40d5c5b..1738fcd42a 100644 --- a/en/tutorials/ddwg/ddwg.sgml +++ b/en/tutorials/ddwg/ddwg.sgml @@ -1,1128 +1,1128 @@
FreeBSD Device Driver Writer's Guide <author>Eric L. Hernes, <tt/erich@rrnet.com/ <date>Wednesday, May 29, 1996 <abstract> This document describes how to add a device driver to FreeBSD. It is <it/not/ intended to be a tutorial on unix device drivers in general. It is intended for device driver authors, familiar with the unix device driver model, to work on FreeBSD. </abstract> <toc> <sect> Overview <p> <it> The FreeBSD kernel is very well documented, unfortunately it's all in `C'. </it> <sect> Types of drivers. <sect1> Character <sect2> Data Structures <p> <tt/struct cdevsw/ Structure <sect2> Entry Points <sect3> d_open() <p> d_open() takes several arguments, the formal list looks something like: <code> int d_open(dev_t dev, int flag, int mode, struct proc *p) </code> d_open() is called on <em/every/ open of the device. <p> The <tt/dev/ argument contains the major and minor number of the device opened. These are available through the macros <tt/major()/ and <tt/minor()/ <p> The <tt/flag/ and <tt/mode/ arguments are as described in the open(2) manual page. It is recommended that you check these for access modes in <sys/fcntl.h> and do what is required. For example if <tt/flag/ is (O_NONBLOCK | O_EXLOCK) the open should fail if either it would block, or exclusive access cannot be granted. <p> The <tt/p/ argument contains all the information about the current process. <sect3> d_close() <p> d_close() takes the same argument list as d_open(): <code> int d_close(dev_t dev , int flag , int mode , struct proc *p) </code> d_close() is only called on the last close of your device (per minor device). For example in the following code fragment, d_open() is called 3 times, but d_close() is called only once. <code> ... fd1=open("/dev/mydev", O_RDONLY); fd2=open("/dev/mydev", O_RDONLY); fd3=open("/dev/mydev", O_RDONLY); ... <useful stuff with fd1, fd2, fd3 here> ... close(fd1); close(fd2); close(fd3); ... </code> The arguments are similar to those described above for d_open(). <sect3> d_read() and d_write() <p> d_read() and d_write take the following argument lists: <code> int d_read(dev_t dev, struct uio *uio, int flat) int d_write(dev_t dev, struct uio *uio, int flat) </code> The d_read() and d_write() entry points are called when read(2) and write(2) are called on your device from user-space. The transfer of data can be handled through the kernel support routine uiomove(). <sect3> d_ioctl() <p> It's argument list is as follows: <code> int d_ioctl(dev_t dev, int cmd, caddr_t arg, int flag, struct proc *p) </code> d_ioctl() is a catch-all for operations which don't make sense in a read/write paradigm. Probably the most famous of all ioctl's is on tty devices, through stty(1). The ioctl entry point is called from ioctl() in sys/kern/sys_generic.c<p> There are four different types of ioctl's which can be implemented. <sys/ioccom.h> contains convenience macros for defining these ioctls. <tt/_IO(g,n)/ for control type operations. &nl; <tt/_IOR(g,n,t)/ for operations that read data from a device. &nl; <tt/_IOW(g,n,t)/ for operations that write data to a device. &nl; <tt/_IOWR(g,n,t)/ for operations that write to a device, and then read data back. &nl; Here <tt/g/ refers to a <em/group/. This is an 8-bit value, typically indicative of the device; for example, 't' is used in tty ioctls. <tt/n/ refers to the number of the ioctl within the group. On SCO, this number alone denotes the ioctl. <tt/t/ is the data type which will get passed to the driver; this gets handed to a sizeof() operator in the kernel. The ioctl() system call will either copyin() or copyout() or both for your driver, then hand you a pointer to the data structure in the <tt/arg/ argument of the d_ioctl call. Currently the data size is limited to one page (4k on the i386). <sect3> d_stop() <sect3> d_reset() <sect3> d_devtotty() <sect3> d_select() <sect3> d_mmap() <sect3> d_strategy() <p> d_strategy()'s argument list is as follows: <code> void d_strategy(struct buf *bp) </code> <p> d_strategy() is used for devices which use some form of scatter-gather io. It is most common in a block device. This is significantly different than the System V model, where only the block driver performs scatter-gather io. Under BSD, character devices are sometimes requested to perform scatter-gather io via the readv() and writev() system calls. <sect2> Header Files <sect1> Block <sect2> Data Structures <p> <tt/struct bdevsw/ Structure <p> <tt/struct buf/ Structure <sect2> Entry Points <sect3> d_open() <p> Described in the Character device section. <sect3> d_close() <p> Described in the Character device section. <sect3> d_strategy() <p> Described in the Character device section. <sect3> d_ioctl() <p> Described in the Character device section. <sect3> d_dump() <sect3> d_psize() <sect2> Header Files <sect1> Network <sect2> Data Structures <p> <tt/struct ifnet/ Structure <sect2> Entry Points <sect3> if_init() <sect3> if_output() <sect3> if_start() <sect3> if_done() <sect3> if_ioctl() <sect3> if_watchdog() <sect2> Header Files <sect1> Line Discipline <sect2> Data Structures <p> <tt/struct linesw/ Structure <sect2> Entry Points <sect3> l_open() <sect3> l_close() <sect3> l_read() <sect3> l_write() <sect3> l_ioctl() <sect3> l_rint() <sect3> l_start() <sect3> l_modem() <sect2> Header Files <sect> Supported Busses <sect1> ISA -- Industry Standard Architecture <sect2> Data Structures <sect3> <tt/struct isa_device/ Structure <p> This structure is required, but generally it is created by config(8) from the kernel configuration file. It is required on a per-device basis, meaning that if you have a driver which controls two serial boards, you will have two isa_device structures. If you build a device as an LKM, you must create your own isa_device structure to reflect your configuration. (lines 85 - 131 in pcaudio_lkm.c) There is nearly a direct mapping between the config file and the isa_device structure. The definition from /usr/src/sys/i386/isa/isa_device.h is: <code> struct isa_device { int id_id; /* device id */ struct isa_driver *id_driver; int id_iobase; /* base i/o address */ u_short id_irq; /* interrupt request */ short id_drq; /* DMA request */ caddr_t id_maddr; /* physical i/o memory address on bus (if any)*/ int id_msize; /* size of i/o memory */ inthand2_t *id_intr; /* interrupt interface routine */ int id_unit; /* unit number */ int id_flags; /* flags */ int id_scsiid; /* scsi id if needed */ int id_alive; /* device is present */ #define RI_FAST 1 /* fast interrupt handler */ u_int id_ri_flags; /* flags for register_intr() */ int id_reconfig; /* hot eject device support (such as PCMCIA) */ int id_enabled; /* is device enabled */ int id_conflicts; /* we're allowed to conflict with things */ struct isa_device *id_next; /* used in isa_devlist in userconfig() */ }; </code> <!-- XXX add stuff here --> <sect3> <tt/struct isa_driver/ Structure <p> This structure is defined in ``/usr/src/sys/i386/isa/isa_device.h''. These are required on a per-driver basis. The definition is: <code> struct isa_driver { int (*probe) __P((struct isa_device *idp)); /* test whether device is present */ int (*attach) __P((struct isa_device *idp)); /* setup driver for a device */ char *name; /* device name */ int sensitive_hw; /* true if other probes confuse us */ }; </code> This is the structure used by the probe/attach code to detect and initialize your device. The <tt/probe/ member is a pointer to your device probe function; the <tt/attach/ member is a pointer to your attach function. The <tt/name/ member is a character pointer to the two or three letter name for your driver. This is the name reported during the probe/attach process (and probably also in lsdev(8)). The <tt/sensitive_hw/ member is a flag which helps the probe code determine probing order. A typical instantiation is: <code> struct isa_driver mcddriver = { mcd_probe, mcd_attach, "mcd" }; </code> <sect2> Entry Points <sect3> probe() <p> probe() takes a <tt/struct isa_device/ pointer as an argument and returns an int. The return value is ``zero'' or ``non-zero'' as to the absence or presence of your device. This entry point may (and probably should) be declared as <tt/static/ because it is accessed via the <tt/probe/ member of the <tt/struct isa_driver/ structure. This function is intended to detect the presence of your device only; it should not do any configuration of the device itself. <sect3> attach() <p> attach() also takes a <tt/struct isa_device/ pointer as an argument and returns an int. The return value is also ``zero'' or ``non-zero'' indicating whether or not the attach was successful. This function is intended to do any special initialization of the device as well as confirm that the device is usable. It too should be declared <tt/static/ because it is accessed through the <tt/attach/ member of the <tt/isa_driver/ structure. <sect2> Header Files <sect1> EISA -- Extended Industry Standard Architecture <sect2> Data Structures <p> <tt/struct eisa_dev/ Structure <p> <tt/struct isa_driver/ Structure <sect2> Entry Points <sect3> probe() <p> Described in the ISA device section. <sect3> attach() <p> Described in the ISA device section. <sect2> Header Files <sect1> PCI -- Peripheral Computer Interconnect <sect2> Data Structures <p> <tt/struct pci_device/ Structure name: The short device name. probe: Checks if the driver can support a device with this type. The tag may be used to get more info with pci_read_conf(). See below. It returns a string with the device's name, or a NULL pointer, if the driver cannot support this device. attach: Allocate a control structure and prepare it. This function may use the PCI mapping functions. See below. (configuration id) or type. count: A pointer to a unit counter. It's used by the PCI configurator to allocate unit numbers. <sect2> Entry Points <sect3> probe() <sect3> attach() <sect3> shutdown() <sect2> Header Files <sect1> SCSI -- Small Computer Systems Interface <sect2> Data Structures <p> <tt/struct scsi_adapter/ Structure <p> <tt/struct scsi_device/ Structure <p> <tt/struct scsi_ctlr_config/ Structure <p> <tt/struct scsi_device_config/ Structure <p> <tt/struct scsi_link/ Structure <sect2> Entry Points <sect3> attach() <sect3> init() <sect2> Header Files <sect1> PCCARD (PCMCIA) <sect2> Data Structures <p> <tt/struct slot_cont/ Structure <p> <tt/struct pccard_drv/ Structure <p> <tt/struct pccard_dev/ Structure <p> <tt/struct slot/ Structure <sect2> Entry Points <sect3> handler() <sect3> unload() <sect3> suspend() <sect3> init() <sect2> Header Files a. <pccard/slot.h> <sect> Linking Into the Kernel. <p> In FreeBSD, support for the ISA and EISA busses is i386 specific. While FreeBSD itself is presently available on the i386 platform, some effort has been made to make the PCI, PCCARD, and SCSI code portable. The ISA and EISA specific code resides in /usr/src/sys/i386/isa and /usr/src/sys/i386/eisa respectively. The machine independent PCI, PCCARD, and SCSI code reside in /usr/src/sys/{pci,pccard,scsi}. The i386 specific code for these reside in /usr/src/sys/i386/{pci,pccard,scsi}. <p> In FreeBSD, a device driver can be either binary or source. There is no ``official'' place for binary drivers to reside. BSD/OS uses something like sys/i386/OBJ. Since most drivers are distributed in source, the following discussion refers to a source driver. Binary only drivers are sometimes provided by hardware vendors who wish to maintain the source as proprietary. <p> A typical driver has the source code in one c-file, say dev.c. The driver also can have some include files; devreg.h typically contains public device register declarations, macros, and other driver specific declarations. Some drivers call this devvar.h instead. Some drivers, such as the dgb (for the Digiboard PC/Xe), require microcode to be loaded onto the board. For the dgb driver the microcode is compiled and dumped into a header file ala file2c(1). <p> If the driver has data structures and ioctl's which are specific to the driver/device, and need to be accessible from user-space, they should be put in a separate include file which will reside in /usr/include/machine/ (some of these reside in /usr/include/sys/). These are typically named something like ioctl_dev.h or devio.h. <p> If a driver is being written which, from user space is identical to a device which already exists, care should be taken to use the same ioctl interface and data structures. For example, from -user space, a SCSI cdrom drive should be identical to an IDE cdrom +user space, a SCSI CDROM drive should be identical to an IDE cdrom drive; or a serial line on an intelligent multiport card (Digiboard, Cyclades, ...) should be identical to the sio devices. These devices have a fairly well defined interface which should be used. <p> There are two methods for linking a driver into the kernel, static and the LKM model. The first method is fairly standard across the *BSD family. The other method was originally developed by Sun (I believe), and has been implemented into BSD using the Sun model. I don't believe that the current implementation uses any Sun code. <sect1> Standard Model <p> The steps required to add your driver to the standard FreeBSD kernel are <itemize> <item> Add to the driver list <item> Add an entry to the [bc]devsw <item> Add the driver entry to the kernel config file <item> config(8), compile, and install the kernel <item> make required nodes. <item> reboot. </itemize> <sect2> Adding to the driver list. <p> The standard model for adding a device driver to the Berkeley kernel is to add your driver to the list of known devices. This list is dependant on the cpu architecture. If the device is not i386 specific (PCCARD, PCI, SCSI), the file is in ``/usr/src/sys/conf/files''. If the device is i386 specific, use ``/usr/src/sys/i386/conf/files.i386''. A typical line looks like: <tscreen><code> i386/isa/joy.c optional joy device-driver </code></tscreen> The first field is the pathname of the driver module relative to /usr/src/sys. For the case of a binary driver the path would be something like ``i386/OBJ/joy.o''. The second field tells config(8) that this is an optional driver. Some devices are required for the kernel to even be built. The third field is the name of the device. The fourth field tells config that it's a device driver (as opposed to just optional). This causes config to create entries for the device in some structures in /usr/src/sys/compile/KERNEL/ioconf.c. It is also possible to create a file ``/usr/src/sys/i386/conf/files.KERNEL'' whose contents will override the default files.i386, but only for the kernel ``KERNEL''. <sect2>Make room in conf.c <p> Now you must edit ``/usr/src/sys/i386/i386/conf.c'' to make an entry for your driver. Somewhere near the top, you need to declare your entry points. The entry for the joystick driver is: <code> #include "joy.h" #if NJOY > 0 d_open_t joyopen; d_close_t joyclose; d_rdwr_t joyread; d_ioctl_t joyioctl; #else #define joyopen nxopen #define joyclose nxclose #define joyread nxread #define joyioctl nxioctl #endif </code> This either defines your entry points, or null entry points which will return ENXIO when called (the #else clause). The include file ``joy.h'' is automatically generated by config(8) when the kernel build tree is created. This usually has only one line like: <code> #define NJOY 1 </code> or <code> #define NJOY 0 </code> which defines the number of your devices in your kernel. You must additionally add a slot to either cdevsw[&rsqb, or to bdevsw[&rsqb, depending on whether it is a character device or a block device, or both if it is a block device with a raw interface. The entry for the joystick driver is: <code> /* open, close, read, write, ioctl, stop, reset, ttys, select, mmap, strat */ struct cdevsw cdevsw[] = { ... { joyopen, joyclose, joyread, nowrite, /*51*/ joyioctl, nostop, nullreset, nodevtotty,/*joystick */ seltrue, nommap, NULL}, ... } </code> Order is what determines the major number of your device. Which is why there will always be an entry for your driver, either null entry points, or actual entry points. It is probably worth noting that this is significantly different from SCO and other system V derivatives, where any device can (in theory) have any major number. This is largely a convenience on FreeBSD, due to the way device nodes are created. More on this later. <sect2>Adding your device to the config file. <p> This is simply adding a line describing your device. The joystick description line is: <verb> device joy0 at isa? port "IO_GAME" </verb> This says we have a device called ``joy0'' on the isa bus using io-port ``IO_GAME'' (IO_GAME is a macro defined in /usr/src/sys/i386/isa/isa.h). A slightly more complicated entry is for the ``ix'' driver: <verb> device ix0 at isa? port 0x300 net irq 10 iomem 0xd0000 iosiz 32768 vector ixintr </verb> This says that we have a device called `ix0' on the ISA bus. It uses io-port 0x300. It's interrupt will be masked with other devices in the network class. It uses interrupt 10. It uses 32k of shared memory at physical address 0xd0000. It also defines it's interrupt handler to be ``ixintr()'' <sect2>config(8) the kernel. <p> Now with our config file in hand, we can create a kernel compile directory. This is done by simply typing: <verb> # config KERNEL </verb> where KERNEL is the name of your config file. Config creates a compile tree for you kernel in /usr/src/sys/compile/KERNEL. It creates the Makefile, some .c files, and some .h files with macros defining the number of each device in your kernel. Now you can go to the compile directory and build. Each time you run config, your previous build tree will be removed, unless you config with a -n. If you have config'ed and compiled a GENERIC kernel, you can ``make links'' to avoid compiling a few files on each iteration. I typically run <verb> # make depend links all </verb> followed by a ``make install'' when the kernel is done to my liking. <sect2>Making device nodes. <p> On FreeBSD, you are responsible for making your own device nodes. The major number of your device is determined by the slot number in the device switch. Minor number is driver dependent, of course. You can either run the mknod's from the command line, or add a section to /dev/MAKEDEV.local, or even /dev/MAKEDEV to do the work. I sometimes create a MAKEDEV.dev script that can be run stand-alone or pasted into /dev/MAKEDEV.local <sect2>Reboot. <p> This is the easy part. There are a number of ways to do this, reboot, fastboot, shutdown -r, cycle the power, etc. Upon bootup you should see your XXprobe() called, and if all is successful, your XXattach() too. <sect1> Loadable Kernel Module (LKM) <p> There are really no defined procedures for writing an LKM driver. The following is my own conception after experimenting with the LKM device interface and looking at the standard device driver model, this is one way of adding an LKM interface to an existing driver without touching the original driver source (or binary). It is recommended though, that if you plan to release source to your driver, the LKM specific parts should be part of the driver itself, conditionally compiled on the LKM macro (i.e. #ifdef LKM). This section will focus on writing the LKM specific part of the driver. We will assume that we have written a driver which will drop into the standard device driver model, which we would now like to implement as an LKM. We will use the pcaudio driver as a sample driver, and develop an LKM front-end. The source and makefile for the pcaudio LKM, ``pcaudio_lkm.c'' and ``Makefile'', should be placed in /usr/src/lkm/pcaudio. What follows is a breakdown of pcaudio_lkm.c. Lines 17 - 26 -- This includes the file ``pca.h'' and conditionally compiles the rest of the LKM on whether or not we have a pcaudio device defined. This mimics the behavior of config. In a standard device driver, config(8) generates the pca.h file from the number pca devices in the config file. <code> 17 /* 18 * figure out how many devices we have.. 19 */ 20 21 #include "pca.h" 22 23 /* 24 * if we have at least one ... 25 */ 26 #if NPCA > 0 </code> Lines 27 - 37 -- Includes required files from various include directories. <code> 27 #include <sys/param.h> 28 #include <sys/systm.h> 29 #include <sys/exec.h> 30 #include <sys/conf.h> 31 #include <sys/sysent.h> 32 #include <sys/lkm.h> 33 #include <sys/errno.h> 34 #include <i386/isa/isa_device.h> 35 #include <i386/isa/isa.h> 36 37 </code> Lines 38 - 51 -- Declares the device driver entry points as external. <code> 38 /* 39 * declare your entry points as externs 40 */ 41 42 extern int pcaprobe(struct isa_device *); 43 extern int pcaattach(struct isa_device *); 44 extern int pcaopen(dev_t, int, int, struct proc *); 45 extern int pcaclose(dev_t, int, int, struct proc *); 46 extern int pcawrite(dev_t, struct uio *, int); 47 extern int pcaioctl(dev_t, int, caddr_t); 48 extern int pcaselect(dev_t, int, struct proc *); 49 extern void pcaintr(struct clockframe *); 50 extern struct isa_driver pcadriver; 51 </code> Lines 52 - 70 -- This is creates the device switch entry table for your driver. This table gets swapped wholesale into the system device switch at the location specified by your major number. In the standard model, these are in /usr/src/sys/i386/i386/conf.c. NOTE: you cannot pick a device major number higher than what exists in conf.c, for example at present, conf.c rev 1.85, there are 67 slots for character devices, you cannot use a (character) major device number 67 or greater, without first reserving space in conf.c. <code> 52 /* 53 * build your device switch entry table 54 */ 55 56 static struct cdevsw pcacdevsw = { 57 (d_open_t *) pcaopen, /* open */ 58 (d_close_t *) pcaclose, /* close */ 59 (d_rdwr_t *) enodev, /* read */ 60 (d_rdwr_t *) pcawrite, /* write */ 61 (d_ioctl_t *) pcaioctl, /* ioctl */ 62 (d_stop_t *) enodev, /* stop?? */ 63 (d_reset_t *) enodev, /* reset */ 64 (d_ttycv_t *) enodev, /* ttys */ 65 (d_select_t *) pcaselect, /* select */ 66 (d_mmap_t *) enodev, /* mmap */ 67 (d_strategy_t *) enodev /* strategy */ 68 }; 69 70 </code> Lines 71 - 131 -- This section is analogous to the config file declaration of your device. The members of the isa_device structure are filled in by what is known about your device, I/O port, shared memory segment, etc. We will probably never have a need for two pcaudio devices in the kernel, but this example shows how multiple devices can be supported. <code> 71 /* 72 * this lkm arbitrarily supports two 73 * instantiations of the pc-audio device. 74 * 75 * this is for illustration purposes 76 * only, it doesn't make much sense 77 * to have two of these beasts... 78 */ 79 80 81 /* 82 * these have a direct correlation to the 83 * config file entries... 84 */ 85 struct isa_device pcadev[NPCA] = { 86 { 87 11, /* device id */ 88 &pcadriver, /* driver pointer */ 89 IO_TIMER1, /* base io address */ 90 -1, /* interrupt */ 91 -1, /* dma channel */ 92 (caddr_t)-1, /* physical io memory */ 93 0, /* size of io memory */ 94 pcaintr , /* interrupt interface */ 95 0, /* unit number */ 96 0, /* flags */ 97 0, /* scsi id */ 98 0, /* is alive */ 99 0, /* flags for register_intr */ 100 0, /* hot eject device support */ 101 1 /* is device enabled */ 102 }, 103 #if NPCA >1 104 { 105 106 /* 107 * these are all zeros, because it doesn't make 108 * much sense to be here 109 * but it may make sense for your device 110 */ 111 112 0, /* device id */ 113 &pcadriver, /* driver pointer */ 114 0, /* base io address */ 115 -1, /* interrupt */ 116 -1, /* dma channel */ 117 -1, /* physical io memory */ 118 0, /* size of io memory */ 119 NULL, /* interrupt interface */ 120 1, /* unit number */ 121 0, /* flags */ 122 0, /* scsi id */ 123 0, /* is alive */ 124 0, /* flags for register_intr */ 125 0, /* hot eject device support */ 126 1 /* is device enabled */ 127 }, 128 #endif 129 130 }; 131 </code> Lines 132 - 139 -- This calls the C-preprocessor macro MOD_DEV, which sets up an LKM device driver, as opposed to an LKM filesystem, or an LKM system call. <code> 132 /* 133 * this macro maps to a funtion which 134 * sets the LKM up for a driver 135 * as opposed to a filesystem, systemcall, or misc 136 * LKM. 137 */ 138 MOD_DEV("pcaudio_mod", LM_DT_CHAR, 24, &pcacdevsw); 139 </code> Lines 140 - 168 -- This is the function which will be called when the driver is loaded. This function tries to work like sys/i386/isa/isa.c which does the probe/attach calls for a driver at boot time. The biggest trick here is that it maps the physical address of the shared memory segment, which is specified in the isa_device structure to a kernel virtual address. Normally the physical address is put in the config file which builds the isa_device structures in /usr/src/sys/compile/KERNEL/ioconf.c. The probe/attach sequence of /usr/src/sys/isa/isa.c translates the physical address to a virtual one so that in your probe/attach routines you can do things like <verb> (int *)id->id_maddr = something; </verb> and just refer to the shared memory segment via pointers. <code> 140 /* 141 * this function is called when the module is 142 * loaded; it tries to mimic the behavior 143 * of the standard probe/attach stuff from 144 * isa.c 145 */ 146 int 147 pcaload(){ 148 int i; 149 uprintf("PC Audio Driver Loaded\n"); 150 for (i=0; i<NPCA; i++){ 151 /* 152 * this maps the shared memory address 153 * from physical to virtual, to be 154 * consistant with the way 155 * /usr/src/sys/i386/isa.c handles it. 156 */ 157 pcadev[i].id_maddr -=0xa0000; 158 pcadev[i].id_maddr += atdevbase; 159 if ((*pcadriver.probe)(pcadev+i)) { 160 (*(pcadriver.attach))(pcadev+i); 161 } else { 162 uprintf("PC Audio Probe Failed\n"); 163 return(1); 164 } 165 } 166 return 0; 167 } 168 </code> Lines 169 - 179 -- This is the function called when your driver is unloaded; it just displays a message to that effect. <code> 169 /* 170 * this function is called 171 * when the module is unloaded 172 */ 173 174 int 175 pcaunload(){ 176 uprintf("PC Audio Driver Unloaded\n"); 177 return 0; 178 } 179 </code> Lines 180 - 190 -- This is the entry point which is specified on the command line of the modload. By convention it is named <dev>_mod. This is how it is defined in bsd.lkm.mk, the makefile which builds the LKM. If you name your module following this convention, you can do ``make load'' and ``make unload'' from /usr/src/lkm/pcaudio. <p> Note: this has gone through <em/many/ revisions from release 2.0 to 2.1. It may or may not be possible to write a module which is portable across all three releases. <p> <code> 180 /* 181 * this is the entry point specified 182 * on the modload command line 183 */ 184 185 int 186 pcaudio_mod(struct lkm_table *lkmtp, int cmd, int ver) 187 { 188 DISPATCH(lkmtp, cmd, ver, pcaload, pcaunload, nosys); 189 } 190 191 #endif /* NICP > 0 */ </code> <sect1> Device Type Idiosyncrasies <sect2> Character <sect2> Block <sect2> Network <sect2> Line Discipline <sect1> Bus Type Idiosyncrasies <sect2> ISA <sect2> EISA <sect2> PCI <sect2> SCSI <sect2> PCCARD <sect> Kernel Support <sect1> Data Structures <sect2> <tt/struct kern_devconf/ Structure <p> This structure contains some information about the state of the device and driver. It is defined in /usr/src/sys/sys/devconf.h as: <code> struct devconf { char dc_name[MAXDEVNAME]; /* name */ char dc_descr[MAXDEVDESCR]; /* description */ int dc_unit; /* unit number */ int dc_number; /* unique id */ char dc_pname[MAXDEVNAME]; /* name of the parent device */ int dc_punit; /* unit number of the parent */ int dc_pnumber; /* unique id of the parent */ struct machdep_devconf dc_md; /* machine-dependent stuff */ enum dc_state dc_state; /* state of the device (see above) */ enum dc_class dc_class; /* type of device (see above) */ size_t dc_datalen; /* length of data */ char dc_data[1]; /* variable-length data */ }; </code> <sect2> <tt/struct proc/ Structure <p> This structure contains all the information about a process. It is defined in /usr/src/sys/sys/proc.h: <code> /* * Description of a process. * * This structure contains the information needed to manage a thread of * control, known in UN*X as a process; it has references to substructures * containing descriptions of things that the process uses, but may share * with related processes. The process structure and the substructures * are always addressable except for those marked "(PROC ONLY)" below, * which might be addressable only on a processor on which the process * is running. */ struct proc { struct proc *p_forw; /* Doubly-linked run/sleep queue. */ struct proc *p_back; struct proc *p_next; /* Linked list of active procs */ struct proc **p_prev; /* and zombies. */ /* substructures: */ struct pcred *p_cred; /* Process owner's identity. */ struct filedesc *p_fd; /* Ptr to open files structure. */ struct pstats *p_stats; /* Accounting/statistics (PROC ONLY). */ struct plimit *p_limit; /* Process limits. */ struct vmspace *p_vmspace; /* Address space. */ struct sigacts *p_sigacts; /* Signal actions, state (PROC ONLY). */ #define p_ucred p_cred->pc_ucred #define p_rlimit p_limit->pl_rlimit int p_flag; /* P_* flags. */ char p_stat; /* S* process status. */ char p_pad1[3]; pid_t p_pid; /* Process identifier. */ struct proc *p_hash; /* Hashed based on p_pid for kill+exit+... */ struct proc *p_pgrpnxt; /* Pointer to next process in process group. */ struct proc *p_pptr; /* Pointer to process structure of parent. */ struct proc *p_osptr; /* Pointer to older sibling processes. */ /* The following fields are all zeroed upon creation in fork. */ #define p_startzero p_ysptr struct proc *p_ysptr; /* Pointer to younger siblings. */ struct proc *p_cptr; /* Pointer to youngest living child. */ pid_t p_oppid; /* Save parent pid during ptrace. XXX */ int p_dupfd; /* Sideways return value from fdopen. XXX */ /* scheduling */ u_int p_estcpu; /* Time averaged value of p_cpticks. */ int p_cpticks; /* Ticks of cpu time. */ fixpt_t p_pctcpu; /* %cpu for this process during p_swtime */ void *p_wchan; /* Sleep address. */ char *p_wmesg; /* Reason for sleep. */ u_int p_swtime; /* Time swapped in or out. */ u_int p_slptime; /* Time since last blocked. */ struct itimerval p_realtimer; /* Alarm timer. */ struct timeval p_rtime; /* Real time. */ u_quad_t p_uticks; /* Statclock hits in user mode. */ u_quad_t p_sticks; /* Statclock hits in system mode. */ u_quad_t p_iticks; /* Statclock hits processing intr. */ int p_traceflag; /* Kernel trace points. */ struct vnode *p_tracep; /* Trace to vnode. */ int p_siglist; /* Signals arrived but not delivered. */ struct vnode *p_textvp; /* Vnode of executable. */ char p_lock; /* Process lock (prevent swap) count. */ char p_pad2[3]; /* alignment */ /* End area that is zeroed on creation. */ #define p_endzero p_startcopy /* The following fields are all copied upon creation in fork. */ #define p_startcopy p_sigmask sigset_t p_sigmask; /* Current signal mask. */ sigset_t p_sigignore; /* Signals being ignored. */ sigset_t p_sigcatch; /* Signals being caught by user. */ u_char p_priority; /* Process priority. */ u_char p_usrpri; /* User-priority based on p_cpu and p_nice. */ char p_nice; /* Process "nice" value. */ char p_comm[MAXCOMLEN+1]; struct pgrp *p_pgrp; /* Pointer to process group. */ struct sysentvec *p_sysent; /* System call dispatch information. */ struct rtprio p_rtprio; /* Realtime priority. */ /* End area that is copied on creation. */ #define p_endcopy p_addr struct user *p_addr; /* Kernel virtual addr of u-area (PROC ONLY). */ struct mdproc p_md; /* Any machine-dependent fields. */ u_short p_xstat; /* Exit status for wait; also stop signal. */ u_short p_acflag; /* Accounting flags. */ struct rusage *p_ru; /* Exit information. XXX */ }; </code> <sect2> <tt/struct buf/ Structure <p> The <tt/struct buf/ structure is used to interface with the buffer cache. It is defined in /usr/src/sys/sys/buf.h: <code> /* * The buffer header describes an I/O operation in the kernel. */ struct buf { LIST_ENTRY(buf) b_hash; /* Hash chain. */ LIST_ENTRY(buf) b_vnbufs; /* Buffer's associated vnode. */ TAILQ_ENTRY(buf) b_freelist; /* Free list position if not active. */ struct buf *b_actf, **b_actb; /* Device driver queue when active. */ struct proc *b_proc; /* Associated proc; NULL if kernel. */ volatile long b_flags; /* B_* flags. */ int b_qindex; /* buffer queue index */ int b_error; /* Errno value. */ long b_bufsize; /* Allocated buffer size. */ long b_bcount; /* Valid bytes in buffer. */ long b_resid; /* Remaining I/O. */ dev_t b_dev; /* Device associated with buffer. */ struct { caddr_t b_addr; /* Memory, superblocks, indirect etc. */ } b_un; void *b_saveaddr; /* Original b_addr for physio. */ daddr_t b_lblkno; /* Logical block number. */ daddr_t b_blkno; /* Underlying physical block number. */ /* Function to call upon completion. */ void (*b_iodone) __P((struct buf *)); /* For nested b_iodone's. */ struct iodone_chain *b_iodone_chain; struct vnode *b_vp; /* Device vnode. */ int b_pfcent; /* Center page when swapping cluster. */ int b_dirtyoff; /* Offset in buffer of dirty region. */ int b_dirtyend; /* Offset of end of dirty region. */ struct ucred *b_rcred; /* Read credentials reference. */ struct ucred *b_wcred; /* Write credentials reference. */ int b_validoff; /* Offset in buffer of valid region. */ int b_validend; /* Offset of end of valid region. */ daddr_t b_pblkno; /* physical block number */ caddr_t b_savekva; /* saved kva for transfer while bouncing */ void *b_driver1; /* for private use by the driver */ void *b_driver2; /* for private use by the driver */ void *b_spc; struct vm_page *b_pages[(MAXPHYS + PAGE_SIZE - 1)/PAGE_SIZE]; int b_npages; }; </code> <sect2> <tt/struct uio/ Structure <p> This structure is used for moving data between the kernel and user spaces through read() and write() system calls. It is defined in /usr/src/sys/sys/uio.h: <code> struct uio { struct iovec *uio_iov; int uio_iovcnt; off_t uio_offset; int uio_resid; enum uio_seg uio_segflg; enum uio_rw uio_rw; struct proc *uio_procp; }; </code> <sect1> Functions lots of 'em <sect> References. <p> FreeBSD Kernel Sources http://www.freebsd.org <p> NetBSD Kernel Sources http://www.netbsd.org <p> Writing Device Drivers: Tutorial and Reference; Tim Burke, Mark A. Parenti, Al, Wojtas; Digital Press, ISBN 1-55558-141-2. <p> Writing A Unix Device Driver; Janet I. Egan, Thomas J. Teixeira; John Wiley & Sons, ISBN 0-471-62859-X. <p> Writing Device Drivers for SCO Unix; Peter Kettle; </article> diff --git a/en/tutorials/devel/devel.sgml b/en/tutorials/devel/devel.sgml index e9d8fbf560..0fde023afd 100644 --- a/en/tutorials/devel/devel.sgml +++ b/en/tutorials/devel/devel.sgml @@ -1,1738 +1,1739 @@ <!DOCTYPE linuxdoc PUBLIC "-//FreeBSD//DTD linuxdoc//EN"> +<!-- $Id: devel.sgml,v 1.2 1996-10-06 20:17:10 jfieber Exp $ --> <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++ ++ file: /home/james/docs/devel.sgml ++ ++ Copyright James Raynard, Thursday 30th May 1996 ++ ++ Sgml doc for programming under FreeBSD. --> <article> <title>A User's Guide to FreeBSD Programming Tools <author>James Raynard, <tt /jraynard@freebsd.org/ <date>30th May 1996 <abstract> 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 <it /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 </abstract> <sect><heading>Introduction</heading> <p> 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 isn't 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. <p> 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. <p> 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! <sect><heading>Introduction to Programming</heading> <p> A program is a set of instructions that tell the computer to do various things; sometimes the instruction it has to perform depends on what happened when it performed a previous instruction. This section gives an overview of the two main ways in which you can give these instructions, or ``commands'' as they're usually called. One way uses an interpreter, the other a compiler. As human languages are too difficult for a computer to understand in an unambiguous way, commands are usually written in one or other languages specially designed for the purpose. <sect1><heading>Interpreters</heading> <p> 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. <P> 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. <p> In my opinion, interpreted languages are the best way to start if you haven't 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. <p> <sect1><heading>Interpreters available with FreeBSD</heading> <p> Here is a list of interpreters that are available as <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/" name="FreeBSD packages">, with a brief discussion of some of the more popular interpreted languages. <p> To get one of these packages, all you need to do is to click on the hotlink for the package, then run <tscreen><verb> pkg_add <package name> </verb></tscreen> as root. Obviously, you'll need to have a fully-functional FreeBSD 2.1.0 system for the package to work! <descrip> <tag>Basic</tag> 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 <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/lang/bwbasic-2.10.tgz" name="Bywater Basic Interpreter"> and the <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/lang/pbasic-2.0.tgz" name="Phil Cockroft's Basic Interpreter"> (formerly Rabbit Basic) are available as FreeBSD <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/" name="FreeBSD packages"> <tag>Lisp</tag> 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 <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/gcl-2.0.tgz" name="GNU Common Lisp"> available as a package. <tag>Perl</tag> Very popular with system administrators for writing scripts; also often used on World Wide Web servers for writing CGI scripts. Version 4, which is probably still the most widely-used version, comes with FreeBSD; the newer <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/lang/perl-5.001.tgz" name="Perl Version 5"> is available as a package. <tag>Scheme</tag> A dialect of Lisp that is rather more compact and cleaner than Common Lisp. Popular in Universities as it's 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 <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/lang/elk-3.0.tgz" name="Elk Scheme Interpreter">, the <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/lang/mit-scheme-7.3.tgz" name="MIT Scheme Interpreter"> and the <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/lang/scm-4e1.tgz" name="SCM Scheme Interpreter">. <!-- <tag>TCL and Tk</tag> Programming with the X windowing system can best be described as rather character-forming. As someone once said, if they designed cars the way X was designed, each car would have five steering wheels, all following completely different conventions, but you can use the radio-cassette player to change gears, which is a really useful feature when you think about it. Or perhaps not. <p> Fortunately, it doesn't have to be like that. A number of people have written "toolkits" for X, where all the interaction with X is hidden inside toolkit routines and you can just say, in effect, ``pop up a window and draw a line from point A to point B''. Many of these are `libraries' that have to be called from inside a C program, but one of the best known toolkits, John Ousterhout's Tk, provides a straightforward way to write GUI programs using a scripted language. And by one of those remarkable coincidences, he also happens to have written an embeddable language, TCL (Tool Command Language) which is very suitable for the purpose, although it is possible to use other interpreted languages such as Perl or Scheme to send commands to Tk. FreeBSD has a <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/lang/tcl-7.4.2.tgz" name="Tool Command Language"> package. --> <tag>Icon</tag> <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/lang/icon-9.0.tgz" name="The Icon Programming Language">. <tag>Logo</tag> <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/lang/ucblogo-3.3.tgz" name="Brian Harvey's LOGO Interpreter">. <tag>Python</tag> <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/lang/python-1.2" name="The Python Object-Oriented Programming Language"> </descrip> <sect1><heading>Compilers</heading> <p> 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 didn't 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. (If you run it in the shell, you may get a core dump). <p> 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 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 wouldn't 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). <p> 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. <p> 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 doesn't have an IDE as such; however it's possible to use Emacs for this purpose. This is discussed under Emacs. <sect><heading>Compiling with cc</heading> <p> This section deals only with the GNU compiler for C and C++, since that comes with the base FreeBSD system. It can be invoked by either `cc' or `gcc'. The details of producing a program with an interpreter vary considerably between interpreters, and are usually well covered in the documentation and on-line help for the interpreter. <p> Once you've written your masterpiece, the next step is to convert it into something that will (hopefully!) run on FreeBSD. This usually involves several steps, each of which is done by a separate program. <enum> <item> Pre-process your source code to remove comments and do other tricks like expanding `macros' in C. <item> Check the syntax of your code to see if you have obeyed the rules of the language. If you haven't, it will complain! <item> Convert the source code into assembler - this is very close to machine code, but still understandable by humans. Allegedly. (To be strictly accurate, cc converts the source code into its own, machine-independent p-code instead of assembler at this stage). <item> Convert the assembler into machine code - yep, we're talking bits and bytes, ones and zeros here. <item> Check that you've used things like functions and global variables in a consistent way (eg if you've called a non-existent function, it'll complain). <item> If you're trying to produce an executable from several source code files, work out how to fit them all together. <item> Work out how to produce something that the system's run-time loader will be able to load into memory and run. <item> (Finally!) Write the executable on the file system. </enum> 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''. <p> 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 <tscreen><verb> cc foobar.c </verb></tscreen> 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 <tscreen><verb> cc foo.c bar.c </verb></tscreen> Note that the syntax checking is just that - checking the syntax. It won't check for any logical mistakes you may have made, like putting the program into an infinite loop, or using a bubble sort when you meant to use a binary sort. {In case you didn't know, a binary sort is an efficient way of sorting things into order and a bubble sort isn't.} <p> 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. <descrip> <tag/-o/ The output name of the file. If you don't use this option, cc will produce an executable called `a.out' (the reasons for this are buried in the mists of history). Example:- <tscreen><verb> cc foobar.c executable is a.out cc -o foobar foobar.c executable is foobar </verb></tscreen> <tag/-c/ Just compile the file, don't link it. Useful for toy programs where you just want to check the syntax, or if you're using a Make file. Example:- <tscreen><verb> cc -c foobar.c </verb></tscreen> This will produce an ``object file'' (not an executable) called `foobar.o'. This can be linked together with other object files into an executable. <tag/-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 <it /very/ useful; the disadvantage is that all this extra information makes the program much bigger. Normally, you compile with -g while you're developing a program and then compile a ``release version'' without -g when you're satisfied it works properly. Example:- <tscreen><verb> cc -g foobar.c </verb></tscreen> This will produce a debug version of the program. (Note, we didn't use the -o flag to specify the executable name, so we'll get an executable called `a.out'. Producing a debug version called `foobar' is left as an exercise for the reader!) <tag/-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. Example:- <tscreen><verb> cc -O -o foobar foobar.c </verb></tscreen> This will produce an optimised version of `foobar'. <p> 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's an ISO standard). <tag/-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. <tag/-ansi/ Turn off most (but not all) of the non-standard features provided by cc. Despite the name, it does not guarantee strictly that your code will comply to the standard. <tag/-pedantic/ Turn off <it /all/ cc's non-standard features. <p> 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''). <p> 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? Example:- <tscreen><verb> cc -Wall -ansi -pedantic -o foobar foobar.c </verb></tscreen> will produce an executable `foobar' after checking foobar.c for standard compliance. <tag/-l/ Specify a library to be used during when linking. <p> 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. <p> The rule is that if the library is called `libsomething.a', you give cc the argument `-lsomething'. For example, the maths library is `libm.a', so you give cc the argument `-lm'. A common ``gotcha'' with the maths library is that it has to be the last library on the command line. <p> Example:- <tscreen><verb> cc -o foobar foobar.c -lm </verb></tscreen> will link the maths library functions into `foobar'. <p> If you're compiling C++ code, you need to add `-lg++' to the command line argument, to link the C++ library functions. Alternatively, you can run c++ instead of cc, which does this for you. <p> Example:- <tscreen><verb> cc -o foobar foobar.cc -lg++ c++ -o foobar foobar.cc </verb></tscreen> 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 DOS-style `.cpp' (which was 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! {c++ can also be invoked as g++ on FreeBSD.} </descrip> <sect1><heading>Common cc Queries and Problems</heading> <p> Q. I'm trying to write a program which uses the sin() function and I get an error like this. What does it mean? <tscreen><verb> /var/tmp/cc0143941.o: Undefined symbol `_sin' referenced from text segment </verb></tscreen> A. When using mathematical functions like sin(), you have to tell cc to link in the maths library, like so:- <tscreen><verb> cc -o foobar foobar.c -lm </verb></tscreen> Q. All right, I wrote this simple program to practice using -lm. All it does is raise 2.1 to the power of 6. <code> #include <stdio.h> int main() { float f; f = pow(2.1, 6); printf("2.1 ^ 6 = %f\n", f); return 0; } </code> and I compiled it as <tscreen><verb> gcc temp.c -lm </verb></tscreen> like you said I should, but I get this when I run it:- <tscreen><verb> $ ./a.out 2.1 ^ 6 = 1023.000000 </verb></tscreen> This is <it /not/ the right answer! What the %$&#'s going on? <p> A. When the compiler sees you call a function, it checks if it's already seen a prototype for it. If it hasn't, it assumes the function returns an int, which is definitely not what you want here. <p> Q. So how do I fix this? <p> A. The prototypes for the mathematical functions are in math.h. If you include this file, the compiler will be able to find the prototype and it'll stop doing strange things to your calculation! <code> #include <math.h> #include <stdio.h> int main() { ... </code> <p> <tscreen><verb> $ ./a.out 2.1 ^ 6 = 85.766121 </verb></tscreen> Morale: if you're using any of the mathematical functions, always include math.h and remember to link in the maths library. Q. I've compiled a file called `foobar.c' and I can't find an executable called `foobar'. Where's it gone? <p> A. cc will call the executable `a.out' unless you tell it differently. Use the -o option, eg <tscreen><verb> cc -o foobar foobar.c </verb></tscreen> Q. OK, I've got an executable called `foobar', I can see it when I do `ls', but when I type in 'foobar' at the command prompt it tells me there's no such file. Why can't it find it? <p> A. Unlike DOS, Unix won't look in the current directory when it's 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 <tscreen><verb> bin:/usr/bin:/usr/local/bin:. </verb></tscreen> (The dot at the end means ``look in the current directory if it's not in any of the others'') <p> Q. I called my executable `test', but nothing happens when I run it. What's going on? <p> A. Most Unix systems have a program called `test' in /usr/bin and the shell's picking that one up before it gets to checking the current directory. Either type <tscreen><verb> ./test </verb></tscreen> or choose a better name for your program! <p> Q. 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? <p> A. 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. <p> Q. Fascinating stuff, but what I am supposed to do now? <p> A. Use gdb to analyse the core (see Debugging). <p> Q. When my program dumped core, it said something about a segmentation fault. What's that? <p> A. 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. <p> Common causes for this are:- <itemize> <item> Trying to write to a NULL pointer, eg <code> char *foo = NULL; strcpy(foo, "bang!"); </code> <item> Using a pointer that hasn't been initialised, eg <code> char *foo; strcpy(foo, "bang!"); </code> 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. <p> <item> Trying to access past the end of an array, eg <code> int bar[20]; bar[27] = 6; </code> <item> Trying to store something in read-only memory, eg <code> char *foo = "My string"; strcpy(foo, "bang!"); </code> (Unix compilers often put string literals like ``My string'' into read-only areas of memory). <item> Doing naughty things with malloc() and free(), eg <code> char bar[80]; free(bar); </code> or <code> char *foo = malloc(27); free(foo); free(foo); </code> </itemize> (Note 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) <p> Q. 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? <p> A. 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. <p> Q. 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? <p> A. Yes, just go to another console or xterm, do <tscreen><verb> ps </verb></tscreen> to find out the process ID of your program, and do <tscreen><verb> kill -ABRT <pid> </verb></tscreen> This is useful if your program has got stuck in an infinite loop, for instance. (If your program traps SIGABRT, there are several other signals which have a similar effect). <sect><heading>Make</heading> <p> <sect1><heading>What is make?</heading> <p> When you're working on a simple program with only one or two source files, typing in <tscreen><verb> cc file1.c file2.c </verb></tscreen> is not too bad, but it quickly becomes very tedious when there are several files - and it can take a while to compile, too. <p> 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:- <tscreen><verb> cc file1.o file2.o ... file37.c ... </verb></tscreen> if we'd changed file37.c, but not any of the others, since the last time we compiled. <p> This may speed up the compilation quite a bit, but doesn't solve the typing problem. <p> 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. <p> 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? <p> 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. <p> This program is called <tt /make/. It reads in a file, called a make file, 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 make file also has rules telling make <it /how/ to re-compile the source file, making it a much more powerful tool. <p> Make files 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 (they don't use the `MAKEFILE' form as block capitals are often used for documentation files like `README'). <sect1><heading>Example of using make</heading> <p> Here's a very simple make file:- <tscreen><verb> foo: foo.c cc -o foo foo.c </verb></tscreen> It consists of two lines, a dependency line and a creation line. <p> The dependency line here consists of the name of the program (known as ``the target''), followed by a colon, then a gap, then the name of the source file. When make reads this line, it looks to see if `foo' exists; if it exists, it compares the time 'foo' was last modified to the time `foo.c' was last modified. If 'foo' does not exist, or is older than `foo.c', it then looks at the creation line to find out what to do. In other words, this is the rule for working out when foo.c needs to be re-compiled. <p> 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. <p> 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! <p> Another useful property of make files is that the targets don't have to be programs. For instance, we could have a make file that looks like this:- <tscreen><verb> foo: foo.c cc -o foo foo.c install: cp foo /home/me </verb></tscreen> We can tell make which target we want to make by typing <tscreen><verb> make <target> </verb></tscreen> make will then only look at that target and ignore any others. For example, if we type `make foo' with the make file above, make will ignore the 'install' target. <p> 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. <p> 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 make files, so that the application can be installed in the correct directory when it has been correctly compiled. <p> 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). <sect1><heading>FreeBSD Make Files</heading> <p> Make files can be rather complicated to write. Fortunately, BSD-based systems like FreeBSD come with some very powerful ones as part of the system. <p> One very good example of this is the FreeBSD ports system. Here's the essential part of a typical ports Makefile:- <code> MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/ DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz .include <bsd.port.mk> </code> Now, if we go to the directory for this port and type make, the following happens:- <enum> <item> A check is made to see if the source code for this port is already on the system. <item> If it isn't, an FTP connection to the URL in ``MASTER_SITES'' is set up to download the source. <item> 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. <item> Any changes required to make the source work on FreeBSD are applied - this is known as ``patching''. <item> 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). <item> 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. <item> 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. </enum> Now I think you'll agree that's rather impressive for a four line script! <p> The secret lies in the last line, which tells make to look in the system make file 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 make file that tells make to do all the things above (plus a couple of other things I didn't mention, not to mention handling any errors that may occur) and anyone can get access to that just by putting a single line in their own make file! <p> If you want to have a look at these system make files, they're in /usr/share/mk, but it's probably best to wait until you've had a bit of practice with make files, as they are very complicated (and if you do look at them, make sure you have a flask of strong coffee handy!) <sect1><heading>More advanced uses of make</heading> <p> Make is a very powerful tool, and can do much more than the simple example above shows. Unfortunately, there are several different versions of make, and they all differ considerably. The best way to learn what they can do is probably to read the documentation - hopefully this introduction will have given you a base from which you can do this. <p> The version of make that comes with FreeBSD is the Berkeley make; there is a tutorial for it in /usr/share/doc/psd/12.make. To view it, do <tscreen><verb> zmore paper.ascii.gz </verb></tscreen> in that directory. <p> 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 it's own right. <p> 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 <tscreen><verb> * Make: (make). The GNU Make utility. </verb></tscreen> 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). <sect><heading>Debugging</heading> <p> <sect1><heading>The Debugger</heading> <p> The debugger that comes with FreeBSD is called `gdb' (GNU debugger). You start it up by typing <tscreen><verb> gdb <progname> </verb></tscreen> although most people prefer to run it inside Emacs. You can do this by <tscreen><verb> M-x gdb RET <progname> RET. </verb></tscreen> 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. <p> 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. <p> 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. <p> Finally, if you find its text-based command-prompt style off-putting, there's a graphical front-end for it <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/ports/devel/xxgdb.tgz" name="xxgdb"> in the ports. <p> This section is intended to be an introduction to using gdb and does not cover specialised topics such as debugging the kernel. <sect1><heading>Running a program in the debugger</heading> <p> You'll need to have compiled the program with the `-g' option to get the most out of using gdb. It will work without, but you'll only see the name of the function you're in, instead of the source code. If you see a line like <tscreen><verb> ...(no debugging symbols found)... </verb></tscreen> when gdb starts up, you'll know that the program wasn't compiled with the `-g' option. <p> 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!). <p> 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. <p> Here's a simple example of how to spot a mistake in a program with gdb. This is our program (with a deliberate mistake):- <code> #include <stdio.h> int bazz(int anint); main() { int i; printf("This is my program\n"); bazz(i); return 0; } int bazz(int anint) { printf("You gave me %d\n", anint); return anint; } </code> This program sets i to be 5 and passes it to a function bazz() which prints out the number we gave it. <p> When we compile and run the program we get <tscreen><verb> cc -g -o temp temp.c ./temp This is my program anint = 4231 </verb></tscreen> That wasn't what we expected! Time to see what's going on! <tscreen><verb> Current directory is ~/tmp/ 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 Breakpoint 1 at 0x160f: file temp.c, line 9. # gdb puts breakpoint at main() (gdb) run # Run as far as main() Starting program: /home/james/tmp/temp # Program starts running Breakpoint 1, main () at temp.c:9 # gdb stops at main() (gdb) n # Go to next line This is my program # Program prints out "This .." (gdb) s # step into bazz() bazz (anint=4231) at temp.c:17 # gdb displays stack frame </verb></tscreen> 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. <tscreen><verb> (gdb) up # Move up call stack #1 0x1625 in main () at temp.c:11 # gdb displays stack frame (gdb) p i # Show us the value of i $1 = 4231 # gdb displays 4231 </verb></tscreen> Oh dear! Looking at the code, we forgot to initialise i. We meant to put <code> ... main() { int i; i = 5; printf("This is my program\n"); ... </code> but we missed 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. <p> Note that 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). <sect1><heading>Examining a core file</heading> <p> A core file is basically a file which contains the complete state of the process when it crashed. In ``the good old days'', programmers had to print out hex listings of core files and sweat over machine code manuals, but now life is a 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. <p> To examine a core file, start up gdb in the usual way. Instead of typing `break' or `run', type <tscreen><verb> core progname.core </verb></tscreen> (if you're not in the same directory as the core file, you'll have to do `dir /path/to/core/file' first). <p> You should see something like this:- <tscreen><verb> Current directory is ~/tmp/ 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 foobar (some_arg=0x5) at temp.c:17 </verb></tscreen> 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'. <p> 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:- <tscreen><verb> (gdb) bt #0 0x164a in bazz (anint=0x5) at temp.c:17 #1 0xefbfd888 in end () #2 0x162c in main () at temp.c:11 </verb></tscreen> The end() function is called when a program crashes; in this case, the bazz() function was called from main(). <sect1><heading>Attaching to a running program</heading> <p> One of the neatest features about gdb is that it can attach to a program that's already running. (Of course, that assumes you have sufficient permissions to do so). A common problem is when you are stepping through a program that forks, and you want to trace the child, but the debugger will only let you trace the parent. <p> What you do is start up another gdb, use `ps' to find the process ID for the child, and do <tscreen><verb> attach <pid> </verb></tscreen> in gdb, and then debug as usual. <p> ``That's all very well,'' you're probably thinking, ``but by the time I've done that, the child process will be over the hill and far away''. Fear not, gentle reader, here's how to do it (courtesy of the gdb info pages):- <tscreen><verb> ... 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 */ ... </verb></tscreen> Now all you have to do is attach to the child, set PauseMode to 0, and wait for the sleep() call to return! <sect><heading>Using Emacs as a Development Environment</heading> <p> <sect1><heading>Emacs</heading> <p> 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 (at least, not unless you pay out very large sums of money). 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. <p> 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. <p> 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). <p> It's impossible even to summarise everything Emacs can do here, but here are some of the features of interest to developers:- <itemize> <item> Very powerful editor, allowing search-and-replace on both strings and regular expressions (patterns), jumping to start/end of block expression, etc, etc. <item> Pull-down menus and online help. <item> Language-dependent syntax highlighting and indentation. <item> Completely customisable. <item> You can compile and debug programs within Emacs. <item> On a compilation error, you can jump to the offending line of source code. <item> Friendly-ish front-end to the `info' program used for reading GNU hypertext documentation (including the documentation on Emacs). <item> Friendly front-end to GDB, allowing you to look at the source code as you step through your program. <item> You can read Usenet news and mail while your program is compiling ;-) </itemize> And doubtless many more that I've overlooked. <p> Emacs can be installed on FreeBSD using <htmlurl url="ftp://ftp.freebsd.org:pub/FreeBSD/packages/editors/emacs" name="the Emacs package">. <p> 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). <p> 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 <tscreen><verb> M-x replace-s RET foo RET bar RET </verb></tscreen> 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. <p> 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). <p> 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. <p> 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. <p> 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). <p> Oh, and to get out of Emacs, do C-c C-x (that means hold down the control key, press `c', press `x' 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). <sect1><heading>Configuring Emacs</heading> <p> Emacs does many wonderful things, some of them are built in, some of them need to be configured. <p> Instead of using a proprietary macro language for configuration, Emacs uses a version of Lisp specially adapted for editors, known as Emacs Lisp. This can be quite useful if you want to go on and learn something like Common Lisp, as it's considerably smaller than Common Lisp (although still quite big!). <p> The best way to learn Emacs Lisp is to download the <htmlurl url="ftp://prep.ai.mit.edu:pub/gnu/elisp-manual-19-2.4.tar.gz" name="Emacs Tutorial"> <p> However, there's no need to actually know any Lisp to get started with configuring Emacs, as I've included a sample ``.emacs'' file, which should be enough to get you started. Just copy it into your home directory and restart Emacs if it's already running; it will read the commands from the file and (hopefully) give you a useful basic setup. <sect1><heading>A sample .emacs file</heading> <p> Unfortunately, there's far too much here to explain it in detail; however there are one or two points worth mentioning. <itemize> <item> Everything beginning with a `;' is a comment and is ignored by Emacs. <item> In the first line, the -*- Emacs-Lisp -*- is so that we can edit the .emacs file itself within Emacs and get all the fancy features for editing Emacs Lisp (Emacs usually tries to guess this based on the filename, and may not get it right for .emacs). <item> The `tab' key is bound to an indentation function in some modes, so when you press the tab key, it will indent the current line of code. If you want to put a tab character in whatever you're writing, hold the control key down while you're pressing the tab key. <item> This file supports syntax highlighting for C, C++, Perl, Lisp and Scheme (by guessing the language from the filename). <item> Emacs already has a pre-defined function called ``next-error''. In a compilation output window, this allows you to move from one compilation error to the next by doing M-n; we define a complementary function, ``previous-error'', that allows you to go to a previous error by doing M-p. The nicest feature of all is that C-c C-c will open up the source file in which the error occurred and jump to the appropriate line. <item> 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 <tscreen><verb> emacsclient <filename> </verb></tscreen> and then you can edit the file in your Emacs! (Many Emacs users set their EDITOR environment to `emacsclient' so this happens every time they need to edit a file). </itemize> <tscreen><verb> ;; -*-Emacs-Lisp-*- ;; This file is designed to be re-evaled; use the variable first-time ;; to avoid any problems with this. (defvar first-time t "Flag signifying this is the first time that .emacs has been evaled") ;; 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) (global-set-key [C-f10] 'kill-compilation) ;; 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) ;; Pretty diff mode (autoload 'ediff-buffers "ediff" "Intelligent Emacs interface to diff" t) (autoload 'ediff-files "ediff" "Intelligent Emacs interface to diff" t) (autoload 'ediff-files-remote "ediff" "Intelligent Emacs interface to diff") </verb></tscreen> <tscreen><verb> (if first-time (setq auto-mode-alist (append '(("\\.cpp$" . c++-mode) ("\\.hpp$" . c++-mode) ("\\.lsp$" . lisp-mode) ("\\.scm$" . scheme-mode) ("\\.pl$" . perl-mode) ) auto-mode-alist))) ;; Auto font lock mode (defvar font-lock-auto-mode-list (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'lisp-mode 'perl-mode 'scheme-mode) "List of modes to always start in font-lock-mode") (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)) ) ) (global-set-key [M-f1] 'font-lock-fontify-buffer) ;; New dabbrev stuff ;(require 'new-dabbrev) (setq dabbrev-always-check-other-buffers t) (setq dabbrev-abbrev-char-regexp "\\sw\\|\\s_") (add-hook 'emacs-lisp-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-replace) nil))) (add-hook 'c-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-replace) nil))) (add-hook 'text-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) t) (set (make-local-variable 'dabbrev-case-replace) t))) ;; C++ and C mode... (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) (setq c-indent-level 4) (setq c-continued-statement-offset 4) (setq c++-empty-arglist-indent 4)) (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)) ;; Add all of the hooks... (add-hook 'c++-mode-hook 'my-c++-mode-hook) (add-hook 'c-mode-hook 'my-c-mode-hook) (add-hook 'scheme-mode-hook 'my-scheme-mode-hook) (add-hook 'emacs-lisp-mode-hook 'my-lisp-mode-hook) (add-hook 'lisp-mode-hook 'my-lisp-mode-hook) (add-hook 'perl-mode-hook 'my-perl-mode-hook) ;; Complement to next-error (defun previous-error (n) "Visit previous compilation error message and corresponding source code." (interactive "p") (next-error (- n))) </verb></tscreen> <tscreen><verb> ;; 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) ;; Elisp archive searching (autoload 'format-lisp-code-directory "lispdir" nil t) (autoload 'lisp-dir-apropos "lispdir" nil t) (autoload 'lisp-dir-retrieve "lispdir" nil t) (autoload 'lisp-dir-verify "lispdir" nil t) ;; Font lock mode (defun my-make-face (face colour &optional bold) "Create a face from a colour and optionally make it bold" (make-face face) (copy-face 'default face) (set-face-foreground face colour) (if bold (make-face-bold face)) ) (if (eq window-system 'x) (progn (my-make-face 'blue "blue") (my-make-face 'red "red") (my-make-face 'green "dark green") (setq font-lock-comment-face 'blue) (setq font-lock-string-face 'bold) (setq font-lock-type-face 'bold) (setq font-lock-keyword-face 'bold) (setq font-lock-function-name-face 'red) (setq font-lock-doc-string-face 'green) (add-hook 'find-file-hooks 'font-lock-auto-mode-select) (setq baud-rate 1000000) (global-set-key "\C-cmm" 'menu-bar-mode) (global-set-key "\C-cms" 'scroll-bar-mode) (global-set-key [backspace] 'backward-delete-char) ; (global-set-key [delete] 'delete-char) (standard-display-european t) (load-library "iso-transl"))) ;; X11 or PC using direct screen writes (if window-system (progn ;; (global-set-key [M-f1] 'hilit-repaint-command) ;; (global-set-key [M-f2] [?\C-u M-f1]) (setq hilit-mode-enable-list '(not text-mode c-mode c++-mode emacs-lisp-mode lisp-mode scheme-mode) hilit-auto-highlight nil hilit-auto-rehighlight 'visible hilit-inhibit-hooks nil hilit-inhibit-rebinding t) (require 'hilit19) (require 'paren)) (setq baud-rate 2400) ; For slow serial connections ) ;; TTY type terminal (if (and (not window-system) (not (equal system-type 'ms-dos))) (progn (if first-time (progn (keyboard-translate ?\C-h ?\C-?) (keyboard-translate ?\C-? ?\C-h))))) ;; Under UNIX (if (not (equal system-type 'ms-dos)) (progn (if first-time (server-start)))) ;; Add any face changes here (add-hook 'term-setup-hook 'my-term-setup-hook) (defun my-term-setup-hook () (if (eq window-system 'pc) (progn ;; (set-face-background 'default "red") ))) ;; Restore the "desktop" - do this as late as possible (if first-time (progn (desktop-load-default) (desktop-read))) ;; Indicate that this file has been read at least once (setq first-time nil) ;; No need to debug anything now (setq debug-on-error nil) ;; All done (message "All done, %s%s" (user-login-name) ".") </verb></tscreen> <sect1><heading>Extending the Range of Languages Emacs Understands</heading> <p> Now, this is all very well if you only want to program in the languages already catered for in the .emacs file (C, C++, Perl, Lisp and Scheme), but what happens if a new language called "whizbang" comes out, full of exciting features? <p> The first thing to do is find out if "whizbang" comes with any files that tell Emacs about the language. These usually end in ".el", short for "Emacs Lisp". For example, if "whizbang" is a FreeBSD port, we can locate these files by doing <tscreen><verb> find /usr/ports/lang/whizbang -name *.el -print </verb></tscreen> -and install them by copying them into Emac's site Lisp directory. On +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. So for example, if the output from the find command was <tscreen><verb> /usr/ports/lang/whizbang/work/misc/whizbang.el </verb></tscreen> we would do <tscreen><verb> cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/share/emacs/site-lisp </verb></tscreen> 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. <p> Find the auto-mode-alist entry in .emacs and add a line for whizbang, such as:- <tscreen><verb> ... ("\\.lsp$" . lisp-mode) ("\\.wiz$" . whizbang-mode) ("\\.scm$" . scheme-mode) ... </verb></tscreen> This means that Emacs will automatically go into whizbang-mode when you edit a file ending in .wiz. <p> Just below this, you'll find the font-lock-auto-mode-list entry. Add whizbang-mode to it like so:- <tscreen><verb> ;; Auto font lock mode (defvar font-lock-auto-mode-list (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'whizbang-mode 'lisp-mode 'perl-mode 'scheme-mode) "List of modes to always start in font-lock-mode") </verb></tscreen> This means that Emacs will always enable font-lock-mode (ie syntax highlighting) when editing a .wiz file. <p> 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). <sect><heading>Further Reading</heading> <sect1><heading>Bibliography</heading> <p> <itemize> <item> Brian Harvey and Matthew Wright <em>Simply Scheme</em> MIT 1994. <newline>ISBN 0-262-08226-8 </item> <item> Randall Schwartz <em>Learning Perl</em> O'Reilly 1993 <newline>ISBN 1-56592-042-2 </item> <item> Patrick Henry Winston and Berthold Klaus Paul Horn <em>Lisp (3rd Edition)</em> Addison-Wesley 1989 <newline>ISBN 0-201-08319-1 </item> <item> Brian W. Kernighan and Rob Pike <em>The Unix Programming Environment</em> Prentice-Hall 1984 <newline>ISBN 0-13-937681-X </item> <item> Brian W. Kernighan and Dennis M. Ritchie <em>The C Programming Language (2nd Edition)</em> Prentice-Hall 1988 <newline>ISBN 0-13-110362-8 </item> <item> Bjarne Stroustrup <em>The C++ Programming Language</em> Addison-Wesley 1991 <newline>ISBN 0-201-53992-6 </item> <item> W. Richard Stevens <em>Advanced Programming in the Unix Environment</em> Addison-Wesley 1992 <newline>ISBN 0-201-56317-7 </item> <item> W. Richard Stevens <em>Unix Network Programming</em> Prentice-Hall 1990 <newline>ISBN 0-13-949876-1 </item> </itemize> </article> diff --git a/en/tutorials/disklessx/disklessx.sgml b/en/tutorials/disklessx/disklessx.sgml index 94a8b62c87..914236c41e 100644 --- a/en/tutorials/disklessx/disklessx.sgml +++ b/en/tutorials/disklessx/disklessx.sgml @@ -1,264 +1,266 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN" [ <!ENTITY base CDATA "../.."> -<!ENTITY date "$Date: 1996-09-24 17:46:00 $"> +<!ENTITY date "$Date: 1996-10-06 20:17:12 $"> <!ENTITY title "Diskless X Server: a how to guide"> <!ENTITY copyright " "> <!ENTITY % includes SYSTEM "../../includes.sgml"> %includes; ]> +<!-- $Id: disklessx.sgml,v 1.2 1996-10-06 20:17:12 jfieber Exp $ --> + <html> &header; <H3>By Jerry Kendall</H3> <H3>(<a href="mailto:jerry@kcis.com">jerry@kcis.com</a>)</H3> <p>With the help of some 'friends' on the FreeBSD-hackers list, I have been able to create a diskless X terminal... The creation of the X terminal required first creating a diskless system with minimal utilities mounted -via NFS. These same steps were used to create 2 seperate diskless systems. +via NFS. These same steps were used to create 2 separate diskless systems. The first is 'altair.kcis.com'. A diskless X terminal that I run on my old 386DX-40. It has a 340Meg hard disk but, I did not want to change it. So, it boots from 'antares.kcis.com' across a ethernet. The second system is a 486DX2-66. I setup a diskless FreeBSD (complete) that uses no local disk. The server in that case is a Sun 670MP running SunOS 4.1.3. The same setup configuration was needed for both.</p> <hr> NOTE: I am sure that there is stuff that needs to be added to this. Please send me any comments.... <hr> <h2>Creating the boot floppy (On the diskless system)</h2> <p>Since the network boot loaders will not work with some of the TSR's and such that MS-DOS uses, it is best to create a dedicated boot floppy OR, if you can, create an MS-DOS menu that will (via the config.sys/autoexec.bat files) ask what configuration to load when the system starts. The later is the method that I use and it works great. My MS-DOS (6.x) menu is below.</p> <pre> ---- config.sys ---- [menu] menuitem=normal, normal menuitem=unix, unix [normal] .... normal config.sys stuff ... [unix] ---- ---- autoexec.bat ---- @ECHO OFF goto %config% :normal ... normal autoexec.bat stuff ... goto end :unix cd \netboot nb8390.com :end ----</pre> <h2>Getting the network boot programs (On the server)</h2> <p>Compile the 'net-boot' programs that are located in /usr/src/sys/i386/boot/netboot. You should read the comments at the top of the makefile. Adjust as required. !!!! make a backup of the original in case it gets fobar'd !!! When the build is done, there should be 2 MS-DOS executables, 'nb8390.com' and 'nb3c509.com'. One of these two programs will be what you need to run on the diskless server. It will load the kernel from the boot server. At this point, put both programs on the MS-DOS boot floppy created earlier. <h2>Determine which program to run (On the diskless system)</h2> <p>If you know the chipset that your ethernet adapter uses, this is easy. If you have the NS8390 chipset, or a NS8390 based chipset, use NB8390.COM. If you have a 3Com 509 based chipset, use the NB3C509.COM boot program. If you are not sure which you have, try using one, if it says 'No adapter found', try the other. Beyond that, you are pretty much on your own. <h2>Booting across the network</h2> <p>Boot the diskless system with out any config.sys/autoexec.bat files. try running the boot program for your ethernet adapter.</p> <pre> My ethernet adapter is running in WD8013 16bit mode so I run NB8390.COM C:> cd \netboot C:> nb8390 Boot from Network (Y/N) ? Y BOOTP/TFTP/NFS bootstrap loader ESC for menu Searching for adapter.. WD8013EBT base 0x0300, memory 0x000D8000, addr 00:40:01:43:26:66 Searching for server..</pre> <p>At this point, my diskless system is trying to find a machine to act as a boot server. Make note of the addr line above, you will need this number later. Reset the diskless system and modify your config.sys and autoexec.bat files to do these steps automatically for you. Perhaps in a menu. If you had to run 'nb3c509.com' instead of 'nb8390.com' the output is the same as above. If you got 'No adapter found' at the 'Searching for adapter..' message, verify that you did indeed set the compile time defines in the makefile correctly.</p> <h2>Allowing systems to boot across the network (On the server)</h2> <p>Make sure the /etc/inetd.conf file has entries for tftp and bootps. Mine are listed below:</p> <pre> ---- /etc/inetd.conf ---- tftp dgram udp wait nobody /usr/libexec/tftpd tftpd # # Additions by who ever you are bootps dgram udp wait root /usr/libexec/bootpd bootpd /etc/bootptab ---- </pre> <p>If you have to change the /etc/inetd.conf file, send a HUP signal to inetd. To do this, get the process ID of inetd with 'ps -ax | grep inetd | grep -v grep'. Once you have it, send it a HUP signal. Do this by 'kill -HUP <pid>'. This will force inetd to re-read its config file.</p> <p>Did you remember to note the 'addr' line from the output of the boot loader on the diskless system???? Guess what, here is where you need it.</p> <p>Add an entry to /etc/bootptab (maybe creating the file). It should be laid out identical to this:</p> <pre> altair:\ :ht=ether:\ :ha=004001432666:\ :sm=255.255.255.0:\ :hn:\ :ds=199.246.76.1:\ :ip=199.246.76.2:\ :gw=199.246.76.1:\ :vm=rfc1048: The lines are as follows: 'altair' the diskless systems name without the domain name. 'ht=ether' the hardware type of 'ethernet'. 'ha=004001432666' the hardware address (the number noted above). 'sm=255.255.255.0' the subnet mask. 'hn' tells server to send client's hostname to the client. 'ds=199.246.76.1' tells the client who the domain server is. 'ip=199.246.76.2' tells the client what it's IP address is. 'gw=199.246.76.1' tells the client what the default gateway is. 'vm=...' just leave it there... </pre> <p>NOTE: ****** Be sure to setup the IP addresses correctly, the addresses above are my own......</p> <p>Create the directory '/tftpboot' on the server it will contain the configuration files for the diskless systems that the server will serve. These files will be named 'cfg.<ip>' where <ip> is the IP address of the diskless system. The config file for 'altair' is /tftpboot/cfg.199.246.76.2. The contents is:</p> <pre> ---- /tftpboot/cfg.199.246.76.2 ---- rootfs 199.246.76.1:/DiskLess/rootfs/altair hostname altair.kcis.com ---- </pre> <p>The line 'hostname altair.kcis.com' simply tells the diskless system what its fully qualified domain name is.</p> <p>The line 'rootfs 199.246.76.1:/DiskLess/rootfs/altair' tells the diskless system where its NFS mountable root filesystem is located.</p> <p>NOTE:!!!!! The NFS mounted root filesystem will be mounted READ ONLY.</p> <p>The hierarchy for the diskless system can be re-mounted allowing read-write operations if required.</p> <p>I use my spare 386DX-40 as a dedicated X terminal...</p> <p>The hierarchy for 'altair' is:</p> <pre> / /bin /etc /tmp /sbin /dev /dev/fd /usr /var /var/run </pre> <p>The actual list of files is:</p> <pre> -r-xr-xr-x 1 root wheel 779984 Dec 11 23:44 ./kernel -r-xr-xr-x 1 root bin 299008 Dec 12 00:22 ./bin/sh -rw-r--r-- 1 root wheel 499 Dec 15 15:54 ./etc/rc -rw-r--r-- 1 root wheel 1411 Dec 11 23:19 ./etc/ttys -rw-r--r-- 1 root wheel 157 Dec 15 15:42 ./etc/hosts -rw-r--r-- 1 root bin 1569 Dec 15 15:26 ./etc/XF86Config.altair -r-x------ 1 bin bin 151552 Jun 10 1995 ./sbin/init -r-xr-xr-x 1 bin bin 176128 Jun 10 1995 ./sbin/ifconfig -r-xr-xr-x 1 bin bin 110592 Jun 10 1995 ./sbin/mount_nfs -r-xr-xr-x 1 bin bin 135168 Jun 10 1995 ./sbin/reboot -r-xr-xr-x 1 root bin 73728 Dec 13 22:38 ./sbin/mount -r-xr-xr-x 1 root wheel 1992 Jun 10 1995 ./dev/MAKEDEV.local -r-xr-xr-x 1 root wheel 24419 Jun 10 1995 ./dev/MAKEDEV </pre> <p>Don't forget to 'MAKEDEV all' in the 'dev' directory.</p> <p>My /etc/rc for 'altair' is:</p> <pre> #!/bin/sh # PATH=/bin:/sbin export PATH # # configure the localhost /sbin/ifconfig lo0 127.0.0.1 # # configure the ethernet card /sbin/ifconfig ed0 199.246.76.2 netmask 0xffffff00 # # mount the root filesystem via NFS /sbin/mount antares:/DiskLess/rootfs/altair / # # mount the /usr filesystem via NFS /sbin/mount antares:/DiskLess/usr /usr # /usr/X11R6/bin/XF86_SVGA -query antares -xf86config /etc/XF86Config.altair > /dev/null 2>&1 # # Reboot after X exits /sbin/reboot # # We blew up.... exit 1 </pre> <hr> <p>Any comments and ALL questions welcome....</p> <address> Jerry Kendall<br> <a href="mailto:jerry@kcis.com">jerry@kcis.com</a> </address> &footer; </body> </html> diff --git a/en/tutorials/mh/mh.sgml b/en/tutorials/mh/mh.sgml index cea321165a..f9207d3b94 100644 --- a/en/tutorials/mh/mh.sgml +++ b/en/tutorials/mh/mh.sgml @@ -1,572 +1,573 @@ +<!-- $Id: mh.sgml,v 1.2 1996-10-06 20:17:14 jfieber Exp $ --> <!-- From matt@garply.com Wed May 22 08:25:18 1996 Date: Tue, 23 Jan 1996 11:02:50 -0600 From: Matt Midboe <matt@garply.com> To: jfieber@freebsd.org Subject: Introduction to MH for FreeBSD Handbook Okay I've diverged from my original plan on the handbook and condensed it a bit. If I find some time I am going to start working on something about how to use sendmail, since I imagine that would be a bit more useful. Here is my guide to using mh on freebsd. Let me know what changes it might need or things that need to be clearer or shorter. --> <!DOCTYPE linuxdoc PUBLIC "-//FreeBSD//DTD linuxdoc//EN"> <!-- This document explains some about the MUA MH --> <article> <title>An MH Primer <author>Matt Midboe, <url url="mailto:matt@garply.com" name="matt@garply.com"> <date>v1.0, 16 January 1996 <abstract>This document contains an introduction to using MH on FreeBSD</abstract> <toc> <sect>Introduction<label id="mhintro"> <p> <!-- This section is here to explain the philosophy behind MH Also make sure that the user has installed the mh package --> MH started back in 1977 at the RAND Corporation, where the initial philosophies behind MH were developed. MH isn't so much a monolithic email program but a philosophy about how best to develop tools for reading email. The MH developers have done a great job adhering to the KISS principle: Keep It Simple Stupid. Rather than have one large program for reading, sending and handling email they have written specialized programs for each part of your email life. One might liken MH to the specialization that one finds in insects and nature. Each tool in MH does one thing, and does it very well. Beyond just the various tools that one uses to handle their email MH has done an excellent job keeping the configuration of each of these tools consistent and uniform. In fact, if you are not quite sure how something is supposed to work or what the arguments for some command are supposed to be then you can generally guess and be right. Each MH command is consistent about how it handles reading the configuration files and how it takes arguments on the command line. One useful thing to remember is that you can always add a <tt/-help/ to the command to have it display the options for that command. The first thing that you need to do is to make sure that you have installed the MH package on your FreeBSD machine. If you installed from CDROM you should be able to execute the following to load mh: <tscreen><verb> pkg_add /cdrom/packages/mh-6.8.3.tgz </verb></tscreen> You will notice that it created a /usr/local/lib/mh directory for you as well as adding several binaries to the /usr/local/bin directory. If you would prefer to compile it yourself then you can anonymous ftp it from <url url="ftp://ftp.ics.uci.edu/" name="ftp.ics.uci.edu"> or <url url="ftp://louie.udel.edu/" name="louie.udel.edu">. This primer is not a full comprehensive explanation of how MH works. This is just intended to get you started on the road to happier, faster mail reading. You should read the man pages for the various commands. Also you might want to read the <url url="news:comp.mail.mh" name="comp.mail.mh"> newsgroup. Also you can read the <url url="http://www.cis.ohio-state.edu/hypertext/faq/usenet/mh-faq/part1/faq.html" name="FAQ"> for MH. The best resource for MH is the O'Reilly and Associates book written by Jerry Peek. <sect>Reading Mail <p> <!-- This section covers how to use inc, msgchk, next, prev, rmm, and rmf --> This section covers how to use <tt/inc/, <tt/show/, <tt/scan/, <tt/next/, <tt/prev/, <tt/rmm/, <tt/rmf/, and <tt/msgchk/. One of the best things about MH is the consistent interface between programs. A few things to keep in mind when using these commands is how to specify message lists. In the case of <em/inc/ this doesn't really make any sense but with commands like <em/show/ it is useful to know. A message list can consist of something like <tt/23 20 16/ which will act on messages 23, 20 and 16. This is fairly simple but you can do more useful things like <tt/23-30/ which will act on all the messages between 23 and 30. You can also specify something like <tt/cur:10/ which will act on the current message and the next 9 messages. The <tt/cur/, <tt/last/, and <tt/first/ messages are special messages that refer to the current, last or first message in the folder. <sect1><heading>inc, msgchk - read in your new email or check it<label id="inc"></> <p> If you just type in <em>inc</em> and hit return you will be well on your way to getting started with MH. The first time you run <em>inc</em> it will setup your account to use all the MH defaults and ask you about creating a Mail directory. If you have mail waiting to be downloaded you will see something that looks like: <tscreen><verb> 29 01/15 Doug White Re: Another Failed to boot problem<<On Mon, 15 J 30 01/16 "Jordan K. Hubbar Re: FBSD 2.1<<> Do you want a library instead of 31 01/16 Bruce Evans Re: location of bad144 table<<>> >It would appea 32 01/16 "Jordan K. Hubbar Re: video is up<<> Anyway, mrouted won't run, ev 33 01/16 Michael Smith Re: FBSD 2.1<<Nate Williams stands accused of sa </verb></tscreen> This is the same thing you will see from a ``<ref id="scan">''. If you just run <em>inc</em> with no arguments it will look on your computer for email that is supposed to be coming to you. A lot of people like to use POP for grabbing their email. MH can do POP to grab your email. You will need to give <em>inc</em> a few command line arguments. <tscreen><verb> inc -host mail.pop.org -user username -norpop </verb></tscreen> That tells <em>inc</> to go to <bf/mail.pop.org/ to download your email, and that your username on their system is <bf/username/. The <tt>-norpop</tt> option tells <em>inc</em> to use plain POP3 for downloading your email. MH has support for a few different dialects of POP. More than likely you will never ever need to use them though. While you can do more complex things with inc such as audit files and scan format files this will get you going. The <em/msgchk/ command is used to get information on whether or not you have new email. <em/msgchk/ takes the same <tt/-host/ and <tt/-user/ options that <em/inc/ takes. <sect1><heading>show, next and prev - displaying and moving through emails <label id="show"></> <p> <em/show/ is to show a letter in your current folder. Like inc, -<em/show/ is a fairly straightfoward command. If you just type +<em/show/ is a fairly straightforward command. If you just type <em/show/ and hit return then it displays the current message. You can also give specific message numbers to show: <tscreen><verb> show 32 45 56 </verb></tscreen> This would display message numbers 32, 45 and 56 right after each other. Unless you change the default behavior <em/show/ basically just does a more on the email message. <em/next/ is used to move onto the next message and <em/prev/ will go to the previous message. Both commands have an implied <em/show/ command so that when you go to the next message it automatically displays it. <sect1><heading>scan - shows you a scan of your messages<label id="scan"></> <p> <em/scan/ will display a brief listing of the messages in your current folder. This is an example of what the <em/scan/ command will give you. <tscreen><verb> 30+ 01/16 "Jordan K. Hubbar Re: FBSD 2.1<<> Do you want a library instead of 31 01/16 Bruce Evans Re: location of bad144 table<<>> >It would appea 32 01/16 "Jordan K. Hubbar Re: video is up<<> Anyway, mrouted won't run, ev 33 01/16 Michael Smith Re: FBSD 2.1<<Nate Williams stands accused of sa </verb></tscreen> Like just about everything in MH this display is very configurable. This is the typical default display. It gives you the message number, the date on the email, the sender, the subject line, and a sentence fragment from the very beginning of the email if it can fit it. The + means that message is the current message, so if you do a <em/show/ it will display that message. One useful option for scan is the <tt/-reverse/ option. This will list your messages with the highest message number first and lowest message -number last. Another useful option with <em/scan/ is to to have it +number last. Another useful option with <em/scan/ is to have it read from a file. If you want to scan your incoming mailbox on FreeBSD without having to <em/inc/ it you can do <tt>scan -file /var/mail/username</tt>. This can be used with any file that is in the <bf/mbox/ format. <sect1><heading>rmm and rmf - remove the current message or folder <label id="rmm"></> <p> <em/rmm/ is used to remove a mail message. The default is typically to not actually remove the message but to rename the file to one that is ignored by the MH commands. You will need to through periodically and physically delete the "removed" messages. The <em/rmf/ command is used to remove folders. This doesn't just rename the files but actually removes the from the hard drive so you should be careful when you use this command. <sect1><heading>A typical session of reading with MH<label id="samplereading"></> <p> The first thing that you will want to do is <em/inc/ your new mail. So at a shell prompt just type in <em/inc/ and hit return. <tscreen><verb> tempest% inc Incorporating new mail into inbox... 36+ 01/19 "Stephen L. Lange Request...<<Please remove me as contact for pind 37 01/19 Matt Thomas Re: kern/950: Two PCI bridge chips fail (multipl 38 01/19 "Amancio Hasty Jr Re: FreeBSD and VAT<<>>> Bill Fenner said: > In tempest% </verb></tscreen> This shows you the new email that has been added to your mailbox. So the next thing to do is <em/show/ the email and move around. <tscreen><verb> tempest% show Received: by sashimi.wwa.com (Smail3.1.29.1 #2) id m0tdMZ2-001W2UC; Fri, 19 Jan 96 13:33 CST Date: Fri, 19 Jan 1996 13:33:31 -0600 (CST) From: "Stephen L. Lange" <stvlange@wwa.com> To: matt@garply.com Subject: Request... Message-Id: <Pine.BSD.3.91.960119133211.824A-100000@sashimi.wwa.com> Mime-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII Please remove me as contact for pindat.com tempest% rmm tempest% next Received: from localhost (localhost [127.0.0.1]) by whydos.lkg.dec.com (8.6.11/8 .6.9) with SMTP id RAA24416; Fri, 19 Jan 1996 17:56:48 GMT Message-Id: <199601191756.RAA24416@whydos.lkg.dec.com> X-Authentication-Warning: whydos.lkg.dec.com: Host localhost didn't use HELO pro tocol To: hsu@clinet.fi Cc: hackers@FreeBSD.org Subject: Re: kern/950: Two PCI bridge chips fail (multiple multiport ethernet boards) In-Reply-To: Your message of "Fri, 19 Jan 1996 00:18:36 +0100." <199601182318.AA11772@Sysiphos> X-Mailer: exmh version 1.5omega 10/6/94 Date: Fri, 19 Jan 1996 17:56:40 +0000 From: Matt Thomas <matt@lkg.dec.com> Sender: owner-hackers@FreeBSD.org Precedence: bulk This is due to a typo in pcireg.h (to which I am probably the guilty party). </verb></tscreen> The <em/rmm/ removed the current message and the <em/next/ command moved me on to the next message. Now if I wanted to look at ten most recent messages so I could read one of them here is what I would do: <tscreen><verb> tempest% scan last:10 26 01/16 maddy Re: Testing some stuff<<yeah, well, Trinity has 27 01/17 Automatic digest NET-HAPPENINGS Digest - 16 Jan 1996 to 17 Jan 19 28 01/17 Evans A Criswell Re: Hey dude<<>From matt@tempest.garply.com Tue 29 01/16 Karl Heuer need configure/make volunteers<<The FSF is looki 30 01/18 Paul Stephanouk Re: [alt.religion.scientology] Raw Meat (humor)< 31 01/18 Bill Lenherr Re: Linux NIS Solaris<<--- On Thu, 18 Jan 1996 1 34 01/19 John Fieber Re: Stuff for the email section?<<On Fri, 19 Jan 35 01/19 support@foo.garpl [garply.com #1138] parlor<<Hello. This is the Ne 37+ 01/19 Matt Thomas Re: kern/950: Two PCI bridge chips fail (multipl 38 01/19 "Amancio Hasty Jr Re: FreeBSD and VAT<<>>> Bill Fenner said: > In tempest% </verb></tscreen> Then if I wanted to read message number 27 I would do a <tt/show 27/ and it would be displayed. As you can probably tell from this sample session MH is pretty easy to use and looking through emails and displaying them is fairly intuitive and easy. <sect>Folders and Mail Searching <p> -Anybody who gets lots of email definately wants to be able to +Anybody who gets lots of email definitely wants to be able to prioritize, stamp, brief, de-brief, and number their emails in a variety of different ways. MH can do this better than just about anything. One thing that we haven't really talked about is the concept of folders. You have undoubtedly come across the folders concept using other email programs. MH has folders too. MH can even do sub-folders of a folder. One thing you should keep in mind with MH is that when you ran <em/inc/ for the first time and it asked you if it could create a Mail directory it began storing everything in that directory. If you look at that directory you will find a directory named <bf/inbox/. The <bf/inbox/ directory houses all of your incoming mail that hasn't been thrown anywhere else. Whenever you create a new folder a new directory is going to be created underneath your MH Mail directory, and messages in that folder are going to be stored in that directory. When new email comes in that new email is thrown into your inbox directory with a file name that is equivalent to the message number. So even if you didn't have any of the MH tools to read your email you could still use standard unix commands to munge around in those directories and just more your files. It's this simplicity that really gives you a lot of power with what you can do with your email. Just as you can use message lists like <tt/23 16 42/ with most MH commands there is a folder option you can specify with just about every MH command. If you do a <tt/scan +freebsd/ it will scan your freebsd folder, and your current folder will be changed to freebsd. If you do a <tt/show +freebsd 23 16 42/ <em/show/ is going to switch to your freebsd folder and display messages 23, 16 and 42. So remember that +folder syntax. You will need to make sure you use it to make commands process different folders. Remember you default folder for mail is inbox so doing a <tt/folder +inbox/ should always get you back to your mail. Of course, in MH's infinite flexibility this can be changed but most places have probably left it as inbox. <!-- This section covers how to use pick, folder{s}, and slocal This needs to cover the general +folder format and an overview on the directory structure here. --> <sect1>pick - search email that matches certain criteria <p> <em/pick/ is one of the more complex commands in the MH system. So you might want to read the pick man page for a more thorough understanding. At its simplest level you can do something like <tscreen><verb> tempest% pick -search pci 15 42 55 56 57 </verb></tscreen> This will tell <em/pick/ to look through every single line in every message in your current folder and tell you which message numbers it found the word pci in. You can then <em/show/ those messages and read them if you wish or <em/rmm/ them. You would have to specify something like <tt/show 15 42 55-57/ to display them though. A slightly more useful thing to do is this: <tscreen><verb> tempest% pick -search pci -seq pick 5 hits tempest% show pick </verb></tscreen> This will show you the same messages you just didn't have to work as hard to do it. The <tt/-seq/ option is really an abbreviation of <tt/-sequence/ and <bf/pick/ is just a sequence which contains the message numbers that matched. You can use sequences with just about any MH command. So you could have done an <tt/rmm pick/ and all those messages would be removed instead. You sequence can be named anything. If you run pick again it will overwrite the old sequence if you use the same name. Doing a <tt/pick -search/ can be a bit more time consuming than just searching for message from someone, or to someone. So <em/pick/ allows you to use the following predefined search criteria: <itemize> <item><tt/-to/ search based upon who the message is to <item><tt/-cc/ search based on who is in the cc list <item><tt/-from/ search for who sent the message <item><tt/-subject/ search for emails with this subject <item><tt/-date/ find emails with a matching dat <item><tt>--<em>component</em></tt> search for any other component in the header. (i.e. --reply-to to find all emails with a certain reply-to in the header) </itemize> This allows you to do things like <tscreen><verb> pick -to freebsd-hackers@freebsd.org -seq hackers </verb></tscreen> to get a list of all the email send to the FreeBSD hackers mailing list. <em/pick/ also allows you to group these criteria in differents ways using the following options: <itemize> <item>... <tt/-and/ ... <item>... <tt/-or/ ... <item><tt/-not/ ... <item><tt/-lbrace/ ... <tt/-rbrace/ </itemize> These commands allow you to do things like <tscreen><verb> pick -to freebsd-hackers -and -cc freebsd-hackers </verb></tscreen> That will grab all the email in your inbox that was sent to freebsd-hackers or cc'd to that list. The brace options allow you to group search criteria together. This is sometimes very necessary as in the following example <tscreen><verb> pick -lbrace -to freebsd-hackers -and -not -cc freebsd-questions -rbrace -and -subject pci </verb></tscreen> Basically this says pick (to freebsd-hackers and not cc'd on freebsd-questions) and the subject is pci. It should look through your folder and find all messages send to the freebsd-hackers list that aren't cc'd to the freebsd-questions list that contain something on pci in the subject line. Ordinarily you might have to worry about something called operator precedence. Remember in math how you evaluate from left to right and you do multiplication and division first and addition and subtraction second? MH has the same type of rules for <em/pick/. It's fairly complex so you might want to study the man page. This document is just to help you get acquainted with MH. <sect1>folder, folders, refile - three useful programs for folder maintenance <p> There are three programs which are primarily just for manipulating your folders. The <em/folder/ program is used to switch between folders, pack them, and list them. At its simplest level you can do a <tt/folder +newfolder/ and you will be switched into <bf/newfolder/. From there on out all your MH commands like <em/comp/, <em/repl/, <em/scan/, and <em/show/ will act on that <bf/newfolder/ folder. Sometimes when you are reading and deleting messages you will develop ``holes'' in your folders. If you do a <em/scan/ you might just see messages 34, 35, 36, 43, 55, 56, 57, 80. If you do a <tt/folder -pack/ this will renumber all your messages so that there are no holes. It doesn't actually delete any messages though. So you may need to periodically go through and physically delete <em/rmm/'d messages. If you need statistics on your folders you can do a <em/folders/ or <tt/folder -all/ to list all your folders, how many messages they have, what the current message is in each one and so on. This line of stats it displays for all your folders is the same one you get when you change to a folder with <tt/folder +foldername/. A <em/folders/ command looks like this: <tscreen><verb> Folder # of messages ( range ); cur msg (other files) announce has 1 message ( 1- 1). drafts has no messages. f-hackers has 43 messages ( 1- 43). f-questions has 16 messages ( 1- 16). inbox+ has 35 messages ( 1- 38); cur= 37. lists has 8 messages ( 1- 8). netfuture has 1 message ( 1- 1). out has 31 messages ( 1- 31). personal has 6 messages ( 1- 6). todo has 58 messages ( 1- 58); cur= 1. TOTAL= 199 messages in 13 folders. </verb></tscreen> The <em/refile/ command is what you use to move messages between folders. When you do something like <tt/refile 23 +netfuture/ message number 23 is moved into the netfuture folder. You could also do something like <tt/refile 23 +netfuture/latest/ which would put message number 23 in a subfolder called latest under the netfuture folder. If you want to keep a message in the current folder and link it you can do a <tt/refile -link 23 +netfuture/ which would keep 23 in your current inbox but also list in your netfuture folder. You are probably beginning to realize some of the really powerful things you can do with MH. <sect>Sending Mail <p> <!-- This section covers how to use comp, repl and forw --> Email is a two way street for most people so you want to be able to send something back. The way MH handles sending mail can be a bit difficult to follow at first, but it allows for incredible flexibility. The first thing MH does is to copy a components file into your outgoing email. A components file is basically a skeleton email letter with stuff like the To: and Subject: headers already in it. You are then sent into your editor where you fill in the header information and then type the body of your message below the dashed lines in the message. Then to the <em/whatnow/ program. When you are at the ``What now?'' prompt you can tell it to <bf/send/, <bf/list/, <bf/edit/, <bf/edit/, <bf/push/, and <bf/quit/. Most of these commands are self-explanatory. So the message sending process involves copying a component file, editing your email, and then telling the <em/whatnow/ program what to do with your email. <sect1><heading>comp, forw, reply - compose, forward or reply to a message to someone</> <p> The <em/comp/ program has a few useful command line options. The most important one to know right now is the <tt/-editor/ option. When MH is installed the default editor is usually a program called <em/prompter/ which comes with MH. It's not a very exciting editor and basically just gets the job done. So when you go to compose a message to someone you might want to use <tt/comp -editor /usr/bin/vi/ or <tt/comp -editor /usr/local/bin/pico/ instead. Once you have run <em/comp/ you are in your editor and you see something that looks like this: <tscreen><verb> To: cc: Subject: -------- </verb></tscreen> You need to put the person you are sending the mail to after the To: line. It works the same way for the other headers also, so you would need to put your subject after the Subject: line. Then you would just put the body of your message after the dashed lines. It may seem a bit simplistic since a lot of email programs have special requesters that ask you for this information but there really isn't any point to that. Plus this really gives you excellent flexibility. <tscreen><verb> To:freebsd-rave@freebsd.org cc: Subject:And on the 8th day God created the FreeBSD core team -------- Wow this is an amazing operating system. Thanks! </verb></tscreen> You can now save this message and exit your editor. You will see the <tt/What now?/ prompt and you can type in <tt/send/ or <tt/s/ and hit return. Then the freebsd core team will receive their just rewards. As I mentioned earlier you can also send other commands, for example <tt/quit/ if you don't want to send the message. The <em/forw/ command is stunningly similar. The big difference being that the message you are forwarding is automatically included in the outgoing message. When you run <em/forw/ it will forward your current message. You can always tell it to forward something else by doing something like <tt/forw 23/ and then message number 23 will be put in your outgoing message instead of the current message. Beyond those small differences <em/forw/ functions exactly the same as <em/comp/. You go through the exact same message sending process. The <em/repl/ command will reply to whatever your current message is, unless you give it a different message to reply to. <em/repl/ will do its best to go ahead and fill in some of the email headers already. So you will notice that the To: header already has the address of the recipient in there. Also the Subject: line will already be filled in. You then go about the normal message composition process and you are done. One useful command line option to know here is the <tt/-cc/ option. You can use <bf/all/, <bf/to/, <bf/cc/, <bf/me/ after the <tt/-cc/ option to have <em/repl/ automatically add the various addresses to the cc list in the message. You have probably noticed that the original message isn't included. This is because most MH setups are configured to do this from the start. <sect1> components, and replcomps - components files for comp and repl <p> The <em/components/ file is usually in <tt>/usr/local/lib/mh</tt>. You can copy that file into your MH Mail directory and edit to contain what you want it to contain. It is a fairly basic file. You have various email headers at the top, a dashed line and then nothing. The <em/comp/ command just copies this <em/components/ file and then edits it. You can any kind of valid RFC822 header you want. For instance you could have something like this in your <em/components/ file: <tscreen><verb> To: Fcc: out Subject: X-Mailer: MH 6.8.3 X-Home-Page: http://www.freebsd.org/ ------- </verb></tscreen> MH would then copy this components file and throw you into your editor. The <em/components/ file is fairly simple. If you wanted to have a signature on those messages you would just put your signature in that <em/components/ file. The <em/replcomps/ file is a bit more complex. The default <em/replcomps/ looks like this: <tscreen><verb> %(lit)%(formataddr %<{reply-to}%?{from}%?{sender}%?{return-path}%>)\ %<(nonnull)%(void(width))%(putaddr To: )\n%>\ %(lit)%(formataddr{to})%(formataddr{cc})%(formataddr(me))\ %<(nonnull)%(void(width))%(putaddr cc: )\n%>\ %<{fcc}Fcc: %{fcc}\n%>\ %<{subject}Subject: Re: %{subject}\n%>\ %<{date}In-reply-to: Your message of "\ %<(nodate{date})%{date}%|%(pretty{date})%>."%<{message-id} %{message-id}%>\n%>\ -------- </verb></tscreen> It's in the same basic format as the <em/components/ file but it contains quite a few extra formatting codes. The %(lit) command makes room for the address. The %(formataddr is a function that returns a proper email address. The next part is %< which means if and the {reply-to} means the reply-to field in the original message. So that might be translated this way: <tscreen> %<<bf/if/ {reply-to} <bf/the original message has a reply-to/ then give that to formataddr, %? <bf/else/ {from} <bf/take the from address/, %? <bf/else/ {sender} <bf/take the sender address/, %? <bf/else/ {return-path} <bf/take the return-path from the original message/, %> <bf/endif/. </tscreen> As you can tell MH formatting can get rather involved. You can probably decipher what most of the other functions and variables mean. All of the information on writing these format strings is in the MH-Format man page. The really nice thing is that once you have built your customized <em/replcomps/ file you won't need to touch it again. No other email program really gives you the power and flexibility that MH gives you. </article> diff --git a/en/tutorials/multios/multios.sgml b/en/tutorials/multios/multios.sgml index 8841ffe82d..988812b25a 100644 --- a/en/tutorials/multios/multios.sgml +++ b/en/tutorials/multios/multios.sgml @@ -1,436 +1,437 @@ +<!-- $Id: multios.sgml,v 1.2 1996-10-06 20:17:16 jfieber Exp $ --> <!-- LinuxDoc file was created by LyX 0.8 (C) 1995 by Matthias Ettrich --> <!-- Export filter v0.5 by Pascal Andre --> <!doctype linuxdoc PUBLIC "-//FreeBSD//DTD linuxdoc//EN"> <article> <title>Installing and Using FreeBSD With Other Operating Systems <author><url name="Jay Richmond (jayrich@in.net)" url= "http://www.in.net/~jayrich/doc/mailme.html"> <date>08/06/96 <abstract>This document discusses how to make FreeBSD coexist nicely with other popular operating systems such as <BF>Linux</BF>, <BF>MS-DOS</BF>, <BF>OS/2</BF>, and <BF>Windows 95</BF>. Special thanks to: Annelise Anderson <htmlurl url="andrsn@stanford.edu" name="<andrsn@stanford.edu>"> Randall Hopper <htmlurl url="rhh@ct.picker.com" name="<rhh@ct.picker.com>">and Jordan K. Hubbard <htmlurl url="jkh@time.cdrom.com" name="<jkh@time.cdrom.com>"> </abstract> <toc> <sect>Overview <p>Most people can't fit these operating systems together comfortably without having a larger hard disk, so special information on large EIDE drives is included. Because there are so many combinations of possible operating systems and hard disk configurations, the <ref name="examples section" id="5"> may be of the most use to you. It contains descriptions of specific working computer setups that use multiple operating systems. <p>This document assumes that you have already made room on your hard disk for an additional operating system. Any time you repartition your hard drive, you run the risk of destroying the data on the original partitions. However, if your hard drive is completely occupied by DOS, you might find the FIPS utility (included on the FreeBSD CD-ROM in the \TOOLS directory or via ftp at <htmlurl url="ftp://ftp.freebsd.org/pub/FreeBSD/2.1.5-RELEASE/tools" name="ftp://ftp.freebsd.org/pub/FreeBSD/2.1.5-RELEASE/tools">) useful. It lets you repartition your hard disk without destroying the data already on it. There is also a commercial program available called Partition Magic, which lets you size and delete partitions without consequence. <sect>Overview of Boot Managers <label id="2"><p>These are just brief descriptions of some of the different boot managers you may encounter. Depending on your computer setup, you may find it useful to use more than one of them on the same system. <p>Boot Easy: This is the default boot manager used with FreeBSD. It has the ability to boot most anything, including BSD, OS/2 (HPFS), Windows 95 (FAT and FAT32**), and Linux. Partitions are selected with the function keys. <p>OS/2 Boot Manager: This will boot FAT, HPFS, FFS (FreeBSD), and EXT2 (Linux). It will also boot FAT32** partitions. Partitions are selected using arrow keys. The OS/2 Boot Manager is the only one to use its own separate partition, unlike the others which use the master boot record (MBR). Therefore, it must be installed below the 1024th cylinder to avoid booting problems. It can boot Linux using LILO when it is part of the boot sector, not the MBR. Go to <htmlurl url="http://www.ssc.com/linux/howto.html" name="http://www.ssc.com/linux/howto.html"> on the World Wide Web for more information on booting Linux with OS/2's boot manager. <p>OS-BS: This is an alternative to Boot Easy. It gives you more control over the booting process, with the ability to set the default partition to boot and the booting timeout. The 'beta' version of this programs allows you to boot by selecting the OS with your arrow keys. It is included on the FreeBSD CD in the \TOOLS directory, and via ftp at <htmlurl url="ftp://ftp.freebsd.org/pub/FreeBSD/2.1.5-RELEASE/tools" name="ftp://ftp.freebsd.org/pub/FreeBSD/2.1.5-RELEASE/tools"> <p>LILO, or LInux LOader: This is a limited boot manager. Will boot FreeBSD, though some customization work is required in the LILO configuration file. <p>** FAT32 is the replacement to the FAT filesystem included in Microsoft's OEM SR2 Beta release, which is expected to utilitized on computers pre-loaded with Windows 95 towards the end of 1996. It converts the normal FAT file system and allows you to use smaller cluster sizes for larger hard drives. FAT32 also modifies the traditional FAT boot sector and allocation table, making it incompatible with some boot managers. <sect>A Typical Installation <label id="3"><P>Let's say I have two large EIDE hard drives, and I want to install FreeBSD, Linux, and Windows 95 on them. <P>Here's how I might do it using these hard disks: <enum> <item>/dev/wd0 (first physical hard disk) <item>/dev/wd1 (second hard disk) </enum> <P>Both disks have 1416 cylinders. <P>1. I boot from a MS-DOS or Windows 95 boot disk that contains the FDISK.EXE utility and make a small 50 meg primary partition (35-40 for Windows 95, plus a little breathing room) on the first disk. Also create a larger partition on the second hard disk for my Windows applications and data. <P>2. I reboot and install Windows 95 (easier said than done) :) on the "C:" partition. <P>3. The next thing I do is install Linux. I'm not sure about all the distributions of Linux, but slackware includes LILO (see <ref name="section 2" id="2">). When I am partitioning out my hard disk with Linux "fdisk," I would put all of Linux on the first drive (maybe 300 megs for a nice root partition and some swap space). <P>4. After I install Linux, and are prompted about installing LILO, make SURE that I install it on the boot sector of my root Linux partition, not in the MBR (master boot record). <P>5. The remaining hard disk space can go to FreeBSD. I also make sure that my FreeBSD root slice does not go beyond the 1024th cylinder. (The 1024th cylinder is 528 megs into the disk with our hypothetical 720MB disks). I will use the rest of the hard drive (about 270 megs) for the "/usr" and "/" slices if I wish. The rest of the second hard disk (size depends on the amount of my Windows application/data partition that I created in step 1 can go to the "/usr/src" slice and swap space. <P><VERB> --------------------------------------------------------------------- When viewed with the Windows 95 "fdisk" utility, my hard drives should now look something like this: Display Partition Information Current fixed disk drive: 1 Partition Status Type Volume_Label Mbytes System Usage C: 1 A PRI DOS 50 FAT** 7% 2 A Non-DOS (Linux) 300 43% Total disk space is 696 Mbytes (1 Mbyte = 1048576 bytes) Press Esc to continue --------------------------------------------------------------------- Display Partition Information Current fixed disk drive: 2 Partition Status Type Volume_Label Mbytes System Usage D: 1 A PRI DOS 420 FAT** 60% Total disk space is 696 Mbytes (1 Mbyte = 1048576 bytes) Press Esc to continue ** May say FAT16 or FAT32 if you are using the OEM SR2 update (see <ref name="section 2" id="2">). --------------------------------------------------------------------- </VERB> <P>6. Install FreeBSD. I make sure to boot with my first hard disk set at "NORMAL" in the BIOS. If it is not, I'll have the enter my true disk geometry at boot time (to get this, boot Windows 95 and consult Microsoft Diagnostics (MSD.EXE), or check your BIOS) with the parameter "hd0=1416,16,63" where 1416 is the number of cylinders on my hard disk, 16 is the number of heads per track, and 63 is the number of sectors per track on the drive. <P>7. When partitioning out the hard disk, I make sure to install "Boot Easy" on the first disk. I don't worry about the second disk, nothing is booting off of it. <P>8. When I reboot, "Boot Easy" should recognize my three bootable partitions as DOS (Windows 95), Linux, and BSD (FreeBSD). <sect>Special Considerations <label id="4"><P>Most operating systems are very picky about where and how they are placed on the hard disk. Windows 95 and DOS need to be on the first primary partition on the first hard disk. OS/2 is the exception. It can be installed on the first or second disk in a primary or extended partition. If you are not sure, keep the beginning of the bootable partitions below the 1024th cylinder. <P>If you install Windows 95 on an existing BSD system, it will "destroy" the MBR, and you will have to reinstall your previous boot manager. Boot Easy can be reinstalled by using the BOOTINST.EXE utility included in the \TOOLS directory on the CD-ROM, and via ftp at <htmlurl url="ftp://ftp.freebsd.org/pub/FreeBSD/2.1.5-RELEASE/tools" name="ftp://ftp.freebsd.org/pub/FreeBSD/2.1.5-RELEASE/tools">. You can also re-start the installation process and go to the partition editor. >From there, mark the FreeBSD partition as bootable, select Boot Manager, and then type W to (W)rite out the information to the MBR. You can now reboot, and "Boot Easy" should then recognize Windows 95 as "DOS." <P>Please keep in mind that OS/2 can read FAT and HPFS partitions, but not FFS (FreeBSD) or EXT2 (Linux) partitions. Likewise, Windows 95 can only read and write to FAT and FAT32 (see <ref name="section 2" id="2">) partitions. FreeBSD can read most file systems, but currently cannot read HPFS partitions. Linux can read HPFS partitions, but can't write to them. Recent versions of the Linux kernel (2.x) can read and write to Windows 95 VFAT partitions (VFAT is what gives Windows 95 long file names - it's pretty much the same as FAT). Linux can read and write to most file systems. Got that? I hope so. <sect>Examples <label id="5"><P><EM>(section needs work, please send your example to <htmlurl url="mailto:jayrich@in.net" name="jayrich@in.net">)</EM>. <P>FreeBSD+Win95: If you installed FreeBSD after Windows 95, you should see 'DOS' on the "Boot Easy" menu. This is Windows 95. If you installed Windows 95 after FreeBSD, read <ref name="section 4" id="4"> above. As long as your hard disk does not have 1024 cylinders you should not have a problem booting. If one of your partitions goes beyond the 1024th cylinder however, and you get messages like "invalid system disk" under DOS (Windows 95) and FreeBSD will not boot, try looking for a setting in your BIOS called "> 1024 cylinder support" or "NORMAL/LBA" mode. DOS may need LBA (Logical Block Addressing) in order to boot correctly. If the idea of switching BIOS settings every time you boot up doesn't appeal to you, you can boot FreeBSD through DOS via the FBSDBOOT.EXE utility on the CD (It should find your FreeBSD partition and boot it.) <P>FreeBSD+OS/2+Win95: Nothing new here. OS/2's boot manger can boot all of these operating systems, so that shouldn't be a problem. <P>FreeBSD+Linux: You can also use "Boot Easy" to boot both operating systems. <P>FreeBSD+Linux+Win95: (see <ref name="section 3" id="3">) <label id="sources"><sect>Other Sources of Help <P>There are many Linux HOW-TO's that deal with multiple operating systems on the same hard disk. They are available on the World Wide Web at <htmlurl url="http://www.ssc.com/linux/howto.html" name="http://www.ssc.com/linux/howto.html">. <P>The Linux+OS/2+DOS Mini-HOWTO offers help on configuring the OS/2 boot manager. It is also available on the WWW at: <htmlurl url="http://sunsite.unc.edu/mdw/HOWTO/mini/Linux+OS2+DOS" name="http://sunsite.unc.edu/mdw/HOWTO/mini/Linux+OS2+DOS">. And the <htmlurl url="http://www.in.net/~jkatz/win95/Linux-HOWTO.html" name="http://www.in.net/~jkatz/Linux-HOWTO.html"> is also helpful. <P>The NT Loader Hacking Guide provides good information on multibooting Windows NT, '95, and DOS with other operating systems. It's available at <htmlurl url="http://www.dorsai.org/~dcl/publications/NTLDR_Hacking" name="http://www.dorsai.org/~dcl/publications/NTLDR_Hacking">. <P>And Hale Landis's "How It Works" document pack contains some good info on all sorts of disk geometry and booting related topics. Here are a few links that might help you find it: <htmlurl url="ftp://fission.dt.wdc.com/pub/otherdocs/pc_systems/how_it_works/allhiw.zip" name="ftp://fission.dt.wdc.com/pub/otherdocs/pc_systems/how_it_works/allhiw.zip">, <htmlurl url="http://www.cs.yorku.ca/People/frank/docs/" name="http://www.cs.yorku.ca/People/frank/docs/">. <P>Finally, don't overlook FreeBSD's kernel documentation on the booting procedure, available in the kernel source distribution (it unpacks to <htmlurl url="file:/usr/src/sys/i386/boot/biosboot/README.386BSD" name="file:/usr/src/sys/i386/boot/biosboot/README.386BSD">. <sect>Technical Details <P><EM>(Contributed by Randall Hopper <htmlurl url="rhh@ct.picker.com" name="<rhh@ct.picker.com>">)</EM> <P>This section attempts to give you enough basic information about your hard disks and the disk booting process so that you can troubleshoot most problems you might encounter when getting set up to boot several operating systems. It starts in pretty basic terms, so you may want to skim down in this section until it begins to look unfamiliar and then start reading. <sect1>Disk Primer <P>Three fundamental terms are used to describe the location of data on your hard disk: Cylinders, Heads, and Sectors. It's not particularly important to know what these terms relate to except to know that, together, they identify where data is physically on your disk. <P>Your disk has a particular number of cylinders, number of heads, and number of sectors per cylinder-head (a cylinder-head also known nown as a track). Collectively this information defines the "physical disk geometry" for your hard disk. There are typically 512 bytes per sector, and 63 sectors per track, with the number of cylinders and heads varying widely from disk to disk. Thus you can figure the number of bytes of data that'll fit on your own disk by calculating: <VERB> (# of cylinders) * (# heads) * (63 sectors/track) * (512 bytes/sect) </VERB> <P>For example, on my 1.6 Gig Western Digital AC31600 EIDE hard disk,that's: <VERB> (3148 cyl) * (16 heads) * (63 sectors/track) * (512 bytes/sect) </VERB> <P>which is 1,624,670,208 bytes, or around 1.6 Gig. <P>You can find out the physical disk geometry (number of cylinders, heads, and sectors/track counts) for your hard disks using ATAID or other programs off the net. Your hard disk probably came with this information as well. Be careful though: if you're using BIOS LBA (see <ref name="section 7.3" id="limits">), you can't use just any program to get the physical geometry. This is because many programs (e.g. MSD.EXE or FreeBSD fdisk) don't identify the physical disk geometry; they instead report the "translated geometry" (virtual numbers from using LBA). Stay tuned for what that means. <P>One other useful thing about these terms. Given 3 numbers -- a cylinder number, a head number, and a sector-within-track number -- you identify a specific absolute sector (a 512 byte block of data) on your disk. Cylinders and Heads are numbered up from 0, and Sectors are numbered up from 1. <P>For those that are interested in more technical details, information on disk geometry, boot sectors, BIOSes, etc. can be found all over the net. Query Lycos, Yahoo, etc. for "boot sector" or "master boot record". Among the useful info you'll find are Hale Landis's "How It Works" document pack. See the <ref name="Other Sources of Help" id="sources"> section for a few pointers to this pack. <P>Ok, enough terminology. We're talking about booting here. <sect1><heading>The Booting Process<label id="booting"></heading> <P>On the first sector of your disk (Cyl 0, Head 0, Sector 1) lives the Master Boot Record (MBR). It contains a map of your disk. It identifies up to 4 "partitions", each of which is a contiguous chunk of that disk. FreeBSD calls partitions "slices" to avoid confusion with it's own partitions, but we won't do that here. Each partition can contain its own operating system. <P>Each partition entry in the MBR has a "Partition ID", a "Start Cylinder/Head/Sector", and an "End Cylinder/Head/Sector". The Partition ID tells what type of partition it is (what OS) and the Start/End tells where it is. Here's a smattering of some common Partition IDs: <VERB> ID (hex) DESCRIPTION 01 ...... Primary DOS12 (12-bit FAT) 04 ...... Primary DOS16 (16-bit FAT) 05 ...... Extended DOS 06 ...... Primary big DOS (> 32MB) 0A ...... OS/2 83 ...... Linux (EXT2FS) A5 ...... FreeBSD, NetBSD, 386BSD (UFS) </VERB> <P>Note that not all partitions are bootable (e.g. Extended DOS). Some are -- some aren't. What makes a partition bootable is the configuration of the "Partition Boot Sector" that exists at the beginning of each partition. <P>When you configure your favorite boot manager, it looks up the entries in the MBR partition tables of all your hard disks and lets you name the entries in that list. Then when you boot, the boot manager is invoked by special code in the Master Boot Sector of the first probed hard disk on your system. It looks at the MBR partition table entry corresponding to the partition choice you made, uses the Start Cylinder/Head/Sector information for that partition, loads up the Partition Boot Sector for that partition, and gives it control. That Boot Sector for the partition itself contains enough information to start loading the operating system on that partition. <P>One thing we just brushed past that's important to know. All of your hard disks have MBRs. However, the one that's important is the one on the disk that's first probed by the BIOS. If you have only IDE hard disks, its the first IDE disk (e.g. primary disk on first controller). Similarly for SCSI only systems. If you have both IDE and SCSI hard disks though, the IDE disk is typically probed first by the BIOS, so the first IDE disk is the first probed disk. The boot manager you will install will be hooked into the MBR on this first probed hard disk that we've just described. <sect1>Booting Limitations and Warnings <label id="limits"><P>Now the interesting stuff that you need to watch out for. <P><BF>1. The dreaded 1024 cylinder limit and how BIOS LBA helps</BF> <P>The first part of the booting process is all done through the BIOS, (if that's a new term to you, the BIOS is a software chip on your system motherboard which provides startup code for your computer). As such, this first part of the process is subject to the limitations of the BIOS interface. <P>The BIOS interface used to read the hard disk during this period (INT 13H, Subfunction 2) allocates 10 bits to the Cylinder Number, 8 bits to the Head Number, and 6 bits to the Sector Number. This restricts users of this interface (i.e. boot managers hooked into your disk's MBR as well as OS loaders hooked into the Boot Sectors) to the following limits: <VERB> 1024 cylinders, max 256 heads , max 64 cylinders, max (actually 63 -- "0" isn't available) </VERB> <P>Now big hard disks have lots of cylinders but not a lot of heads, so invariably with big hard disks the number of cylinders is greater than 1024. Given this and the BIOS interface as is, you can't boot off just anywhere on your hard disk. The boot code (the boot manager and the OS loader hooked into all bootable partitions' Boot Sectors) has to reside below cylinder 1024. In fact, if your hard disk is typical and has 16 heads, this equates to: <VERB> 1024 cyl/disk * 16 heads/disk * 63 sect/(cyl-head) * 512 bytes/sector </VERB> <P>which is around the often-mentioned 528MB limit. <P>This is where BIOS LBA (Logical Block Addressing) comes in. BIOS LBA gives the user of the BIOS API calls access to physical cylinders above 1024 though the BIOS interfaces by "redefining" a cylinder. That is, it remaps your cylinders and heads, making it appear through the BIOS as though the disk has "fewer" cylinders and "more" heads than it actually does. In other words, it takes advantage of the fact that hard disks have relatively few heads and lots of cylinders by shifting the balance between number of cylinders and number of heads so that both numbers lie below the above-mentioned limits (1024 cylinders, 256 heads). <P>With BIOS LBA, the hard disk size limitation is virtually removed (well, pushed up to 8 Gigabytes anyway). If you have an LBA BIOS, you can put FreeBSD or any OS anywhere you want and not hit the 1024 cylinder limit. -<P>To use my my 1.6 Gig Western Digital as an example again, it's +<P>To use my 1.6 Gig Western Digital as an example again, it's physical geometry is: <VERB> (3148 cyl, 16 heads, 63 sectors/track, 512 bytes/sector) </VERB> <P>However, my BIOS LBA remaps this to: <VERB> ( 787 cyl, 64 heads, 63 sectors/track, 512 bytes/sector) </VERB> <P>giving the same effective size disk, but with cylinder and head counts within the BIOS API's range (Incidentally, I have both Linux and FreeBSD existing on one of my hard disks above the 1024th physical cylinder, and both operating systems boot fine, thanks to BIOS LBA). <P><BF>2. Boot Managers and Disk Allocation</BF> <P>Another gotcha to watch out when installing boot managers is allocating space for your boot manager. It's best to be aware of this issue up front to save yourself from having to reinstall one or more of your OSs. <P>If you followed the discussion in <ref name="section 7.2" id="booting"> about the Master Boot Sector (where the MBR is), Partition Boot Sectors, and the booting process, you may have been wondering just exactly where on your hard disk that nifty boot manager is going to live. Well, some boot managers are small enough to fit entirely within the Master Boot Sector (Cylinder 0, Head 0, Sector 0) along with the partition table. Others need a bit more room and actually extend a few sectors past the Master Boot Sector in the Cylinder 0 Head 0 track, since that's typically free...typically. <P>That's the catch. Some operating systems (FreeBSD included) let you start their partitions right after the Master Boot Sector at Cylinder 0, Head 0, Sector 2 if you want. In fact, if you give FreeBSD's sysinstall a disk with an empty chunk up front or the whole disk empty, that's where it'll start the FreeBSD partition by default (at least it did when I fell into this trap :-). Then when you go to install your boot manager, if it's one that occupies a few extra sectors after the MBR, it'll overwrite the front of the first partition's data. In the case of FreeBSD, this overwrites the disk label, and renders your FreeBSD partition unbootable. <P>The easy way to avoid this problem (and leave yourself the flexibility to try different boot managers later) is just to always leave the first full track on your disk unallocated when you partition your disk. That is, leave the space from Cylinder 0, Head 0, Sector 2 through Cylinder 0, Head 0, Sector 63 unallocated, and start your first partition at Cylinder 0, Head 1, Sector 1. For what it's worth, when you create a DOS partition at the front of your disk, DOS leaves this space open by default (this is why some boot managers assume it's free). So creating a DOS partition up at the front of your disk avoids this problem altogether. I like to do this myself, creating 1 Meg DOS partition up front, because it also avoids my primary DOS drive letters shifting later when I repartition. <P>For reference, the following boot managers use the Master Boot Sector to store their code and data: <itemize> <item>OS-BS 1.35 <item>Boot Easy <item>LILO </itemize> <P>These boot managers use a few additional sectors after the Master Boot Sector: <itemize> <item>OS-BS 2.0 Beta 8 (sectors 2-5) <item>OS/2's boot manager </itemize> <P><BF>3. What if your machine won't boot?</BF> <P>At some point when installing boot managers, you might leave the MBR in a state such that your machine won't boot. This is unlikely, but possible when re-FDISKing underneath an already-installed boot manager. <P>If you have a bootable DOS partition on your disk, you can boot off a DOS floppy, and run: <VERB> FDISK /MBR </VERB> <P>to put the original, simple DOS boot code back into the system. You can then boot DOS (and DOS only) off the hard drive. Alternatively, just re-run your boot manager installation program off a bootable floppy. </article> diff --git a/en/tutorials/newuser/newuser.sgml b/en/tutorials/newuser/newuser.sgml index 081910225b..7e6bf5b6c6 100644 --- a/en/tutorials/newuser/newuser.sgml +++ b/en/tutorials/newuser/newuser.sgml @@ -1,537 +1,538 @@ <!DOCTYPE linuxdoc PUBLIC "-//FreeBSD//DTD linuxdoc//EN"> +<!-- $Id: newuser.sgml,v 1.2 1996-10-06 20:17:19 jfieber Exp $ --> <article> <title>For People New to Both FreeBSD <em>and</em> Unix <author>Annelise Anderson <htmlurl url="mailto:andrsn@hoover.stanford.edu" name="<andrsn@hoover.stanford.edu>"> <date>June 30, 1996 <abstract>Congratulations on installing FreeBSD! This introduction is for people new to both FreeBSD <em>and</em> Un*x---so it starts with basics. It assumes you're using version 2.0.5 or later of FreeBSD as distributed by Walnut Creek or FreeBSD.ORG, your system (for now) has a single user (you)---and you're probably pretty good with DOS/Windows or OS/2. </abstract> <toc> <!-- ************************************************************ --> <sect>Logging in and Getting Out <p>Log in (when you see <tt>login:</tt>) as a user you created during installation or as <em>root</em>. (Your FreeBSD installation will already have an account for root; root can go anywhere and do anything, including deleting essential files, so be careful!) To log out (and get a new <tt>login</tt> prompt) type <tscreen> exit </tscreen> as often as necessary. Yes, press <em>enter</em> after commands, and remember that Unix is case-sensitive---<tt>exit</tt>, not <tt>EXIT</tt>. To shut down the machine type: <tscreen> /sbin/shutdown -h now </tscreen> Or to reboot type <tscreen> /sbin/shutdown -r now </tscreen> or <tscreen> /sbin/reboot </tscreen> You can also reboot with <tt>Ctrl-Alt-Delete</tt>. Give it a little time to do its work. This is equivalent to <tt>/sbin/reboot</tt> in recent releases of FreeBSD, and is much, much better than hitting the reset button. You don't want to have to reinstall this thing, do you? <!-- ************************************************************ --> <sect>Adding A User with Root Privileges <p>If you didn't create any users when you installed the system and are thus logged in as root, you should probably create a user now with <tscreen> adduser </tscreen> Don't use the <tt>-verbose</tt> option; the defaults are what you want. Suppose you create a user <em>jack</em> with full name <em>Jack Benimble</em>. Give jack a password if security (even kids around who might pound on the keyboard) is an issue. When it asks you if you want to invite jack into other groups, type <tscreen> wheel </tscreen> This will make it possible to log in as <em>jack</em> and use the <tt>su</tt> command to become root. Then you won't get scolded any more for logging in as root, and as root you'll have the same environment as jack (this is good). You can quit <tt>adduser</tt> any time by typing <tt>Ctrl-C</tt>, and at the end you'll have a chance to approve your new user or simply type <tt>n</tt> for no. You might want to create a second newuser (jill?) so that when you edit jack's login files, you'll have a hot spare in case something goes wrong. Once you've done this, use <tt>exit</tt> to get back to a login prompt and log in as <em>jack</em>. In general, it's a good idea to do as much work as possible as an ordinary user who doesn't have the power---and risk---of root. If you already created a user and you want the user to be able to <tt>su</tt> to root, you can log in as root and edit the file <tt>/etc/group</tt>, adding jack to the first line (the group wheel). But first you need to practice <tt>vi</tt>, the text editor. <!-- ************************************************************ --> <sect>Looking Around <p>Logged in as an ordinary user, look around and try out some commands that will access the sources of help and information within FreeBSD. Here are some commands and what they do: <descrip> <tag/<tt>id</tt>/ Tells you who you are! <tag/<tt>pwd</tt>/ Shows you where you are---the current working directory. <tag/<tt>ls</tt>/ Lists the files in the current directory. <tag/<tt>ls -F</tt>/ Lists the files in the current directory with a * after executables, a / after directories, and an @ after symbolic links. <tag/<tt>ls -l</tt>/ Lists the files in long format---size, date, permissions. <tag/<tt>ls -a</tt>/ Lists hidden (unless you're root) ``dot'' files with the others. <tag/<tt>cd</tt>/ Changes directories. <tt>cd ..</tt> backs up one level; note the space after <tt>cd</tt>. <tt>cd /usr/local</tt> goes there. <tt>cd ~</tt> goes to the home directory of the person logged in---e.g., <tt>/usr/home/jack</tt>. Try <tt>cd /cdrom</tt>, and then <tt>ls</tt>, to find out - if your cdrom is mounted and working. + if your CDROM is mounted and working. <tag/<tt>view <em>filename</em></tt>/ Lets you look at a file (named <em>filename</em> without changing it. Try <tt>view /etc/fstab</tt>. <tt>:q</tt> to quit. <tag/<tt>cat <em>filename</em></tt>/ Displays <em>filename</em> on screen. If it's too long and you can see only the end of it, press <tt>ScrollLock</tt> and use the <tt>up-arrow</tt> to move backward; you can use <tt>ScrollLock</tt> with man pages too. Press <tt>ScrollLock</tt> again to quit scrolling. You might want to try <tt>cat</tt> on some of the dot files in your home directory---<tt>cat .cshrc</tt>, <tt>cat .login</tt>, <tt>cat .profile</tt>. </descrip> You'll notice aliases in <tt>.cshrc</tt> for some of the <tt>ls</tt> commands (they're very convenient). You can create other aliases by editing <tt>.cshrc</tt>. You can make these aliases available to all users on the system by putting them in the system-wide csh configuration file, <em>/etc/csh.cshrc</em>. <!-- ************************************************************ --> <sect>Getting Help and Information <p>Here are some useful sources of help. ``text'' stands for something of your choice that you type in---usually a command or filename. <descrip> <tag/<tt>apropos <em>text</em></tt>/ Everything containing string <em>text</em> in the whatis database. <tag/<tt>man <em>text</em></tt>/ The man page for <em>text</em>. The major source of documentation for Un*x systems. <tt>man ls</tt> will tell you all the ways to use the <tt>ls</tt> command. Press <tt>Enter</tt> to move through text, <tt>Ctrl-b</tt> to go back a page, <tt>Ctrl-f</tt> to go forward, <tt>q</tt> or <tt>Ctrl-c</tt> to quit. <tag/<tt>which <em>text</em></tt>/ Tells you where in the user's path the command <em>text</em> is found. <tag/<tt>locate <em>text</em></tt>/ All the paths where the string <tt>text</tt> is found. <tag/<tt>whatis <em>text</em></tt>/ Tells you what the command <tt>text</tt> does and its man page. <tag/<tt>whereis <em>text</em></tt>/ Finds the file <em>text</em>, giving its full path. </descrip> You might want to try using <tt>whatis</tt> on some common useful commands like <tt>cat</tt>, <tt>more</tt>, <tt>grep</tt>, <tt>mv</tt>, <tt>find</tt>, <tt>tar</tt>, <tt>chmod</tt>, <tt>chown</tt>, <tt>date</tt>, and <tt>script</tt>. <tt>more</tt> lets you read a page at a time as it does in DOS, e.g., <tt>ls -l | more</tt> or <tt>more <em>filename</em></tt>. The <tt>*</tt> works as a wildcard---e.g., <tt>ls w*</tt> will show you files beginning with w. Are some of these not working very well? Both <tt>locate</tt> and <tt>whatis</tt> depend on a database that's rebuilt weekly. If your machine isn't going to be left on over the weekend (and running FreeBSD), you might want to run the commands for daily, weekly, and monthly maintenance now and then. Run them as root and give each one time to finish before you start the next one, for now. <tscreen> /etc/daily<newline> /etc/weekly<newline> /etc/monthly </tscreen> If you get tired waiting, press <tt>Alt-F2</tt> to get another virtual console, and log in again. After all, it's a multi-user, multi-tasking system. Nevertheless these commands will probably flash messages on your screen while they're running; you can type <tt>clear</tt> at the prompt to clear the screen. Once they've run, you might want to look at <tt>/var/mail/root</tt> and <tt>/var/log/messages</tt>. Basically running such commands is part of system administration---and as a single user of a Unix system, you're your own system administrator. Virtually everything you need to be root to do is system administration. Such responsibilities aren't covered very well even in those big fat books on Unix, which seem to devote a lot of space to pulling down menus in windows managers. You might want to get one of the two leading books on systems administration, either Evi Nemeth et.al.'s <em>UNIX System Administration Handbook</em> (Prentice-Hall, 1995, ISBN 0-13-15051-7)---the second edition with the red cover; or Æleen Frisch's <em>Essential System Administration</em> (O'Reilly & Associates, 1993, ISBN 0-937175-80-3). I used Nemeth. <!-- ************************************************************ --> <sect>Editing Text <p>To configure your system, you need to edit text files. Most of them will be in the <tt>/etc</tt> directory; and you'll need to <tt>su</tt> to root to be able to change them. The text editor is <tt>vi</tt>. Before you edit a file, you should probably back it up. Suppose you want to edit <tt>/etc/sysconfig</tt>. You could just use <tt>cd /etc</tt> to get to the <tt>/etc</tt> directory and do: <tscreen> cp sysconfig sysconfig.orig </tscreen> This would copy <tt>sysconfig</tt> to <tt>sysconfig.orig</tt>, and you could later copy <tt>sysconfig.orig</tt> to <tt>sysconfig</tt> to recover the original. But even better would be moving (renaming) and then copying back: <tscreen> mv sysconfig sysconfig.orig<newline> cp sysconfig.orig sysconfig </tscreen> because the <tt>mv</tt> command preserves the original date and owner of the file. You can now edit <tt>sysconfig</tt>. If you want the original back, you'd then <tt>mv sysconfig syconfig.myedit</tt> (assuming you want to preserve your edited version) and then <tscreen> mv sysconfig.orig sysconfig </tscreen> to put things back the way they were. To edit a file, type <tscreen> vi filename </tscreen> Move through the text with the arrow keys. <tt>Esc</tt> (the escape key) puts <tt>vi</tt> in command mode. Here are some commands: <descrip> <tag/<tt>x</tt>/ delete letter the cursor is on <tag/<tt>dd</tt>/ delete the entire line (even if it wraps on the screen) <tag/<tt>i</tt>/ insert text at the cursor <tag/<tt>a</tt>/ insert text after the cursor </descrip> Once you type <tt>i</tt> or <tt>a</tt>, you can enter text. <tt>Esc</tt> puts you back in command mode where you can type <descrip> <tag/<tt>:w</tt>/ to write your changes to disk and continue editing <tag/<tt>:wq</tt>/ to write and quit <tag/<tt>:q!</tt>/ to quit without saving changes <tag><tt>/<em>text</em></tt></tag> to move the cursor to <em>text</em>; <tt>/Enter</tt> (the enter key) to find the next instance of <em>text</em>. <tag/<tt>G</tt>/ to go to the end of the file <tag/<tt><em>n</em>G</tt>/ to go to line <em>n</em> in the file, where <em>n</em> is a number <tag/<tt>Ctrl-L</tt>/ to redraw the screen <tag/<tt>Ctrl-b</tt> and <tt>Ctrl-f</tt>/ go back and forward a screen, as they do with <tt>more</tt> and <tt>view</tt>. </descrip> Practice with <tt>vi</tt> in your home directory by creating a new file with <tt>vi filename</tt> and adding and deleting text, saving the file, and calling it up again. <tt>vi</tt> delivers some surprises because it's really quite complex, and sometimes you'll inadvertently issue a command that will do something you don't expect. (Some people actually like <tt>vi</tt>---it's more powerful than DOS EDIT---find out about the <tt>:r</tt> command.) Use <tt>Esc</tt> one or more times to be sure you're in command mode and proceed from there when it gives you trouble, save often with <tt>:w</tt>, and use <tt>:q!</tt> to get out and start over (from your last <tt>:w</tt>) when you need to. Now you can <tt>cd</tt> to <tt>/etc</tt>, <tt>su</tt> to root, use <tt>vi</tt> to edit the file <tt>/etc/group</tt>, and add a user to wheel so the user has root privileges. Just add a comma and the user's login name to the end of the first line in the file, press <tt>Esc</tt>, and use <tt>:wq</tt> to write the file to disk and quit. Instantly effective. (You didn't put a space after the comma, did you?) <!-- ************************************************************ --> <sect>Printing Files from DOS <p>At this point you probably don't have the printer working, so here's a way to create a file from a man page, move it to a floppy, and then print it from DOS. Suppose you want to read carefully about changing permissions on files (pretty important). You can use the command man chmod to read about it. The command <tscreen> man chmod > chmod.txt </tscreen> will send the man page to the <tt>chmod.txt</tt> file instead of showing it on your screen. Now put a dos-formatted diskette in your floppy drive a, <tt>su</tt> to root, and type <tscreen> /sbin/mount -t msdos /dev/fd0 /mnt </tscreen> to mount the floppy drive on <tt>/mnt</tt>. Now (you no longer need to be root, and you can type <tt>exit</tt> to get back to being user jack) you can go to the directory where you created chmod.txt and copy the file to the floppy with: <tscreen> cp chmod.txt /mnt </tscreen> and use <tt>ls /mnt</tt> to get a directory listing of <tt>/mnt</tt>, which should show the file <tt>chmod.txt</tt>. You might especially want to make a file from <tt>/sbin/dmesg</tt> by typing <tscreen> /sbin/dmesg > dmesg.txt </tscreen> and copying <tt>dmesg.txt</tt> to the floppy. <tt>/sbin/dmesg</tt> is the boot log record, and it's useful to understand it because it shows what FreeBSD found when it booted up. If you ask questions on questions@freebsd.org or on a USENET group---like ``FreeBSD isn't finding my tape drive, what do I do?''---people will want to know what <tt>dmesg</tt> has to say. You can now dismount the floppy drive (as root) to get the disk out with <tscreen> /sbin/umount /mnt </tscreen> or reboot to go to DOS. Copy these files to a DOS directory, call them up with DOS EDIT, Windows Notepad, or a word processor, make a minor change so the file has to be saved, and print as you normally would from DOS or Windows. Hope it works! man pages come out best if printed with the dos <tt>print</tt> command. (Copying files from FreeBSD to a mounted dos partition is in some cases still a little risky.) Getting the printer printing from FreeBSD involves creating an appropriate entry in <tt>/etc/printcap</tt> and creating a matching spool directory in <tt>/var/spool/output</tt>. If your printer is on lpt0 (what dos calls LPT1), you may only need to go to <tt>/var/spool/output</tt> and (as root) create the directory lpd by typing: <tscreen> mkdir lpd </tscreen> Then the printer should respond if it's turned on when the system is booted, and lp or lpr should send a file to the printer. Whether or not the file actually prints depends on configuring it, which is covered in the FreeBSD handbook. <!-- ************************************************************ --> <sect>Other Useful Commands <p><descrip> <tag/<tt>df</tt>/ shows file space and mounted systems. <tag/<tt>ps aux</tt>/ shows processes running. <tt>ps ax</tt> is a narrower form. <tag/<tt>lsdev</tt>/ lists configured devices <tag/<tt>devmenu</tt>/ a menu of devices---in color! <tag/<tt>rm <em>filename</em></tt>/ remove <tt>filename</tt> <tag/<tt>rm -R <em>dir</em></tt>/ removes a directory <tt>dir</tt> and all subdirectories---careful! <tag/<tt>ls -R</tt>/ lists files in the current directory and all subdirectories; I used a variant, <tt>ls -AFR > where.txt</tt>, to get a list of all the files in <tt>/</tt> and (separately) <tt>/usr</tt> before I found better ways to find files. <tag/<tt>passwd</tt>/ to change user's password (or root's password) <tag/<tt>man hier</tt>/ man page on the Unix file system </descrip> Use find to locate filename in <tt>/usr</tt> or any of its subdirectories with <tscreen> find /usr -name "<em>filename</em>" </tscreen> You can use <tt>*</tt> as a wildcard in <tt>"<em>filename</em>"</tt> (which should be in quotes). If you tell find to search in <tt>/</tt> instead of <tt>/usr</tt> it will look for the file(s) -on all mounted file systems, including the cdrom and the dos +on all mounted file systems, including the CDROM and the dos partition. An excellent book that explains Unix commands and utilities is Abrahams & Larson, <em>Unix for the Impatient</em> (2nd ed., Addison-Wesley, 1996). There's also a lot of Unix information on the Internet. Try the <url url="http://www.eecs.nwu.edu/unix.html" name="Unix Reference Desk">. <!-- ************************************************************ --> <sect>Next Steps <p>You should now have the tools you need to get around and edit files, so you can get everything up and running. There is a great deal of information in the FreeBSD handbook (which is probably on your hard drive) and <url url="http://www.freebsd.org" name="FreeBSD's web site">. A wide variety of packages and ports are on the <htmlurl -url="http://www.cdrom.com" name="Walnut Creek"> cdrom as well as +url="http://www.cdrom.com" name="Walnut Creek"> CDROM as well as the web site. The handbook tells you more about how to use them (get the package if it exists, with <tt>pkg_add /cdrom/packages/All/<em>packagename</em></tt>, where <em>packagename</em> is the filename of the package). The cdrom has lists of the packages and ports with brief descriptions in <tt>cdrom/packages/index</tt>, <tt>cdrom/packages/index.txt</tt>, and <tt>cdrom/ports/index</tt>, with fuller descriptions in <tt>/cdrom/ports/*/*/pkg/DESCR</tt>, where the <tt>*</tt>s represent subdirectories of kinds of programs and program names respectively. If you find the handbook too sophisticated (what with <tt>lndir</tt> and all) on installing ports from the cdrom, here's what usually works: Find the port you want, say <tt>kermit</tt>. There will be a directory for it on the cdrom. Copy the subdirectory to <tt>/usr/local</tt> (a good place for software you add that should be available to all users) with: <tscreen> cp -R /cdrom/ports/comm/kermit /usr/local </tscreen> This should result in a <tt>/usr/local/kermit</tt> subdirectory that has all the files that the <tt>kermit</tt> subdirectory on -the cdrom has. +the CDROM has. Next, check <tt>/cdrom/ports/distfiles</tt> for a file with a name that indicates it's the port you want. Copy that file to <tt>/usr/ports/distfiles</tt>. (Create <tt>/usr/ports/distfiles</tt> if it doesn't exist using <em>mkdir</em>.) In the case of <tt>kermit</tt>, there is no distfile. Then <tt>cd</tt> to the subdirectory of <tt>/usr/local/kermit</tt> that has the file Makefile. Type <tscreen> make all install </tscreen> During this process the port will ftp to get any compressed files it needs that it didn't find in <tt>/usr/ports/distfiles</tt>. If you don't have your network running yet and there was no file for the port in <tt>/cdrom/ports/distfiles</tt>, you will have to get the distfile using another machine and copy it to <tt>/usr/ports/distfiles</tt> from a floppy or your dos partition. Read <tt>Makefile</tt> (with <tt>cat</tt> or <tt>more</tt> or <tt>view</tt>) to find out where to go (the master distribution site) to get the file and what its name is. Its name will be truncated when downloaded to DOS, and after you get it into <tt>/usr/ports/distfiles</tt> you'll have to rename it (with the <tt>mv</tt> command) to its original name so it can be found. (Use binary file transfers!) Then go back to <tt>/usr/local/kermit</tt>, find the directory with <tt>Makefile</tt>, and type <tt>make all install</tt>. The other thing that happens when installing ports or packages is that some other program is needed. If the installation stops with a message "can't find unzip" or whatever, you might need to install the package or port for unzip before you continue. Once it's installed type <tt>rehash</tt> to make FreeBSD <tt>reread</tt> the files in the path so it knows what's there. (If you get a lot of "path not found" messages when you use <tt>whereis</tt> or which, you might want to make additions to the list of directories in the path statement in <tt>.cshrc</tt> in your home directory. The path statement in Unix does the same kind of work it does in DOS, except the current directory is not (by default) in the path for security reasons; if the command you want is in the directory you're in, you need to type <tt>./</tt> before the command to make it work; no space after the slash.) You might want to get the most recent version of Netscape from their <url url="ftp://ftp.netscape.com" name="ftp site">. (Netscape -requires the X window sytem.) The version you want is the "unknown +requires the X Window System.) The version you want is the "unknown bsd" version. Just use <tt>gunzip <em>filename</em></tt> and <tt>tar xvf <em>filename</em></tt> on it, move the binary to <tt>/usr/local/bin</tt> or some other place binaries are kept, <tt>rehash</tt>, and then put the following lines in <tt>.cshrc</tt> in each user's home directory or (easier) in <tt>/etc/csh.cshrc</tt>, the system-wide csh start-up file: <tscreen> setenv XKEYSYMDB /usr/X11R6/lib/X11/XKeysymDB<newline> setenv XNLSPATH /usr/X11R6/lib/X11/nls </tscreen> This assumes that the file <tt>XKeysymDB</tt> and the directory <tt>nls</tt> are in <tt>/usr/X11R6/lib/X11</tt>; if they're not, find them and put them there. -If you originally got Netscape as a port using the cdrom (or ftp), +If you originally got Netscape as a port using the CDROM (or ftp), don't replace <tt>/usr/local/bin/netscape</tt> with the new netscape binary; this is just a shell script that sets up the environmental variables for you. Instead rename the new binary to <tt>netscape.bin</tt> and replace the old binary, which is <tt>/usr/local/lib/netscape/netscape.bin</tt>. <!-- ************************************************************ --> <sect>Other -<p>As root, you can dismount the cdrom with <tt>/sbin/umount +<p>As root, you can dismount the CDROM with <tt>/sbin/umount /cdrom</tt>, take it out of the drive, insert another one, and mount it with <tt>/sbin/mount_cd9660 /dev/cd0a /cdrom</tt> -assuming <tt>cd0a</tt> is the device name for your cdrom drive. +assuming <tt>cd0a</tt> is the device name for your CDROM drive. -Using the live file system---the second of FreeBSD's cdrom disks---is +Using the live file system---the second of FreeBSD's CDROM disks---is useful if you've got limited space. You might try using <tt>emacs</tt> or playing games from the cdrom. This involves using <tt>lndir</tt>, which gets installed with the X Window System, to tell the program(s) where to find the necessary files, because they're in the <tt>/cdrom</tt> file system instead of in <tt>/usr</tt> and its subdirectories, which is where they're expected to be. Read <tt>man lndir</tt>. You can delete a user (say, jack) by using the command <tt>vipw</tt> to bring up the <tt>master.passwd</tt> file (do not use vi directly on master.passwd); delete the line for jack and save the file. Then edit <tt>/etc/group</tt>, eliminating jack wherever it appears. Finally, go to <tt>/usr/home</tt> and use <tt>rm -R</tt> jack (to get rid of user jack's home directory files). <!-- ************************************************************ --> <sect>Comments Welcome <p>If you use this guide I'd be interested in knowing where it was unclear and what was left out that you think should be included, and if it was helpful. My thanks to Eugene W. Stark, professor of computer science at SUNY-Stony Brook, and John Fieber for helpful comments. Annelise Anderson <htmlurl url="mailto:andrsn@hoover.stanford.edu" name="<andrsn@hoover.stanford.edu>"> </article> diff --git a/en_US.ISO_8859-1/tutorials/ddwg/ddwg.sgml b/en_US.ISO_8859-1/tutorials/ddwg/ddwg.sgml index a9c40d5c5b..1738fcd42a 100644 --- a/en_US.ISO_8859-1/tutorials/ddwg/ddwg.sgml +++ b/en_US.ISO_8859-1/tutorials/ddwg/ddwg.sgml @@ -1,1128 +1,1128 @@ <!DOCTYPE linuxdoc PUBLIC "-//FreeBSD//DTD linuxdoc//EN"> <!-- ++++++++++++++++++++++++++++++++++++++++++++++++++ ++ file: /home/erich/lib/src/sgml/ddwg.sgml ++ ++ Copyright Eric L. Hernes - Wednesday, August 2, 1995 ++ - ++ $Id: ddwg.sgml,v 1.1.1.1 1996-09-24 17:45:58 jfieber Exp $ + ++ $Id: ddwg.sgml,v 1.2 1996-10-06 20:17:08 jfieber Exp $ ++ ++ Sgml doc for something --> <article> <title>FreeBSD Device Driver Writer's Guide <author>Eric L. Hernes, <tt/erich@rrnet.com/ <date>Wednesday, May 29, 1996 <abstract> This document describes how to add a device driver to FreeBSD. It is <it/not/ intended to be a tutorial on unix device drivers in general. It is intended for device driver authors, familiar with the unix device driver model, to work on FreeBSD. </abstract> <toc> <sect> Overview <p> <it> The FreeBSD kernel is very well documented, unfortunately it's all in `C'. </it> <sect> Types of drivers. <sect1> Character <sect2> Data Structures <p> <tt/struct cdevsw/ Structure <sect2> Entry Points <sect3> d_open() <p> d_open() takes several arguments, the formal list looks something like: <code> int d_open(dev_t dev, int flag, int mode, struct proc *p) </code> d_open() is called on <em/every/ open of the device. <p> The <tt/dev/ argument contains the major and minor number of the device opened. These are available through the macros <tt/major()/ and <tt/minor()/ <p> The <tt/flag/ and <tt/mode/ arguments are as described in the open(2) manual page. It is recommended that you check these for access modes in <sys/fcntl.h> and do what is required. For example if <tt/flag/ is (O_NONBLOCK | O_EXLOCK) the open should fail if either it would block, or exclusive access cannot be granted. <p> The <tt/p/ argument contains all the information about the current process. <sect3> d_close() <p> d_close() takes the same argument list as d_open(): <code> int d_close(dev_t dev , int flag , int mode , struct proc *p) </code> d_close() is only called on the last close of your device (per minor device). For example in the following code fragment, d_open() is called 3 times, but d_close() is called only once. <code> ... fd1=open("/dev/mydev", O_RDONLY); fd2=open("/dev/mydev", O_RDONLY); fd3=open("/dev/mydev", O_RDONLY); ... <useful stuff with fd1, fd2, fd3 here> ... close(fd1); close(fd2); close(fd3); ... </code> The arguments are similar to those described above for d_open(). <sect3> d_read() and d_write() <p> d_read() and d_write take the following argument lists: <code> int d_read(dev_t dev, struct uio *uio, int flat) int d_write(dev_t dev, struct uio *uio, int flat) </code> The d_read() and d_write() entry points are called when read(2) and write(2) are called on your device from user-space. The transfer of data can be handled through the kernel support routine uiomove(). <sect3> d_ioctl() <p> It's argument list is as follows: <code> int d_ioctl(dev_t dev, int cmd, caddr_t arg, int flag, struct proc *p) </code> d_ioctl() is a catch-all for operations which don't make sense in a read/write paradigm. Probably the most famous of all ioctl's is on tty devices, through stty(1). The ioctl entry point is called from ioctl() in sys/kern/sys_generic.c<p> There are four different types of ioctl's which can be implemented. <sys/ioccom.h> contains convenience macros for defining these ioctls. <tt/_IO(g,n)/ for control type operations. &nl; <tt/_IOR(g,n,t)/ for operations that read data from a device. &nl; <tt/_IOW(g,n,t)/ for operations that write data to a device. &nl; <tt/_IOWR(g,n,t)/ for operations that write to a device, and then read data back. &nl; Here <tt/g/ refers to a <em/group/. This is an 8-bit value, typically indicative of the device; for example, 't' is used in tty ioctls. <tt/n/ refers to the number of the ioctl within the group. On SCO, this number alone denotes the ioctl. <tt/t/ is the data type which will get passed to the driver; this gets handed to a sizeof() operator in the kernel. The ioctl() system call will either copyin() or copyout() or both for your driver, then hand you a pointer to the data structure in the <tt/arg/ argument of the d_ioctl call. Currently the data size is limited to one page (4k on the i386). <sect3> d_stop() <sect3> d_reset() <sect3> d_devtotty() <sect3> d_select() <sect3> d_mmap() <sect3> d_strategy() <p> d_strategy()'s argument list is as follows: <code> void d_strategy(struct buf *bp) </code> <p> d_strategy() is used for devices which use some form of scatter-gather io. It is most common in a block device. This is significantly different than the System V model, where only the block driver performs scatter-gather io. Under BSD, character devices are sometimes requested to perform scatter-gather io via the readv() and writev() system calls. <sect2> Header Files <sect1> Block <sect2> Data Structures <p> <tt/struct bdevsw/ Structure <p> <tt/struct buf/ Structure <sect2> Entry Points <sect3> d_open() <p> Described in the Character device section. <sect3> d_close() <p> Described in the Character device section. <sect3> d_strategy() <p> Described in the Character device section. <sect3> d_ioctl() <p> Described in the Character device section. <sect3> d_dump() <sect3> d_psize() <sect2> Header Files <sect1> Network <sect2> Data Structures <p> <tt/struct ifnet/ Structure <sect2> Entry Points <sect3> if_init() <sect3> if_output() <sect3> if_start() <sect3> if_done() <sect3> if_ioctl() <sect3> if_watchdog() <sect2> Header Files <sect1> Line Discipline <sect2> Data Structures <p> <tt/struct linesw/ Structure <sect2> Entry Points <sect3> l_open() <sect3> l_close() <sect3> l_read() <sect3> l_write() <sect3> l_ioctl() <sect3> l_rint() <sect3> l_start() <sect3> l_modem() <sect2> Header Files <sect> Supported Busses <sect1> ISA -- Industry Standard Architecture <sect2> Data Structures <sect3> <tt/struct isa_device/ Structure <p> This structure is required, but generally it is created by config(8) from the kernel configuration file. It is required on a per-device basis, meaning that if you have a driver which controls two serial boards, you will have two isa_device structures. If you build a device as an LKM, you must create your own isa_device structure to reflect your configuration. (lines 85 - 131 in pcaudio_lkm.c) There is nearly a direct mapping between the config file and the isa_device structure. The definition from /usr/src/sys/i386/isa/isa_device.h is: <code> struct isa_device { int id_id; /* device id */ struct isa_driver *id_driver; int id_iobase; /* base i/o address */ u_short id_irq; /* interrupt request */ short id_drq; /* DMA request */ caddr_t id_maddr; /* physical i/o memory address on bus (if any)*/ int id_msize; /* size of i/o memory */ inthand2_t *id_intr; /* interrupt interface routine */ int id_unit; /* unit number */ int id_flags; /* flags */ int id_scsiid; /* scsi id if needed */ int id_alive; /* device is present */ #define RI_FAST 1 /* fast interrupt handler */ u_int id_ri_flags; /* flags for register_intr() */ int id_reconfig; /* hot eject device support (such as PCMCIA) */ int id_enabled; /* is device enabled */ int id_conflicts; /* we're allowed to conflict with things */ struct isa_device *id_next; /* used in isa_devlist in userconfig() */ }; </code> <!-- XXX add stuff here --> <sect3> <tt/struct isa_driver/ Structure <p> This structure is defined in ``/usr/src/sys/i386/isa/isa_device.h''. These are required on a per-driver basis. The definition is: <code> struct isa_driver { int (*probe) __P((struct isa_device *idp)); /* test whether device is present */ int (*attach) __P((struct isa_device *idp)); /* setup driver for a device */ char *name; /* device name */ int sensitive_hw; /* true if other probes confuse us */ }; </code> This is the structure used by the probe/attach code to detect and initialize your device. The <tt/probe/ member is a pointer to your device probe function; the <tt/attach/ member is a pointer to your attach function. The <tt/name/ member is a character pointer to the two or three letter name for your driver. This is the name reported during the probe/attach process (and probably also in lsdev(8)). The <tt/sensitive_hw/ member is a flag which helps the probe code determine probing order. A typical instantiation is: <code> struct isa_driver mcddriver = { mcd_probe, mcd_attach, "mcd" }; </code> <sect2> Entry Points <sect3> probe() <p> probe() takes a <tt/struct isa_device/ pointer as an argument and returns an int. The return value is ``zero'' or ``non-zero'' as to the absence or presence of your device. This entry point may (and probably should) be declared as <tt/static/ because it is accessed via the <tt/probe/ member of the <tt/struct isa_driver/ structure. This function is intended to detect the presence of your device only; it should not do any configuration of the device itself. <sect3> attach() <p> attach() also takes a <tt/struct isa_device/ pointer as an argument and returns an int. The return value is also ``zero'' or ``non-zero'' indicating whether or not the attach was successful. This function is intended to do any special initialization of the device as well as confirm that the device is usable. It too should be declared <tt/static/ because it is accessed through the <tt/attach/ member of the <tt/isa_driver/ structure. <sect2> Header Files <sect1> EISA -- Extended Industry Standard Architecture <sect2> Data Structures <p> <tt/struct eisa_dev/ Structure <p> <tt/struct isa_driver/ Structure <sect2> Entry Points <sect3> probe() <p> Described in the ISA device section. <sect3> attach() <p> Described in the ISA device section. <sect2> Header Files <sect1> PCI -- Peripheral Computer Interconnect <sect2> Data Structures <p> <tt/struct pci_device/ Structure name: The short device name. probe: Checks if the driver can support a device with this type. The tag may be used to get more info with pci_read_conf(). See below. It returns a string with the device's name, or a NULL pointer, if the driver cannot support this device. attach: Allocate a control structure and prepare it. This function may use the PCI mapping functions. See below. (configuration id) or type. count: A pointer to a unit counter. It's used by the PCI configurator to allocate unit numbers. <sect2> Entry Points <sect3> probe() <sect3> attach() <sect3> shutdown() <sect2> Header Files <sect1> SCSI -- Small Computer Systems Interface <sect2> Data Structures <p> <tt/struct scsi_adapter/ Structure <p> <tt/struct scsi_device/ Structure <p> <tt/struct scsi_ctlr_config/ Structure <p> <tt/struct scsi_device_config/ Structure <p> <tt/struct scsi_link/ Structure <sect2> Entry Points <sect3> attach() <sect3> init() <sect2> Header Files <sect1> PCCARD (PCMCIA) <sect2> Data Structures <p> <tt/struct slot_cont/ Structure <p> <tt/struct pccard_drv/ Structure <p> <tt/struct pccard_dev/ Structure <p> <tt/struct slot/ Structure <sect2> Entry Points <sect3> handler() <sect3> unload() <sect3> suspend() <sect3> init() <sect2> Header Files a. <pccard/slot.h> <sect> Linking Into the Kernel. <p> In FreeBSD, support for the ISA and EISA busses is i386 specific. While FreeBSD itself is presently available on the i386 platform, some effort has been made to make the PCI, PCCARD, and SCSI code portable. The ISA and EISA specific code resides in /usr/src/sys/i386/isa and /usr/src/sys/i386/eisa respectively. The machine independent PCI, PCCARD, and SCSI code reside in /usr/src/sys/{pci,pccard,scsi}. The i386 specific code for these reside in /usr/src/sys/i386/{pci,pccard,scsi}. <p> In FreeBSD, a device driver can be either binary or source. There is no ``official'' place for binary drivers to reside. BSD/OS uses something like sys/i386/OBJ. Since most drivers are distributed in source, the following discussion refers to a source driver. Binary only drivers are sometimes provided by hardware vendors who wish to maintain the source as proprietary. <p> A typical driver has the source code in one c-file, say dev.c. The driver also can have some include files; devreg.h typically contains public device register declarations, macros, and other driver specific declarations. Some drivers call this devvar.h instead. Some drivers, such as the dgb (for the Digiboard PC/Xe), require microcode to be loaded onto the board. For the dgb driver the microcode is compiled and dumped into a header file ala file2c(1). <p> If the driver has data structures and ioctl's which are specific to the driver/device, and need to be accessible from user-space, they should be put in a separate include file which will reside in /usr/include/machine/ (some of these reside in /usr/include/sys/). These are typically named something like ioctl_dev.h or devio.h. <p> If a driver is being written which, from user space is identical to a device which already exists, care should be taken to use the same ioctl interface and data structures. For example, from -user space, a SCSI cdrom drive should be identical to an IDE cdrom +user space, a SCSI CDROM drive should be identical to an IDE cdrom drive; or a serial line on an intelligent multiport card (Digiboard, Cyclades, ...) should be identical to the sio devices. These devices have a fairly well defined interface which should be used. <p> There are two methods for linking a driver into the kernel, static and the LKM model. The first method is fairly standard across the *BSD family. The other method was originally developed by Sun (I believe), and has been implemented into BSD using the Sun model. I don't believe that the current implementation uses any Sun code. <sect1> Standard Model <p> The steps required to add your driver to the standard FreeBSD kernel are <itemize> <item> Add to the driver list <item> Add an entry to the [bc]devsw <item> Add the driver entry to the kernel config file <item> config(8), compile, and install the kernel <item> make required nodes. <item> reboot. </itemize> <sect2> Adding to the driver list. <p> The standard model for adding a device driver to the Berkeley kernel is to add your driver to the list of known devices. This list is dependant on the cpu architecture. If the device is not i386 specific (PCCARD, PCI, SCSI), the file is in ``/usr/src/sys/conf/files''. If the device is i386 specific, use ``/usr/src/sys/i386/conf/files.i386''. A typical line looks like: <tscreen><code> i386/isa/joy.c optional joy device-driver </code></tscreen> The first field is the pathname of the driver module relative to /usr/src/sys. For the case of a binary driver the path would be something like ``i386/OBJ/joy.o''. The second field tells config(8) that this is an optional driver. Some devices are required for the kernel to even be built. The third field is the name of the device. The fourth field tells config that it's a device driver (as opposed to just optional). This causes config to create entries for the device in some structures in /usr/src/sys/compile/KERNEL/ioconf.c. It is also possible to create a file ``/usr/src/sys/i386/conf/files.KERNEL'' whose contents will override the default files.i386, but only for the kernel ``KERNEL''. <sect2>Make room in conf.c <p> Now you must edit ``/usr/src/sys/i386/i386/conf.c'' to make an entry for your driver. Somewhere near the top, you need to declare your entry points. The entry for the joystick driver is: <code> #include "joy.h" #if NJOY > 0 d_open_t joyopen; d_close_t joyclose; d_rdwr_t joyread; d_ioctl_t joyioctl; #else #define joyopen nxopen #define joyclose nxclose #define joyread nxread #define joyioctl nxioctl #endif </code> This either defines your entry points, or null entry points which will return ENXIO when called (the #else clause). The include file ``joy.h'' is automatically generated by config(8) when the kernel build tree is created. This usually has only one line like: <code> #define NJOY 1 </code> or <code> #define NJOY 0 </code> which defines the number of your devices in your kernel. You must additionally add a slot to either cdevsw[&rsqb, or to bdevsw[&rsqb, depending on whether it is a character device or a block device, or both if it is a block device with a raw interface. The entry for the joystick driver is: <code> /* open, close, read, write, ioctl, stop, reset, ttys, select, mmap, strat */ struct cdevsw cdevsw[] = { ... { joyopen, joyclose, joyread, nowrite, /*51*/ joyioctl, nostop, nullreset, nodevtotty,/*joystick */ seltrue, nommap, NULL}, ... } </code> Order is what determines the major number of your device. Which is why there will always be an entry for your driver, either null entry points, or actual entry points. It is probably worth noting that this is significantly different from SCO and other system V derivatives, where any device can (in theory) have any major number. This is largely a convenience on FreeBSD, due to the way device nodes are created. More on this later. <sect2>Adding your device to the config file. <p> This is simply adding a line describing your device. The joystick description line is: <verb> device joy0 at isa? port "IO_GAME" </verb> This says we have a device called ``joy0'' on the isa bus using io-port ``IO_GAME'' (IO_GAME is a macro defined in /usr/src/sys/i386/isa/isa.h). A slightly more complicated entry is for the ``ix'' driver: <verb> device ix0 at isa? port 0x300 net irq 10 iomem 0xd0000 iosiz 32768 vector ixintr </verb> This says that we have a device called `ix0' on the ISA bus. It uses io-port 0x300. It's interrupt will be masked with other devices in the network class. It uses interrupt 10. It uses 32k of shared memory at physical address 0xd0000. It also defines it's interrupt handler to be ``ixintr()'' <sect2>config(8) the kernel. <p> Now with our config file in hand, we can create a kernel compile directory. This is done by simply typing: <verb> # config KERNEL </verb> where KERNEL is the name of your config file. Config creates a compile tree for you kernel in /usr/src/sys/compile/KERNEL. It creates the Makefile, some .c files, and some .h files with macros defining the number of each device in your kernel. Now you can go to the compile directory and build. Each time you run config, your previous build tree will be removed, unless you config with a -n. If you have config'ed and compiled a GENERIC kernel, you can ``make links'' to avoid compiling a few files on each iteration. I typically run <verb> # make depend links all </verb> followed by a ``make install'' when the kernel is done to my liking. <sect2>Making device nodes. <p> On FreeBSD, you are responsible for making your own device nodes. The major number of your device is determined by the slot number in the device switch. Minor number is driver dependent, of course. You can either run the mknod's from the command line, or add a section to /dev/MAKEDEV.local, or even /dev/MAKEDEV to do the work. I sometimes create a MAKEDEV.dev script that can be run stand-alone or pasted into /dev/MAKEDEV.local <sect2>Reboot. <p> This is the easy part. There are a number of ways to do this, reboot, fastboot, shutdown -r, cycle the power, etc. Upon bootup you should see your XXprobe() called, and if all is successful, your XXattach() too. <sect1> Loadable Kernel Module (LKM) <p> There are really no defined procedures for writing an LKM driver. The following is my own conception after experimenting with the LKM device interface and looking at the standard device driver model, this is one way of adding an LKM interface to an existing driver without touching the original driver source (or binary). It is recommended though, that if you plan to release source to your driver, the LKM specific parts should be part of the driver itself, conditionally compiled on the LKM macro (i.e. #ifdef LKM). This section will focus on writing the LKM specific part of the driver. We will assume that we have written a driver which will drop into the standard device driver model, which we would now like to implement as an LKM. We will use the pcaudio driver as a sample driver, and develop an LKM front-end. The source and makefile for the pcaudio LKM, ``pcaudio_lkm.c'' and ``Makefile'', should be placed in /usr/src/lkm/pcaudio. What follows is a breakdown of pcaudio_lkm.c. Lines 17 - 26 -- This includes the file ``pca.h'' and conditionally compiles the rest of the LKM on whether or not we have a pcaudio device defined. This mimics the behavior of config. In a standard device driver, config(8) generates the pca.h file from the number pca devices in the config file. <code> 17 /* 18 * figure out how many devices we have.. 19 */ 20 21 #include "pca.h" 22 23 /* 24 * if we have at least one ... 25 */ 26 #if NPCA > 0 </code> Lines 27 - 37 -- Includes required files from various include directories. <code> 27 #include <sys/param.h> 28 #include <sys/systm.h> 29 #include <sys/exec.h> 30 #include <sys/conf.h> 31 #include <sys/sysent.h> 32 #include <sys/lkm.h> 33 #include <sys/errno.h> 34 #include <i386/isa/isa_device.h> 35 #include <i386/isa/isa.h> 36 37 </code> Lines 38 - 51 -- Declares the device driver entry points as external. <code> 38 /* 39 * declare your entry points as externs 40 */ 41 42 extern int pcaprobe(struct isa_device *); 43 extern int pcaattach(struct isa_device *); 44 extern int pcaopen(dev_t, int, int, struct proc *); 45 extern int pcaclose(dev_t, int, int, struct proc *); 46 extern int pcawrite(dev_t, struct uio *, int); 47 extern int pcaioctl(dev_t, int, caddr_t); 48 extern int pcaselect(dev_t, int, struct proc *); 49 extern void pcaintr(struct clockframe *); 50 extern struct isa_driver pcadriver; 51 </code> Lines 52 - 70 -- This is creates the device switch entry table for your driver. This table gets swapped wholesale into the system device switch at the location specified by your major number. In the standard model, these are in /usr/src/sys/i386/i386/conf.c. NOTE: you cannot pick a device major number higher than what exists in conf.c, for example at present, conf.c rev 1.85, there are 67 slots for character devices, you cannot use a (character) major device number 67 or greater, without first reserving space in conf.c. <code> 52 /* 53 * build your device switch entry table 54 */ 55 56 static struct cdevsw pcacdevsw = { 57 (d_open_t *) pcaopen, /* open */ 58 (d_close_t *) pcaclose, /* close */ 59 (d_rdwr_t *) enodev, /* read */ 60 (d_rdwr_t *) pcawrite, /* write */ 61 (d_ioctl_t *) pcaioctl, /* ioctl */ 62 (d_stop_t *) enodev, /* stop?? */ 63 (d_reset_t *) enodev, /* reset */ 64 (d_ttycv_t *) enodev, /* ttys */ 65 (d_select_t *) pcaselect, /* select */ 66 (d_mmap_t *) enodev, /* mmap */ 67 (d_strategy_t *) enodev /* strategy */ 68 }; 69 70 </code> Lines 71 - 131 -- This section is analogous to the config file declaration of your device. The members of the isa_device structure are filled in by what is known about your device, I/O port, shared memory segment, etc. We will probably never have a need for two pcaudio devices in the kernel, but this example shows how multiple devices can be supported. <code> 71 /* 72 * this lkm arbitrarily supports two 73 * instantiations of the pc-audio device. 74 * 75 * this is for illustration purposes 76 * only, it doesn't make much sense 77 * to have two of these beasts... 78 */ 79 80 81 /* 82 * these have a direct correlation to the 83 * config file entries... 84 */ 85 struct isa_device pcadev[NPCA] = { 86 { 87 11, /* device id */ 88 &pcadriver, /* driver pointer */ 89 IO_TIMER1, /* base io address */ 90 -1, /* interrupt */ 91 -1, /* dma channel */ 92 (caddr_t)-1, /* physical io memory */ 93 0, /* size of io memory */ 94 pcaintr , /* interrupt interface */ 95 0, /* unit number */ 96 0, /* flags */ 97 0, /* scsi id */ 98 0, /* is alive */ 99 0, /* flags for register_intr */ 100 0, /* hot eject device support */ 101 1 /* is device enabled */ 102 }, 103 #if NPCA >1 104 { 105 106 /* 107 * these are all zeros, because it doesn't make 108 * much sense to be here 109 * but it may make sense for your device 110 */ 111 112 0, /* device id */ 113 &pcadriver, /* driver pointer */ 114 0, /* base io address */ 115 -1, /* interrupt */ 116 -1, /* dma channel */ 117 -1, /* physical io memory */ 118 0, /* size of io memory */ 119 NULL, /* interrupt interface */ 120 1, /* unit number */ 121 0, /* flags */ 122 0, /* scsi id */ 123 0, /* is alive */ 124 0, /* flags for register_intr */ 125 0, /* hot eject device support */ 126 1 /* is device enabled */ 127 }, 128 #endif 129 130 }; 131 </code> Lines 132 - 139 -- This calls the C-preprocessor macro MOD_DEV, which sets up an LKM device driver, as opposed to an LKM filesystem, or an LKM system call. <code> 132 /* 133 * this macro maps to a funtion which 134 * sets the LKM up for a driver 135 * as opposed to a filesystem, systemcall, or misc 136 * LKM. 137 */ 138 MOD_DEV("pcaudio_mod", LM_DT_CHAR, 24, &pcacdevsw); 139 </code> Lines 140 - 168 -- This is the function which will be called when the driver is loaded. This function tries to work like sys/i386/isa/isa.c which does the probe/attach calls for a driver at boot time. The biggest trick here is that it maps the physical address of the shared memory segment, which is specified in the isa_device structure to a kernel virtual address. Normally the physical address is put in the config file which builds the isa_device structures in /usr/src/sys/compile/KERNEL/ioconf.c. The probe/attach sequence of /usr/src/sys/isa/isa.c translates the physical address to a virtual one so that in your probe/attach routines you can do things like <verb> (int *)id->id_maddr = something; </verb> and just refer to the shared memory segment via pointers. <code> 140 /* 141 * this function is called when the module is 142 * loaded; it tries to mimic the behavior 143 * of the standard probe/attach stuff from 144 * isa.c 145 */ 146 int 147 pcaload(){ 148 int i; 149 uprintf("PC Audio Driver Loaded\n"); 150 for (i=0; i<NPCA; i++){ 151 /* 152 * this maps the shared memory address 153 * from physical to virtual, to be 154 * consistant with the way 155 * /usr/src/sys/i386/isa.c handles it. 156 */ 157 pcadev[i].id_maddr -=0xa0000; 158 pcadev[i].id_maddr += atdevbase; 159 if ((*pcadriver.probe)(pcadev+i)) { 160 (*(pcadriver.attach))(pcadev+i); 161 } else { 162 uprintf("PC Audio Probe Failed\n"); 163 return(1); 164 } 165 } 166 return 0; 167 } 168 </code> Lines 169 - 179 -- This is the function called when your driver is unloaded; it just displays a message to that effect. <code> 169 /* 170 * this function is called 171 * when the module is unloaded 172 */ 173 174 int 175 pcaunload(){ 176 uprintf("PC Audio Driver Unloaded\n"); 177 return 0; 178 } 179 </code> Lines 180 - 190 -- This is the entry point which is specified on the command line of the modload. By convention it is named <dev>_mod. This is how it is defined in bsd.lkm.mk, the makefile which builds the LKM. If you name your module following this convention, you can do ``make load'' and ``make unload'' from /usr/src/lkm/pcaudio. <p> Note: this has gone through <em/many/ revisions from release 2.0 to 2.1. It may or may not be possible to write a module which is portable across all three releases. <p> <code> 180 /* 181 * this is the entry point specified 182 * on the modload command line 183 */ 184 185 int 186 pcaudio_mod(struct lkm_table *lkmtp, int cmd, int ver) 187 { 188 DISPATCH(lkmtp, cmd, ver, pcaload, pcaunload, nosys); 189 } 190 191 #endif /* NICP > 0 */ </code> <sect1> Device Type Idiosyncrasies <sect2> Character <sect2> Block <sect2> Network <sect2> Line Discipline <sect1> Bus Type Idiosyncrasies <sect2> ISA <sect2> EISA <sect2> PCI <sect2> SCSI <sect2> PCCARD <sect> Kernel Support <sect1> Data Structures <sect2> <tt/struct kern_devconf/ Structure <p> This structure contains some information about the state of the device and driver. It is defined in /usr/src/sys/sys/devconf.h as: <code> struct devconf { char dc_name[MAXDEVNAME]; /* name */ char dc_descr[MAXDEVDESCR]; /* description */ int dc_unit; /* unit number */ int dc_number; /* unique id */ char dc_pname[MAXDEVNAME]; /* name of the parent device */ int dc_punit; /* unit number of the parent */ int dc_pnumber; /* unique id of the parent */ struct machdep_devconf dc_md; /* machine-dependent stuff */ enum dc_state dc_state; /* state of the device (see above) */ enum dc_class dc_class; /* type of device (see above) */ size_t dc_datalen; /* length of data */ char dc_data[1]; /* variable-length data */ }; </code> <sect2> <tt/struct proc/ Structure <p> This structure contains all the information about a process. It is defined in /usr/src/sys/sys/proc.h: <code> /* * Description of a process. * * This structure contains the information needed to manage a thread of * control, known in UN*X as a process; it has references to substructures * containing descriptions of things that the process uses, but may share * with related processes. The process structure and the substructures * are always addressable except for those marked "(PROC ONLY)" below, * which might be addressable only on a processor on which the process * is running. */ struct proc { struct proc *p_forw; /* Doubly-linked run/sleep queue. */ struct proc *p_back; struct proc *p_next; /* Linked list of active procs */ struct proc **p_prev; /* and zombies. */ /* substructures: */ struct pcred *p_cred; /* Process owner's identity. */ struct filedesc *p_fd; /* Ptr to open files structure. */ struct pstats *p_stats; /* Accounting/statistics (PROC ONLY). */ struct plimit *p_limit; /* Process limits. */ struct vmspace *p_vmspace; /* Address space. */ struct sigacts *p_sigacts; /* Signal actions, state (PROC ONLY). */ #define p_ucred p_cred->pc_ucred #define p_rlimit p_limit->pl_rlimit int p_flag; /* P_* flags. */ char p_stat; /* S* process status. */ char p_pad1[3]; pid_t p_pid; /* Process identifier. */ struct proc *p_hash; /* Hashed based on p_pid for kill+exit+... */ struct proc *p_pgrpnxt; /* Pointer to next process in process group. */ struct proc *p_pptr; /* Pointer to process structure of parent. */ struct proc *p_osptr; /* Pointer to older sibling processes. */ /* The following fields are all zeroed upon creation in fork. */ #define p_startzero p_ysptr struct proc *p_ysptr; /* Pointer to younger siblings. */ struct proc *p_cptr; /* Pointer to youngest living child. */ pid_t p_oppid; /* Save parent pid during ptrace. XXX */ int p_dupfd; /* Sideways return value from fdopen. XXX */ /* scheduling */ u_int p_estcpu; /* Time averaged value of p_cpticks. */ int p_cpticks; /* Ticks of cpu time. */ fixpt_t p_pctcpu; /* %cpu for this process during p_swtime */ void *p_wchan; /* Sleep address. */ char *p_wmesg; /* Reason for sleep. */ u_int p_swtime; /* Time swapped in or out. */ u_int p_slptime; /* Time since last blocked. */ struct itimerval p_realtimer; /* Alarm timer. */ struct timeval p_rtime; /* Real time. */ u_quad_t p_uticks; /* Statclock hits in user mode. */ u_quad_t p_sticks; /* Statclock hits in system mode. */ u_quad_t p_iticks; /* Statclock hits processing intr. */ int p_traceflag; /* Kernel trace points. */ struct vnode *p_tracep; /* Trace to vnode. */ int p_siglist; /* Signals arrived but not delivered. */ struct vnode *p_textvp; /* Vnode of executable. */ char p_lock; /* Process lock (prevent swap) count. */ char p_pad2[3]; /* alignment */ /* End area that is zeroed on creation. */ #define p_endzero p_startcopy /* The following fields are all copied upon creation in fork. */ #define p_startcopy p_sigmask sigset_t p_sigmask; /* Current signal mask. */ sigset_t p_sigignore; /* Signals being ignored. */ sigset_t p_sigcatch; /* Signals being caught by user. */ u_char p_priority; /* Process priority. */ u_char p_usrpri; /* User-priority based on p_cpu and p_nice. */ char p_nice; /* Process "nice" value. */ char p_comm[MAXCOMLEN+1]; struct pgrp *p_pgrp; /* Pointer to process group. */ struct sysentvec *p_sysent; /* System call dispatch information. */ struct rtprio p_rtprio; /* Realtime priority. */ /* End area that is copied on creation. */ #define p_endcopy p_addr struct user *p_addr; /* Kernel virtual addr of u-area (PROC ONLY). */ struct mdproc p_md; /* Any machine-dependent fields. */ u_short p_xstat; /* Exit status for wait; also stop signal. */ u_short p_acflag; /* Accounting flags. */ struct rusage *p_ru; /* Exit information. XXX */ }; </code> <sect2> <tt/struct buf/ Structure <p> The <tt/struct buf/ structure is used to interface with the buffer cache. It is defined in /usr/src/sys/sys/buf.h: <code> /* * The buffer header describes an I/O operation in the kernel. */ struct buf { LIST_ENTRY(buf) b_hash; /* Hash chain. */ LIST_ENTRY(buf) b_vnbufs; /* Buffer's associated vnode. */ TAILQ_ENTRY(buf) b_freelist; /* Free list position if not active. */ struct buf *b_actf, **b_actb; /* Device driver queue when active. */ struct proc *b_proc; /* Associated proc; NULL if kernel. */ volatile long b_flags; /* B_* flags. */ int b_qindex; /* buffer queue index */ int b_error; /* Errno value. */ long b_bufsize; /* Allocated buffer size. */ long b_bcount; /* Valid bytes in buffer. */ long b_resid; /* Remaining I/O. */ dev_t b_dev; /* Device associated with buffer. */ struct { caddr_t b_addr; /* Memory, superblocks, indirect etc. */ } b_un; void *b_saveaddr; /* Original b_addr for physio. */ daddr_t b_lblkno; /* Logical block number. */ daddr_t b_blkno; /* Underlying physical block number. */ /* Function to call upon completion. */ void (*b_iodone) __P((struct buf *)); /* For nested b_iodone's. */ struct iodone_chain *b_iodone_chain; struct vnode *b_vp; /* Device vnode. */ int b_pfcent; /* Center page when swapping cluster. */ int b_dirtyoff; /* Offset in buffer of dirty region. */ int b_dirtyend; /* Offset of end of dirty region. */ struct ucred *b_rcred; /* Read credentials reference. */ struct ucred *b_wcred; /* Write credentials reference. */ int b_validoff; /* Offset in buffer of valid region. */ int b_validend; /* Offset of end of valid region. */ daddr_t b_pblkno; /* physical block number */ caddr_t b_savekva; /* saved kva for transfer while bouncing */ void *b_driver1; /* for private use by the driver */ void *b_driver2; /* for private use by the driver */ void *b_spc; struct vm_page *b_pages[(MAXPHYS + PAGE_SIZE - 1)/PAGE_SIZE]; int b_npages; }; </code> <sect2> <tt/struct uio/ Structure <p> This structure is used for moving data between the kernel and user spaces through read() and write() system calls. It is defined in /usr/src/sys/sys/uio.h: <code> struct uio { struct iovec *uio_iov; int uio_iovcnt; off_t uio_offset; int uio_resid; enum uio_seg uio_segflg; enum uio_rw uio_rw; struct proc *uio_procp; }; </code> <sect1> Functions lots of 'em <sect> References. <p> FreeBSD Kernel Sources http://www.freebsd.org <p> NetBSD Kernel Sources http://www.netbsd.org <p> Writing Device Drivers: Tutorial and Reference; Tim Burke, Mark A. Parenti, Al, Wojtas; Digital Press, ISBN 1-55558-141-2. <p> Writing A Unix Device Driver; Janet I. Egan, Thomas J. Teixeira; John Wiley & Sons, ISBN 0-471-62859-X. <p> Writing Device Drivers for SCO Unix; Peter Kettle; </article>