FreeBSD Architecture Handbook

The FreeBSD Documentation Project

Welcome to the FreeBSD Architecture Handbook. This manual is a work in progress and is the work of many individuals. Many sections do not yet exist and some of those that do exist need to be updated. If you are interested in helping with this project, send email to the FreeBSD documentation project mailing list.

The latest version of this document is always available from the FreeBSD World Wide Web server. It may also be downloaded in a variety of formats and compression options from the FreeBSD FTP server or one of the numerous mirror sites.

FreeBSD is a registered trademark of The FreeBSD Foundation.

UNIX is a registered trademark of The Open Group in the US and other countries.

Sun, Sun Microsystems, SunOS, Solaris, and Java are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

Apple and QuickTime are trademarks of Apple Computer, Inc., registered in the U.S. and other countries.

Macromedia and Flash are trademarks or registered trademarks of Macromedia, Inc. in the United States and/or other countries.

Microsoft, Windows, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

PartitionMagic is a registered trademark of PowerQuest Corporation in the United States and/or other countries.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the FreeBSD Project was aware of the trademark claim, the designations have been followed by the '™' symbol.

Redistribution and use in source (SGML DocBook) and 'compiled' forms (SGML, HTML, PDF, PostScript, RTF and so forth) with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code (SGML DocBook) must retain the above copyright notice, this list of conditions and the following disclaimer as the first lines of this file unmodified.

  2. Redistributions in compiled form (transformed to other DTDs, converted to PDF, PostScript, RTF and other formats) must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Important: THIS DOCUMENTATION IS PROVIDED BY THE FREEBSD DOCUMENTATION PROJECT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD DOCUMENTATION PROJECT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


Table of Contents
I. Kernel
1 Bootstrapping and kernel initialization
1.1 Synopsis
1.2 Overview
1.3 BIOS POST
1.4 boot0 stage
1.5 boot2 stage
1.6 loader stage
1.7 Kernel initialization
2 Locking Notes
2.1 Mutexes
2.2 Shared Exclusive Locks
2.3 Atomically Protected Variables
3 Kernel Objects
3.1 Terminology
3.2 Kobj Operation
3.3 Using Kobj
4 The Jail Subsystem
4.1 Architecture
4.2 Restrictions
5 The SYSINIT Framework
5.1 Terminology
5.2 SYSINIT Operation
5.3 Using SYSINIT
6 The TrustedBSD MAC Framework
6.1 MAC Documentation Copyright
6.2 Synopsis
6.3 Introduction
6.4 Policy Background
6.5 MAC Framework Kernel Architecture
6.6 MAC Policy Architecture
6.7 MAC Policy Entry Point Reference
6.8 Userland Architecture
6.9 Conclusion
7 Virtual Memory System
7.1 Management of physical memory--vm_page_t
7.2 The unified buffer cache--vm_object_t
7.3 Filesystem I/O--struct buf
7.4 Mapping Page Tables--vm_map_t, vm_entry_t
7.5 KVM Memory Mapping
7.6 Tuning the FreeBSD VM system
8 SMPng Design Document
8.1 Introduction
8.2 Basic Tools and Locking Fundamentals
8.3 General Architecture and Design
8.4 Specific Locking Strategies
8.5 Implementation Notes
8.6 Miscellaneous Topics
Glossary
II. Device Drivers
9 Writing FreeBSD Device Drivers
9.1 Introduction
9.2 Dynamic Kernel Linker Facility - KLD
9.3 Accessing a device driver
9.4 Character Devices
9.5 Block Devices (Are Gone)
9.6 Network Drivers
10 ISA device drivers
10.1 Synopsis
10.2 Basic information
10.3 Device_t pointer
10.4 Configuration file and the order of identifying and probing during auto-configuration
10.5 Resources
10.6 Bus memory mapping
10.7 DMA
10.8 xxx_isa_probe
10.9 xxx_isa_attach
10.10 xxx_isa_detach
10.11 xxx_isa_shutdown
10.12 xxx_intr
11 PCI Devices
11.1 Probe and Attach
11.2 Bus Resources
12 Common Access Method SCSI Controllers
12.1 Synopsis
12.2 General architecture
12.3 Polling
12.4 Asynchronous Events
12.5 Interrupts
12.6 Errors Summary
12.7 Timeout Handling
13 USB Devices
13.1 Introduction
13.2 Host Controllers
13.3 USB Device Information
13.4 Device probe and attach
13.5 USB Drivers Protocol Information
14 Newbus
14.1 Device Drivers
14.2 Overview of Newbus
14.3 Newbus API
15 Sound subsystem
15.1 Introduction
15.2 Files
15.3 Probing, attaching, etc.
15.4 Interfaces
16 PC Card
16.1 Adding a device
III. Appendices
Bibliography
Index
List of Tables
2-1. Mutex List
2-2. Shared Exclusive Lock List
List of Figures
14-1. driver_t implementation
14-2. Device statesdevice_state_t
List of Examples
5-1. Example of a SYSINIT()
5-2. Example of Adjusting SYSINIT() Order
5-3. Example of a SYSUNINIT()
9-1. Example of a Sample Echo Pseudo-Device Driver for FreeBSD 4.X
9-2. Example of a Sample Echo Pseudo-Device Driver for FreeBSD 5.X
14-1. Newbus Methods

Chapter 1 Bootstrapping and kernel initialization

Contributed by Sergey Lyubka.

1.1 Synopsis

This chapter is an overview of the boot and system initialization process, starting from the BIOS (firmware) POST, to the first user process creation. Since the initial steps of system startup are very architecture dependent, the IA-32 architecture is used as an example.


1.2 Overview

A computer running FreeBSD can boot by several methods, although the most common method, booting from a harddisk where the OS is installed, will be discussed here. The boot process is divided into several steps:

  • BIOS POST

  • boot0 stage

  • boot2 stage

  • loader stage

  • kernel initialization

The boot0 and boot2 stages are also referred to as bootstrap stages 1 and 2 in boot(8) as the first steps in FreeBSD's 3-stage bootstrapping procedure. Various information is printed on the screen at each stage, so you may visually recognize them using the table that follows. Please note that the actual data may differ from machine to machine:

may vary

BIOS (firmware) messages

F1    FreeBSD
F2    BSD
F5    Disk 2


boot0

>>FreeBSD/i386 BOOT
Default: 1:ad(1,a)/boot/loader
boot:


boot2a

BTX loader 1.0 BTX version is 1.01
BIOS drive A: is disk0
BIOS drive C: is disk1
BIOS 639kB/64512kB available memory
FreeBSD/i386 bootstrap loader, Revision 0.8
Console internal video/keyboard
(jkh@bento.freebsd.org, Mon Nov 20 11:41:23 GMT 2000)
/kernel text=0x1234 data=0x2345 syms=[0x4+0x3456]
Hit [Enter] to boot immediately, or any other key for command prompt
Booting [kernel] in 9 seconds..._


loader

Copyright (c) 1992-2002 The FreeBSD Project.
Copyright (c) 1979, 1980, 1983, 1986, 1988, 1989, 1991, 1992, 1993, 1994
        The Regents of the University of California. All rights reserved.
FreeBSD 4.6-RC #0: Sat May  4 22:49:02 GMT 2002
    devnull@kukas:/usr/obj/usr/src/sys/DEVNULL
Timecounter "i8254"  frequency 1193182 Hz


kernel

Notes:
a. This prompt will appear if the user presses a key just after selecting an OS to boot at the boot0 stage.

1.3 BIOS POST

When the PC powers on, the processor's registers are set to some predefined values. One of the registers is the instruction pointer register, and its value after a power on is well defined: it is a 32-bit value of 0xfffffff0. The instruction pointer register points to code to be executed by the processor. One of the registers is the cr1 32-bit control register, and its value just after the reboot is 0. One of the cr1's bits, the bit PE (Protected Enabled) indicates whether the processor is running in protected or real mode. Since at boot time this bit is cleared, the processor boots in real mode. Real mode means, among other things, that linear and physical addresses are identical.

The value of 0xfffffff0 is slightly less then 4Gb, so unless the machine has 4Gb physical memory, it cannot point to a valid memory address. The computer's hardware translates this address so that it points to a BIOS memory block.

BIOS stands for Basic Input Output System, and it is a chip on the motherboard that has a relatively small amount of read-only memory (ROM). This memory contains various low-level routines that are specific to the hardware supplied with the motherboard. So, the processor will first jump to the address 0xfffffff0, which really resides in the BIOS's memory. Usually this address contains a jump instruction to the BIOS's POST routines.

POST stands for Power On Self Test. This is a set of routines including the memory check, system bus check and other low-level stuff so that the CPU can initialize the computer properly. The important step on this stage is determining the boot device. All modern BIOS's allow the boot device to be set manually, so you can boot from a floppy, CD-ROM, harddisk etc.

The very last thing in the POST is the INT 0x19 instruction. That instruction reads 512 bytes from the first sector of boot device into the memory at address 0x7c00. The term first sector originates from harddrive architecture, where the magnetic plate is divided to a number of cylindrical tracks. Tracks are numbered, and every track is divided by a number (usually 64) sectors. Track number 0 is the outermost on the magnetic plate, and sector 1, the first sector (tracks, or, cylinders, are numbered starting from 0, but sectors - starting from 1), has a special meaning. It is also called Master Boot Record, or MBR. The remaining sectors on the first track are never used [1].


1.4 boot0 stage

Take a look at the file /boot/boot0. This is a small 512-byte file, and it is exactly what FreeBSD's installation procedure wrote to your harddisk's MBR if you chose the “bootmanager” option at installation time.

As mentioned previously, the INT 0x19 instruction loads an MBR, i.e. the boot0 content, into the memory at address 0x7c00. Taking a look at the file sys/boot/i386/boot0/boot0.s can give a guess at what is happening there - this is the boot manager, which is an awesome piece of code written by Robert Nordier.

The MBR, or, boot0, has a special structure starting from offset 0x1be, called the partition table. It has 4 records of 16 bytes each, called partition records, which represent how the harddisk(s) are partitioned, or, in FreeBSD's terminology, sliced. One byte of those 16 says whether a partition (slice) is bootable or not. Exactly one record must have that flag set, otherwise boot0's code will refuse to proceed.

A partition record has the following fields:

  • the 1-byte filesystem type

  • the 1-byte bootable flag

  • the 6 byte descriptor in CHS format

  • the 8 byte descriptor in LBA format

A partition record descriptor has the information about where exactly the partition resides on the drive. Both descriptors, LBA and CHS, describe the same information, but in different ways: LBA (Logical Block Addressing) has the starting sector for the partition and the partition's length, while CHS (Cylinder Head Sector) has coordinates for the first and last sectors of the partition.

The boot manager scans the partition table and prints the menu on the screen so the user can select what disk and what slice to boot. By pressing an appropriate key, boot0 performs the following actions:

  • modifies the bootable flag for the selected partition to make it bootable, and clears the previous

  • saves itself to disk to remember what partition (slice) has been selected so to use it as the default on the next boot

  • loads the first sector of the selected partition (slice) into memory and jumps there

What kind of data should reside on the very first sector of a bootable partition (slice), in our case, a FreeBSD slice? As you may have already guessed, it is boot2.


1.5 boot2 stage

You might wonder, why boot2 comes after boot0, and not boot1. Actually, there is a 512-byte file called boot1 in the directory /boot as well. It is used for booting from a floppy. When booting from a floppy, boot1 plays the same role as boot0 for a harddisk: it locates boot2 and runs it.

You may have realized that a file /boot/mbr exists as well. It is a simplified version of boot0. The code in mbr does not provide a menu for the user, it just blindly boots the partition marked active.

The code implementing boot2 resides in sys/boot/i386/boot2/, and the executable itself is in /boot. The files boot0 and boot2 that are in /boot are not used by the bootstrap, but by utilities such as boot0cfg. The actual position for boot0 is in the MBR. For boot2 it is the beginning of a bootable FreeBSD slice. These locations are not under the filesystem's control, so they are invisible to commands like ls.

The main task for boot2 is to load the file /boot/loader, which is the third stage in the bootstrapping procedure. The code in boot2 cannot use any services like open() and read(), since the kernel is not yet loaded. It must scan the harddisk, knowing about the filesystem structure, find the file /boot/loader, read it into memory using a BIOS service, and then pass the execution to the loader's entry point.

Besides that, boot2 prompts for user input so the loader can be booted from different disk, unit, slice and partition.

The boot2 binary is created in special way:

sys/boot/i386/boot2/Makefile
boot2: boot2.ldr boot2.bin ${BTX}/btx/btx
    btxld -v -E ${ORG2} -f bin -b ${BTX}/btx/btx -l boot2.ldr \
        -o boot2.ld -P 1 boot2.bin

This Makefile snippet shows that btxld(8) is used to link the binary. BTX, which stands for BooT eXtender, is a piece of code that provides a protected mode environment for the program, called the client, that it is linked with. So boot2 is a BTX client, i.e. it uses the service provided by BTX.

The btxld utility is the linker. It links two binaries together. The difference between btxld(8) and ld(1) is that ld usually links object files into a shared object or executable, while btxld links an object file with the BTX, producing the binary file suitable to be put on the beginning of the partition for the system boot.

boot0 passes the execution to BTX's entry point. BTX then switches the processor to protected mode, and prepares a simple environment before calling the client. This includes:

  • virtual v86 mode. That means, the BTX is a v86 monitor. Real mode instructions like pushf, popf, cli, sti, if called by the client, will work.

  • Interrupt Descriptor Table (IDT) is set up so all hardware interrupts are routed to the default BIOS's handlers, and interrupt 0x30 is set up to be the syscall gate.

  • Two system calls: exec and exit, are defined:

    sys/boot/i386/btx/lib/btxsys.s:
            .set INT_SYS,0x30       # Interrupt number
    #
    # System call: exit
    #
    __exit:     xorl %eax,%eax          # BTX system
            int $INT_SYS            #  call 0x0
    #
    # System call: exec
    #
    __exec:     movl $0x1,%eax          # BTX system
            int $INT_SYS            #  call 0x1
    

BTX creates a Global Descriptor Table (GDT):

sys/boot/i386/btx/btx/btx.s:
gdt:        .word 0x0,0x0,0x0,0x0       # Null entry
        .word 0xffff,0x0,0x9a00,0xcf    # SEL_SCODE
        .word 0xffff,0x0,0x9200,0xcf    # SEL_SDATA
        .word 0xffff,0x0,0x9a00,0x0 # SEL_RCODE
        .word 0xffff,0x0,0x9200,0x0 # SEL_RDATA
        .word 0xffff,MEM_USR,0xfa00,0xcf# SEL_UCODE
        .word 0xffff,MEM_USR,0xf200,0xcf# SEL_UDATA
        .word _TSSLM,MEM_TSS,0x8900,0x0 # SEL_TSS

The client's code and data start from address MEM_USR (0xa000), and a selector (SEL_UCODE) points to the client's code segment. The SEL_UCODE descriptor has Descriptor Privilege Level (DPL) 3, which is the lowest privilege level. But the INT 0x30 instruction handler resides in a segment pointed to by the SEL_SCODE (supervisor code) selector, as shown from the code that creates an IDT:

       mov $SEL_SCODE,%dh      # Segment selector
init.2:     shr %bx             # Handle this int?
        jnc init.3          # No
        mov %ax,(%di)           # Set handler offset
        mov %dh,0x2(%di)        #  and selector
        mov %dl,0x5(%di)        # Set P:DPL:type
        add $0x4,%ax            # Next handler

So, when the client calls __exec(), the code will be executed with the highest privileges. This allows the kernel to change the protected mode data structures, such as page tables, GDT, IDT, etc later, if needed.

boot2 defines an important structure, struct bootinfo. This structure is initialized by boot2 and passed to the loader, and then further to the kernel. Some nodes of this structures are set by boot2, the rest by the loader. This structure, among other information, contains the kernel filename, BIOS harddisk geometry, BIOS drive number for boot device, physical memory available, envp pointer etc. The definition for it is:

/usr/include/machine/bootinfo.h
struct bootinfo {
    u_int32_t   bi_version;
    u_int32_t   bi_kernelname;      /* represents a char * */
    u_int32_t   bi_nfs_diskless;    /* struct nfs_diskless * */
                /* End of fields that are always present. */
#define bi_endcommon    bi_n_bios_used
    u_int32_t   bi_n_bios_used;
    u_int32_t   bi_bios_geom[N_BIOS_GEOM];
    u_int32_t   bi_size;
    u_int8_t    bi_memsizes_valid;
    u_int8_t    bi_bios_dev;        /* bootdev BIOS unit number */
    u_int8_t    bi_pad[2];
    u_int32_t   bi_basemem;
    u_int32_t   bi_extmem;
    u_int32_t   bi_symtab;      /* struct symtab * */
    u_int32_t   bi_esymtab;     /* struct symtab * */
                /* Items below only from advanced bootloader */
    u_int32_t   bi_kernend;     /* end of kernel space */
    u_int32_t   bi_envp;        /* environment */
    u_int32_t   bi_modulep;     /* preloaded modules */
};

boot2 enters into an infinite loop waiting for user input, then calls load(). If the user does not press anything, the loop breaks by a timeout, so load() will load the default file (/boot/loader). Functions ino_t lookup(char *filename) and int xfsread(ino_t inode, void *buf, size_t nbyte) are used to read the content of a file into memory. /boot/loader is an ELF binary, but where the ELF header is prepended with a.out's struct exec structure. load() scans the loader's ELF header, loading the content of /boot/loader into memory, and passing the execution to the loader's entry:

sys/boot/i386/boot2/boot2.c:
    __exec((caddr_t)addr, RB_BOOTINFO | (opts & RBX_MASK),
       MAKEBOOTDEV(dev_maj[dsk.type], 0, dsk.slice, dsk.unit, dsk.part),
       0, 0, 0, VTOP(&bootinfo));

1.6 loader stage

loader is a BTX client as well. I will not describe it here in detail, there is a comprehensive manpage written by Mike Smith, loader(8). The underlying mechanisms and BTX were discussed above.

The main task for the loader is to boot the kernel. When the kernel is loaded into memory, it is being called by the loader:

sys/boot/common/boot.c:
    /* Call the exec handler from the loader matching the kernel */
    module_formats[km->m_loader]->l_exec(km);

1.7 Kernel initialization

Let us take a look at the command that links the kernel. This will help us identify the exact location where the loader passes execution to the kernel. This location is the kernel's actual entry point.

sys/conf/Makefile.i386:
ld -elf -Bdynamic -T /usr/src/sys/conf/ldscript.i386  -export-dynamic \
-dynamic-linker /red/herring -o kernel -X locore.o \
<lots of kernel .o files>

A few interesting things can be seen in this line. First, the kernel is an ELF dynamically linked binary, but the dynamic linker for kernel is /red/herring, which is definitely a bogus file. Second, taking a look at the file sys/conf/ldscript.i386 gives an idea about what ld options are used when compiling a kernel. Reading through the first few lines, the string

sys/conf/ldscript.i386:
ENTRY(btext)

says that a kernel's entry point is the symbol `btext'. This symbol is defined in locore.s:

sys/i386/i386/locore.s:
    .text
/**********************************************************************
 *
 * This is where the bootblocks start us, set the ball rolling...
 *
 */
NON_GPROF_ENTRY(btext)

First what is done is the register EFLAGS is set to a predefined value of 0x00000002, and then all the segment registers are initialized:

sys/i386/i386/locore.s
/* Don't trust what the BIOS gives for eflags. */
    pushl   $PSL_KERNEL
    popfl

/*
 * Don't trust what the BIOS gives for %fs and %gs.  Trust the bootstrap
 * to set %cs, %ds, %es and %ss.
 */
    mov %ds, %ax
    mov %ax, %fs
    mov %ax, %gs

btext calls the routines recover_bootinfo(), identify_cpu(), create_pagetables(), which are also defined in locore.s. Here is a description of what they do:

recover_bootinfo This routine parses the parameters to the kernel passed from the bootstrap. The kernel may have been booted in 3 ways: by the loader, described above, by the old disk boot blocks, and by the old diskless boot procedure. This function determines the booting method, and stores the struct bootinfo structure into the kernel memory.
identify_cpu This functions tries to find out what CPU it is running on, storing the value found in a variable _cpu.
create_pagetables This function allocates and fills out a Page Table Directory at the top of the kernel memory area.

The next steps are enabling VME, if the CPU supports it:

   testl   $CPUID_VME, R(_cpu_feature)
    jz  1f
    movl    %cr4, %eax
    orl $CR4_VME, %eax
    movl    %eax, %cr4

Then, enabling paging:

/* Now enable paging */
    movl    R(_IdlePTD), %eax
    movl    %eax,%cr3           /* load ptd addr into mmu */
    movl    %cr0,%eax           /* get control word */
    orl $CR0_PE|CR0_PG,%eax     /* enable paging */
    movl    %eax,%cr0           /* and let's page NOW! */

The next three lines of code are because the paging was set, so the jump is needed to continue the execution in virtualized address space:

   pushl   $begin              /* jump to high virtualized address */
    ret

/* now running relocated at KERNBASE where the system is linked to run */
begin:

The function init386() is called, with a pointer to the first free physical page, after that mi_startup(). init386 is an architecture dependent initialization function, and mi_startup() is an architecture independent one (the 'mi_' prefix stands for Machine Independent). The kernel never returns from mi_startup(), and by calling it, the kernel finishes booting:

sys/i386/i386/locore.s:
    movl    physfree, %esi
    pushl   %esi                /* value of first for init386(first) */
    call    _init386            /* wire 386 chip for unix operation */
    call    _mi_startup         /* autoconfiguration, mountroot etc */
    hlt     /* never returns to here */

1.7.1 init386()

init386() is defined in sys/i386/i386/machdep.c and performs low-level initialization, specific to the i386 chip. The switch to protected mode was performed by the loader. The loader has created the very first task, in which the kernel continues to operate. Before running straight away to the code, I will enumerate the tasks the processor must complete to initialize protected mode execution:

  • Initialize the kernel tunable parameters, passed from the bootstrapping program.

  • Prepare the GDT.

  • Prepare the IDT.

  • Initialize the system console.

  • Initialize the DDB, if it is compiled into kernel.

  • Initialize the TSS.

  • Prepare the LDT.

  • Set up proc0's pcb.

What init386() first does is initialize the tunable parameters passed from bootstrap. This is done by setting the environment pointer (envp) and calling init_param1(). The envp pointer has been passed from loader in the bootinfo structure:

sys/i386/i386/machdep.c:
        kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;

    /* Init basic tunables, hz etc */
    init_param1();

init_param1() is defined in sys/kern/subr_param.c. That file has a number of sysctls, and two functions, init_param1() and init_param2(), that are called from init386():

sys/kern/subr_param.c
    hz = HZ;
    TUNABLE_INT_FETCH("kern.hz", &hz);

TUNABLE_<typename>_FETCH is used to fetch the value from the environment:

/usr/src/sys/sys/kernel.h
#define TUNABLE_INT_FETCH(path, var)    getenv_int((path), (var))

Sysctl kern.hz is the system clock tick. Along with this, the following sysctls are set by init_param1(): kern.maxswzone, kern.maxbcache, kern.maxtsiz, kern.dfldsiz, kern.maxdsiz, kern.dflssiz, kern.maxssiz, kern.sgrowsiz.

Then init386() prepares the Global Descriptors Table (GDT). Every task on an x86 is running in its own virtual address space, and this space is addressed by a segment:offset pair. Say, for instance, the current instruction to be executed by the processor lies at CS:EIP, then the linear virtual address for that instruction would be “the virtual address of code segment CS” + EIP. For convenience, segments begin at virtual address 0 and end at a 4Gb boundary. Therefore, the instruction's linear virtual address for this example would just be the value of EIP. Segment registers such as CS, DS etc are the selectors, i.e. indexes, into GDT (to be more precise, an index is not a selector itself, but the INDEX field of a selector). FreeBSD's GDT holds descriptors for 15 selectors per CPU:

sys/i386/i386/machdep.c:
union descriptor gdt[NGDT * MAXCPU];    /* global descriptor table */

sys/i386/include/segments.h:
/*
 * Entries in the Global Descriptor Table (GDT)
 */
#define GNULL_SEL   0   /* Null Descriptor */
#define GCODE_SEL   1   /* Kernel Code Descriptor */
#define GDATA_SEL   2   /* Kernel Data Descriptor */
#define GPRIV_SEL   3   /* SMP Per-Processor Private Data */
#define GPROC0_SEL  4   /* Task state process slot zero and up */
#define GLDT_SEL    5   /* LDT - eventually one per process */
#define GUSERLDT_SEL    6   /* User LDT */
#define GTGATE_SEL  7   /* Process task switch gate */
#define GBIOSLOWMEM_SEL 8   /* BIOS low memory access (must be entry 8) */
#define GPANIC_SEL  9   /* Task state to consider panic from */
#define GBIOSCODE32_SEL 10  /* BIOS interface (32bit Code) */
#define GBIOSCODE16_SEL 11  /* BIOS interface (16bit Code) */
#define GBIOSDATA_SEL   12  /* BIOS interface (Data) */
#define GBIOSUTIL_SEL   13  /* BIOS interface (Utility) */
#define GBIOSARGS_SEL   14  /* BIOS interface (Arguments) */

Note that those #defines are not selectors themselves, but just a field INDEX of a selector, so they are exactly the indices of the GDT. for example, an actual selector for the kernel code (GCODE_SEL) has the value 0x08.

The next step is to initialize the Interrupt Descriptor Table (IDT). This table is to be referenced by the processor when a software or hardware interrupt occurs. For example, to make a system call, user application issues the INT 0x80 instruction. This is a software interrupt, so the processor's hardware looks up a record with index 0x80 in the IDT. This record points to the routine that handles this interrupt, in this particular case, this will be the kernel's syscall gate. The IDT may have a maximum of 256 (0x100) records. The kernel allocates NIDT records for the IDT, where NIDT is the maximum (256):

sys/i386/i386/machdep.c:
static struct gate_descriptor idt0[NIDT];
struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */

For each interrupt, an appropriate handler is set. The syscall gate for INT 0x80 is set as well:

sys/i386/i386/machdep.c:
    setidt(0x80, &IDTVEC(int0x80_syscall),
            SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));

So when a userland application issues the INT 0x80 instruction, control will transfer to the function _Xint0x80_syscall, which is in the kernel code segment and will be executed with supervisor privileges.

Console and DDB are then initialized:

sys/i386/i386/machdep.c:
    cninit();
/* skipped */
#ifdef DDB
    kdb_init();
    if (boothowto & RB_KDB)
        Debugger("Boot flags requested debugger");
#endif

The Task State Segment is another x86 protected mode structure, the TSS is used by the hardware to store task information when a task switch occurs.

The Local Descriptors Table is used to reference userland code and data. Several selectors are defined to point to the LDT, they are the system call gates and the user code and data selectors:

/usr/include/machine/segments.h
#define LSYS5CALLS_SEL  0   /* forced by intel BCS */
#define LSYS5SIGR_SEL   1
#define L43BSDCALLS_SEL 2   /* notyet */
#define LUCODE_SEL  3
#define LSOL26CALLS_SEL 4   /* Solaris >= 2.6 system call gate */
#define LUDATA_SEL  5
/* separate stack, es,fs,gs sels ? */
/* #define  LPOSIXCALLS_SEL 5*/ /* notyet */
#define LBSDICALLS_SEL  16  /* BSDI system call gate */
#define NLDT        (LBSDICALLS_SEL + 1)

Next, proc0's Process Control Block (struct pcb) structure is initialized. proc0 is a struct proc structure that describes a kernel process. It is always present while the kernel is running, therefore it is declared as global:

sys/kern/kern_init.c:
    struct  proc proc0;

The structure struct pcb is a part of a proc structure. It is defined in /usr/include/machine/pcb.h and has a process's information specific to the i386 architecture, such as registers values.


1.7.2 mi_startup()

This function performs a bubble sort of all the system initialization objects and then calls the entry of each object one by one:

sys/kern/init_main.c:
    for (sipp = sysinit; *sipp; sipp++) {

        /* ... skipped ... */

        /* Call function */
        (*((*sipp)->func))((*sipp)->udata);
        /* ... skipped ... */
    }

Although the sysinit framework is described in the Developers' Handbook, I will discuss the internals of it.

Every system initialization object (sysinit object) is created by calling a SYSINIT() macro. Let us take as example an announce sysinit object. This object prints the copyright message:

sys/kern/init_main.c:
static void
print_caddr_t(void *data __unused)
{
    printf("%s", (char *)data);
}
SYSINIT(announce, SI_SUB_COPYRIGHT, SI_ORDER_FIRST, print_caddr_t, copyright)

The subsystem ID for this object is SI_SUB_COPYRIGHT (0x0800001), which comes right after the SI_SUB_CONSOLE (0x0800000). So, the copyright message will be printed out first, just after the console initialization.

Let us take a look at what exactly the macro SYSINIT() does. It expands to a C_SYSINIT() macro. The C_SYSINIT() macro then expands to a static struct sysinit structure declaration with another DATA_SET macro call:

/usr/include/sys/kernel.h:
      #define C_SYSINIT(uniquifier, subsystem, order, func, ident) \
      static struct sysinit uniquifier ## _sys_init = { \ subsystem, \
      order, \ func, \ ident \ }; \ DATA_SET(sysinit_set,uniquifier ##
      _sys_init);

#define SYSINIT(uniquifier, subsystem, order, func, ident)  \
    C_SYSINIT(uniquifier, subsystem, order,         \
    (sysinit_cfunc_t)(sysinit_nfunc_t)func, (void *)ident)

The DATA_SET() macro expands to a MAKE_SET(), and that macro is the point where the all sysinit magic is hidden:

/usr/include/linker_set.h
#define MAKE_SET(set, sym)                      \
    static void const * const __set_##set##_sym_##sym = &sym;   \
    __asm(".section .set." #set ",\"aw\"");             \
    __asm(".long " #sym);                       \
    __asm(".previous")
#endif
#define TEXT_SET(set, sym) MAKE_SET(set, sym)
#define DATA_SET(set, sym) MAKE_SET(set, sym)

In our case, the following declaration will occur:

static struct sysinit announce_sys_init = {
    SI_SUB_COPYRIGHT,
    SI_ORDER_FIRST,
    (sysinit_cfunc_t)(sysinit_nfunc_t)  print_caddr_t,
    (void *) copyright
};

static void const *const __set_sysinit_set_sym_announce_sys_init =
    &announce_sys_init;
__asm(".section .set.sysinit_set" ",\"aw\"");
__asm(".long " "announce_sys_init");
__asm(".previous");

The first __asm instruction will create an ELF section within the kernel's executable. This will happen at kernel link time. The section will have the name .set.sysinit_set. The content of this section is one 32-bit value, the address of announce_sys_init structure, and that is what the second __asm is. The third __asm instruction marks the end of a section. If a directive with the same section name occurred before, the content, i.e. the 32-bit value, will be appended to the existing section, so forming an array of 32-bit pointers.

Running objdump on a kernel binary, you may notice the presence of such small sections:

% objdump -h /kernel
  7 .set.cons_set 00000014  c03164c0  c03164c0  002154c0  2**2
                  CONTENTS, ALLOC, LOAD, DATA
  8 .set.kbddriver_set 00000010  c03164d4  c03164d4  002154d4  2**2
                  CONTENTS, ALLOC, LOAD, DATA
  9 .set.scrndr_set 00000024  c03164e4  c03164e4  002154e4  2**2
                  CONTENTS, ALLOC, LOAD, DATA
 10 .set.scterm_set 0000000c  c0316508  c0316508  00215508  2**2
                  CONTENTS, ALLOC, LOAD, DATA
 11 .set.sysctl_set 0000097c  c0316514  c0316514  00215514  2**2
                  CONTENTS, ALLOC, LOAD, DATA
 12 .set.sysinit_set 00000664  c0316e90  c0316e90  00215e90  2**2
                  CONTENTS, ALLOC, LOAD, DATA

This screen dump shows that the size of .set.sysinit_set section is 0x664 bytes, so 0x664/sizeof(void *) sysinit objects are compiled into the kernel. The other sections such as .set.sysctl_set represent other linker sets.

By defining a variable of type struct linker_set the content of .set.sysinit_set section will be “collected” into that variable:

sys/kern/init_main.c:
      extern struct linker_set sysinit_set; /* XXX */

The struct linker_set is defined as follows:

/usr/include/linker_set.h:
  struct linker_set {
    int ls_length;
    void    *ls_items[1];       /* really ls_length of them, trailing NULL */
};

The first node will be equal to the number of a sysinit objects, and the second node will be a NULL-terminated array of pointers to them.

Returning to the mi_startup() discussion, it is must be clear now, how the sysinit objects are being organized. The mi_startup() function sorts them and calls each. The very last object is the system scheduler:

/usr/include/sys/kernel.h:
enum sysinit_sub_id {
    SI_SUB_DUMMY        = 0x0000000,    /* not executed; for linker*/
    SI_SUB_DONE     = 0x0000001,    /* processed*/
    SI_SUB_CONSOLE      = 0x0800000,    /* console*/
    SI_SUB_COPYRIGHT    = 0x0800001,    /* first use of console*/
...
    SI_SUB_RUN_SCHEDULER    = 0xfffffff /* scheduler: no return*/
};

The system scheduler sysinit object is defined in the file sys/vm/vm_glue.c, and the entry point for that object is scheduler(). That function is actually an infinite loop, and it represents a process with PID 0, the swapper process. The proc0 structure, mentioned before, is used to describe it.

The first user process, called init, is created by the sysinit object init:

sys/kern/init_main.c:
static void
create_init(const void *udata __unused)
{
    int error;
    int s;

    s = splhigh();
    error = fork1(&proc0, RFFDG | RFPROC, &initproc);
    if (error)
        panic("cannot fork init: %d\n", error);
    initproc->p_flag |= P_INMEM | P_SYSTEM;
    cpu_set_fork_handler(initproc, start_init, NULL);
    remrunqueue(initproc);
    splx(s);
}
SYSINIT(init,SI_SUB_CREATE_INIT, SI_ORDER_FIRST, create_init, NULL)

The create_init() allocates a new process by calling fork1(), but does not mark it runnable. When this new process is scheduled for execution by the scheduler, the start_init() will be called. That function is defined in init_main.c. It tries to load and exec the init binary, probing /sbin/init first, then /sbin/oinit, /sbin/init.bak, and finally /stand/sysinstall:

sys/kern/init_main.c:
static char init_path[MAXPATHLEN] =
#ifdef  INIT_PATH
    __XSTRING(INIT_PATH);
#else
    "/sbin/init:/sbin/oinit:/sbin/init.bak:/stand/sysinstall";
#endif

Chapter 2 Locking Notes

This chapter is maintained by the FreeBSD SMP Next Generation Project. Please direct any comments or suggestions to its FreeBSD symmetric multiprocessing mailing list.

This document outlines the locking used in the FreeBSD kernel to permit effective multi-processing within the kernel. Locking can be achieved via several means. Data structures can be protected by mutexes or lockmgr(9) locks. A few variables are protected simply by always using atomic operations to access them.


2.1 Mutexes

A mutex is simply a lock used to guarantee mutual exclusion. Specifically, a mutex may only be owned by one entity at a time. If another entity wishes to obtain a mutex that is already owned, it must wait until the mutex is released. In the FreeBSD kernel, mutexes are owned by processes.

Mutexes may be recursively acquired, but they are intended to be held for a short period of time. Specifically, one may not sleep while holding a mutex. If you need to hold a lock across a sleep, use a lockmgr(9) lock.

Each mutex has several properties of interest:

Variable Name

The name of the struct mtx variable in the kernel source.

Logical Name

The name of the mutex assigned to it by mtx_init. This name is displayed in KTR trace messages and witness errors and warnings and is used to distinguish mutexes in the witness code.

Type

The type of the mutex in terms of the MTX_* flags. The meaning for each flag is related to its meaning as documented in mutex(9).

MTX_DEF

A sleep mutex

MTX_SPIN

A spin mutex

MTX_RECURSE

This mutex is allowed to recurse.

Protectees

A list of data structures or data structure members that this entry protects. For data structure members, the name will be in the form of structure name.member name.

Dependent Functions

Functions that can only be called if this mutex is held.

Table 2-1. Mutex List

Variable Name Logical Name Type Protectees Dependent Functions
sched_lock “sched lock” MTX_SPIN | MTX_RECURSE _gmonparam, cnt.v_swtch, cp_time, curpriority, mtx.mtx_blocked, mtx.mtx_contested, proc.p_procq, proc.p_slpq, proc.p_sflag, proc.p_stat, proc.p_estcpu, proc.p_cpticks proc.p_pctcpu, proc.p_wchan, proc.p_wmesg, proc.p_swtime, proc.p_slptime, proc.p_runtime, proc.p_uu, proc.p_su, proc.p_iu, proc.p_uticks, proc.p_sticks, proc.p_iticks, proc.p_oncpu, proc.p_lastcpu, proc.p_rqindex, proc.p_heldmtx, proc.p_blocked, proc.p_mtxname, proc.p_contested, proc.p_priority, proc.p_usrpri, proc.p_nativepri, proc.p_nice, proc.p_rtprio, pscnt, slpque, itqueuebits, itqueues, rtqueuebits, rtqueues, queuebits, queues, idqueuebits, idqueues, switchtime, switchticks setrunqueue, remrunqueue, mi_switch, chooseproc, schedclock, resetpriority, updatepri, maybe_resched, cpu_switch, cpu_throw, need_resched, resched_wanted, clear_resched, aston, astoff, astpending, calcru, proc_compare
vm86pcb_lock “vm86pcb lock” MTX_DEF vm86pcb vm86_bioscall
Giant “Giant” MTX_DEF | MTX_RECURSE nearly everything lots
callout_lock “callout lock” MTX_SPIN | MTX_RECURSE callfree, callwheel, nextsoftcheck, proc.p_itcallout, proc.p_slpcallout, softticks, ticks  

2.2 Shared Exclusive Locks

These locks provide basic reader-writer type functionality and may be held by a sleeping process. Currently they are backed by lockmgr(9).

Table 2-2. Shared Exclusive Lock List

Variable Name Protectees
allproc_lock allproc zombproc pidhashtbl proc.p_list proc.p_hash nextpid
proctree_lock proc.p_children proc.p_sibling

2.3 Atomically Protected Variables

An atomically protected variable is a special variable that is not protected by an explicit lock. Instead, all data accesses to the variables use special atomic operations as described in atomic(9). Very few variables are treated this way, although other synchronization primitives such as mutexes are implemented with atomically protected variables.

  • mtx.mtx_lock


Chapter 3 Kernel Objects

Kernel Objects, or Kobj provides an object-oriented C programming system for the kernel. As such the data being operated on carries the description of how to operate on it. This allows operations to be added and removed from an interface at run time and without breaking binary compatibility.


3.1 Terminology

Object

A set of data - data structure - data allocation.

Method

An operation - function.

Class

One or more methods.

Interface

A standard set of one or more methods.


3.2 Kobj Operation

Kobj works by generating descriptions of methods. Each description holds a unique id as well as a default function. The description's address is used to uniquely identify the method within a class' method table.

A class is built by creating a method table associating one or more functions with method descriptions. Before use the class is compiled. The compilation allocates a cache and associates it with the class. A unique id is assigned to each method description within the method table of the class if not already done so by another referencing class compilation. For every method to be used a function is generated by script to qualify arguments and automatically reference the method description for a lookup. The generated function looks up the method by using the unique id associated with the method description as a hash into the cache associated with the object's class. If the method is not cached the generated function proceeds to use the class' table to find the method. If the method is found then the associated function within the class is used; otherwise, the default function associated with the method description is used.

These indirections can be visualized as the following:

object->cache<->class

3.3 Using Kobj

3.3.1 Structures

struct kobj_method

3.3.2 Functions

void kobj_class_compile(kobj_class_t cls);
void kobj_class_compile_static(kobj_class_t cls, kobj_ops_t ops);
void kobj_class_free(kobj_class_t cls);
kobj_t kobj_create(kobj_class_t cls, struct malloc_type *mtype, int mflags);
void kobj_init(kobj_t obj, kobj_class_t cls);
void kobj_delete(kobj_t obj, struct malloc_type *mtype);

3.3.3 Macros

KOBJ_CLASS_FIELDS
KOBJ_FIELDS
DEFINE_CLASS(name, methods, size)
KOBJMETHOD(NAME, FUNC)

3.3.4 Headers

<sys/param.h>
<sys/kobj.h>

3.3.5 Creating an interface template

The first step in using Kobj is to create an Interface. Creating the interface involves creating a template that the script src/sys/kern/makeobjops.pl can use to generate the header and code for the method declarations and method lookup functions.

Within this template the following keywords are used: #include, INTERFACE, CODE, METHOD, STATICMETHOD, and DEFAULT.

The #include statement and what follows it is copied verbatim to the head of the generated code file.

For example:

#include <sys/foo.h>

The INTERFACE keyword is used to define the interface name. This name is concatenated with each method name as [interface name]_[method name]. Its syntax is INTERFACE [interface name];.

For example:

INTERFACE foo;

The CODE keyword copies its arguments verbatim into the code file. Its syntax is CODE { [whatever] };

For example:

CODE {
    struct foo * foo_alloc_null(struct bar *)
    {
        return NULL;
}
};

The METHOD keyword describes a method. Its syntax is METHOD [return type] [method name] { [object [, arguments]] };

For example:

METHOD int bar {
    struct object *;
    struct foo *;
    struct bar;
};

The DEFAULT keyword may follow the METHOD keyword. It extends the METHOD key word to include the default function for method. The extended syntax is METHOD [return type] [method name] { [object; [other arguments]] }DEFAULT [default function];

For example:

METHOD int bar {
    struct object *;
    struct foo *;
    int bar;
} DEFAULT foo_hack;

The STATICMETHOD keyword is used like the METHOD keyword except the kobj data is not at the head of the object structure so casting to kobj_t would be incorrect. Instead STATICMETHOD relies on the Kobj data being referenced as 'ops'. This is also useful for calling methods directly out of a class's method table.

Other complete examples:

src/sys/kern/bus_if.m
src/sys/kern/device_if.m

3.3.6 Creating a Class

The second step in using Kobj is to create a class. A class consists of a name, a table of methods, and the size of objects if Kobj's object handling facilities are used. To create the class use the macro DEFINE_CLASS(). To create the method table create an array of kobj_method_t terminated by a NULL entry. Each non-NULL entry may be created using the macro KOBJMETHOD().

For example:

DEFINE_CLASS(fooclass, foomethods, sizeof(struct foodata));

kobj_method_t foomethods[] = {
    KOBJMETHOD(bar_doo, foo_doo),
    KOBJMETHOD(bar_foo, foo_foo),
    { NULL, NULL}
};

The class must be “compiled”. Depending on the state of the system at the time that the class is to be initialized a statically allocated cache, “ops table” have to be used. This can be accomplished by declaring a struct kobj_ops and using kobj_class_compile_static(); otherwise, kobj_class_compile() should be used.


3.3.7 Creating an Object

The third step in using Kobj involves how to define the object. Kobj object creation routines assume that Kobj data is at the head of an object. If this in not appropriate you will have to allocate the object yourself and then use kobj_init() on the Kobj portion of it; otherwise, you may use kobj_create() to allocate and initialize the Kobj portion of the object automatically. kobj_init() may also be used to change the class that an object uses.

To integrate Kobj into the object you should use the macro KOBJ_FIELDS.

For example

struct foo_data {
    KOBJ_FIELDS;
    foo_foo;
    foo_bar;
};

3.3.8 Calling Methods

The last step in using Kobj is to simply use the generated functions to use the desired method within the object's class. This is as simple as using the interface name and the method name with a few modifications. The interface name should be concatenated with the method name using a '_' between them, all in upper case.

For example, if the interface name was foo and the method was bar then the call would be:

[return value = ] FOO_BAR(object [, other parameters]);

3.3.9 Cleaning Up

When an object allocated through kobj_create() is no longer needed kobj_delete() may be called on it, and when a class is no longer being used kobj_class_free() may be called on it.


Chapter 4 The Jail Subsystem

Evan SarmientoCopyright © 2001 Evan Sarmiento

On most UNIX® systems, root has omnipotent power. This promotes insecurity. If an attacker gained root on a system, he would have every function at his fingertips. In FreeBSD there are sysctls which dilute the power of root, in order to minimize the damage caused by an attacker. Specifically, one of these functions is called secure levels. Similarly, another function which is present from FreeBSD 4.0 and onward, is a utility called jail(8). Jail chroots an environment and sets certain restrictions on processes which are forked within the jail. For example, a jailed process cannot affect processes outside the jail, utilize certain system calls, or inflict any damage on the host environment.

Jail is becoming the new security model. People are running potentially vulnerable servers such as Apache, BIND, and sendmail within jails, so that if an attacker gains root within the jail, it is only an annoyance, and not a devastation. This article mainly focuses on the internals (source code) of jail. If you are looking for a how-to on setting up a jail, I suggest you look at my other article in Sys Admin Magazine, May 2001, entitled "Securing FreeBSD using Jail."


4.1 Architecture

Jail consists of two realms: the userland program, jail(8), and the code implemented within the kernel: the jail(2) system call and associated restrictions. I will be discussing the userland program and then how jail is implemented within the kernel.


4.1.1 Userland Code

The source for the userland jail is located in /usr/src/usr.sbin/jail, consisting of one file, jail.c. The program takes these arguments: the path of the jail, hostname, IP address, and the command to be executed.


4.1.1.1 Data Structures

In jail.c, the first thing I would note is the declaration of an important structure struct jail j; which was included from /usr/include/sys/jail.h.

The definition of the jail structure is:

/usr/include/sys/jail.h: 

struct jail {
        u_int32_t       version;
        char            *path;
        char            *hostname;
        u_int32_t       ip_number;
};

As you can see, there is an entry for each of the arguments passed to the jail(8) program, and indeed, they are set during its execution.

/usr/src/usr.sbin/jail/jail.c
char path[PATH_MAX];
...
if (realpath(argv[0], path) == NULL)
    err(1, "realpath: %s", argv[0]);
if (chdir(path) != 0)
    err(1, "chdir: %s", path);
memset(&j, 0, sizeof(j));
j.version = 0;
j.path = path;
j.hostname = argv[1];

4.1.1.2 Networking

One of the arguments passed to the jail(8) program is an IP address with which the jail can be accessed over the network. jail(8) translates the IP address given into host byte order and then stores it in j (the jail structure).

/usr/src/usr.sbin/jail/jail.c:
struct in_addr in; 
... 
if (inet_aton(argv[2], &in) == 0)
    errx(1, "Could not make sense of ip-number: %s", argv[2]);
j.ip_number = ntohl(in.s_addr);

The inet_aton(3) function "interprets the specified character string as an Internet address, placing the address into the structure provided." The ip_number member in the jail structure is set only when the IP address placed onto the in structure by inet_aton(3) is translated into host byte order by ntohl(3).


4.1.1.3 Jailing The Process

Finally, the userland program jails the process. Jail now becomes an imprisoned process itself and then executes the command given using execv(3).

/usr/src/usr.sbin/jail/jail.c
i = jail(&j); 
... 
if (execv(argv[3], argv + 3) != 0)
    err(1, "execv: %s", argv[3]);

As you can see, the jail() function is called, and its argument is the jail structure which has been filled with the arguments given to the program. Finally, the program you specify is executed. I will now discuss how jail is implemented within the kernel.


4.1.2 Kernel Space

We will now be looking at the file /usr/src/sys/kern/kern_jail.c. This is the file where the jail(2) system call, appropriate sysctls, and networking functions are defined.


4.1.2.1 sysctls

In kern_jail.c, the following sysctls are defined:

/usr/src/sys/kern/kern_jail.c:

int     jail_set_hostname_allowed = 1;
SYSCTL_INT(_security_jail, OID_AUTO, set_hostname_allowed, CTLFLAG_RW,
    &jail_set_hostname_allowed, 0,
    "Processes in jail can set their hostnames");

int     jail_socket_unixiproute_only = 1;
SYSCTL_INT(_security_jail, OID_AUTO, socket_unixiproute_only, CTLFLAG_RW,
    &jail_socket_unixiproute_only, 0,
    "Processes in jail are limited to creating UNIX/IPv4/route sockets only");

int     jail_sysvipc_allowed = 0;
SYSCTL_INT(_security_jail, OID_AUTO, sysvipc_allowed, CTLFLAG_RW,
    &jail_sysvipc_allowed, 0,
    "Processes in jail can use System V IPC primitives");

static int jail_enforce_statfs = 2;
SYSCTL_INT(_security_jail, OID_AUTO, enforce_statfs, CTLFLAG_RW,
    &jail_enforce_statfs, 0,
    "Processes in jail cannot see all mounted file systems");

int    jail_allow_raw_sockets = 0;
SYSCTL_INT(_security_jail, OID_AUTO, allow_raw_sockets, CTLFLAG_RW,
    &jail_allow_raw_sockets, 0,
    "Prison root can create raw sockets");

int    jail_chflags_allowed = 0;
SYSCTL_INT(_security_jail, OID_AUTO, chflags_allowed, CTLFLAG_RW,
    &jail_chflags_allowed, 0,
    "Processes in jail can alter system file flags");

int     jail_mount_allowed = 0;
SYSCTL_INT(_security_jail, OID_AUTO, mount_allowed, CTLFLAG_RW,
    &jail_mount_allowed, 0,
    "Processes in jail can mount/unmount jail-friendly file systems");

Each of these sysctls can be accessed by the user through the sysctl(8) program. Throughout the kernel, these specific sysctls are recognized by their name. For example, the name of the first sysctl is security.jail.set_hostname_allowed.


4.1.2.2 jail(2) system call

Like all system calls, the jail(2) system call takes two arguments, struct thread *td and struct jail_args *uap. td is a pointer to the thread structure which describes the calling thread. In this context, uap is a pointer to the structure in which a pointer to the jail structure passed by the userland jail.c is contained. When I described the userland program before, you saw that the jail(2) system call was given a jail structure as its own argument.

/usr/src/sys/kern/kern_jail.c:
/*
 * struct jail_args {
 *  struct jail *jail;
 * };
 */ 
int 
jail(struct thread *td, struct jail_args *uap)

Therefore, uap->jail can be used to access the jail structure which was passed to the system call. Next, the system call copies the jail structure into kernel space using the copyin(9) function. copyin(9) takes three arguments: the address of the data which is to be copied into kernel space, uap->jail, where to store it, j and the size of the storage. The jail structure pointed by uap->jail is copied into kernel space and is stored in another jail structure, j.

/usr/src/sys/kern/kern_jail.c: 
error = copyin(uap->jail, &j, sizeof(j));

There is another important structure defined in jail.h. It is the prison structure. The prison structure is used exclusively within kernel space. Here is the definition of the prison structure.

/usr/include/sys/jail.h:
struct prison {
        LIST_ENTRY(prison) pr_list;                     /* (a) all prisons */
        int              pr_id;                         /* (c) prison id */
        int              pr_ref;                        /* (p) refcount */
        char             pr_path[MAXPATHLEN];           /* (c) chroot path */
        struct vnode    *pr_root;                       /* (c) vnode to rdir */
        char             pr_host[MAXHOSTNAMELEN];       /* (p) jail hostname */
        u_int32_t        pr_ip;                         /* (c) ip addr host */
        void            *pr_linux;                      /* (p) linux abi */
        int              pr_securelevel;                /* (p) securelevel */
        struct task      pr_task;                       /* (d) destroy task */
        struct mtx       pr_mtx;
      void            **pr_slots;                     /* (p) additional data */
};

The jail(2) system call then allocates memory for a prison structure and copies data between the jail and prison structure.

/usr/src/sys/kern/kern_jail.c:
MALLOC(pr, struct prison *, sizeof(*pr), M_PRISON, M_WAITOK | M_ZERO);
...
error = copyinstr(j.path, &pr->pr_path, sizeof(pr->pr_path), 0);
if (error)
    goto e_killmtx;
...
error = copyinstr(j.hostname, &pr->pr_host, sizeof(pr->pr_host), 0);
if (error)
     goto e_dropvnref;
pr->pr_ip = j.ip_number;

Next, we will discuss another important system call jail_attach(2), which implements the function to put a process into the jail.

/usr/src/sys/kern/kern_jail.c:
/*
 * struct jail_attach_args {
 *      int jid;
 * };
 */
int
jail_attach(struct thread *td, struct jail_attach_args *uap)

This system call makes the changes that can distinguish a jailed process from those unjailed ones. To understand what jail_attach(2) does for us, certain background information is needed.

On FreeBSD, each kernel visible thread is identified by its thread structure, while the processes are described by their proc structures. You can find the definitions of the thread and proc structure in /usr/include/sys/proc.h. For example, the td argument in any system call is actually a pointer to the calling thread's thread structure, as stated before. The td_proc member in the thread structure pointed by td is a pointer to the proc structure which represents the process that contains the thread represented by td. The proc structure contains members which can describe the owner's identity(p_ucred), the process resource limits(p_limit), and so on. In the ucred structure pointed by p_ucred member in the proc structure, there is a pointer to the prison structure(cr_prison).

/usr/include/sys/proc.h: 
struct thread {
    ...
    struct proc *td_proc;
    ...
};
struct proc { 
    ...
    struct ucred *p_ucred; 
    ...
};
/usr/include/sys/ucred.h
struct ucred {
    ...
    struct prison *cr_prison;
    ...
};

In kern_jail.c, the function jail() then calls function jail_attach() with a given jid. And jail_attach() calls function change_root() to change the root directory of the calling process. The jail_attach() then creates a new ucred structure, and attaches the newly created ucred structure to the calling process after it has successfully attached the prison structure to the ucred structure. From then on, the calling process is recognized as jailed. When the kernel routine jailed() is called in the kernel with the newly created ucred structure as its argument, it returns 1 to tell that the credential is connected with a jail. The public ancestor process of all the process forked within the jail, is the process which runs jail(8), as it calls the jail(2) system call. When a program is executed through execve(2), it inherits the jailed property of its parent's ucred structure, therefore it has a jailed ucred structure.

/usr/src/sys/kern/kern_jail.c
int
jail(struct thread *td, struct jail_args *uap)
{
...
    struct jail_attach_args jaa;
...
    error = jail_attach(td, &jaa);
    if (error)
        goto e_dropprref;
...
}

int
jail_attach(struct thread *td, struct jail_attach_args *uap)
{
    struct proc *p;
    struct ucred *newcred, *oldcred;
    struct prison *pr;
...
    p = td->td_proc;
...
    pr = prison_find(uap->jid);
...
    change_root(pr->pr_root, td);
...
    newcred->cr_prison = pr;
    p->p_ucred = newcred;
...
}

When a process is forked from its parent process, the fork(2) system call uses crhold() to maintain the credential for the newly forked process. It inherently keep the newly forked child's credential consistent with its parent, so the child process is also jailed.

/usr/src/sys/kern/kern_fork.c:
p2->p_ucred = crhold(td->td_ucred);
...
td2->td_ucred = crhold(p2->p_ucred);

4.2 Restrictions

Throughout the kernel there are access restrictions relating to jailed processes. Usually, these restrictions only check whether the process is jailed, and if so, returns an error. For example:

if (jailed(td->td_ucred))
    return (EPERM);

4.2.1 SysV IPC

System V IPC is based on messages. Processes can send each other these messages which tell them how to act. The functions which deal with messages are: msgctl(3), msgget(3), msgsnd(3) and msgrcv(3). Earlier, I mentioned that there were certain sysctls you could turn on or off in order to affect the behavior of jail. One of these sysctls was security.jail.sysvipc_allowed. By default, this sysctl is set to 0. If it were set to 1, it would defeat the whole purpose of having a jail; privileged users from the jail would be able to affect processes outside the jailed environment. The difference between a message and a signal is that the message only consists of the signal number.

/usr/src/sys/kern/sysv_msg.c:

  • msgget(key, msgflg): msgget returns (and possibly creates) a message descriptor that designates a message queue for use in other functions.

  • msgctl(msgid, cmd, buf): Using this function, a process can query the status of a message descriptor.

  • msgsnd(msgid, msgp, msgsz, msgflg): msgsnd sends a message to a process.

  • msgrcv(msgid, msgp, msgsz, msgtyp, msgflg): a process receives messages using this function

In each of the system calls corresponding to these functions, there is this conditional:

/usr/src/sys/kern/sysv_msg.c:
if (!jail_sysvipc_allowed && jailed(td->td_ucred))
    return (ENOSYS);

Semaphore system calls allow processes to synchronize execution by doing a set of operations atomically on a set of semaphores. Basically semaphores provide another way for processes lock resources. However, process waiting on a semaphore, that is being used, will sleep until the resources are relinquished. The following semaphore system calls are blocked inside a jail: semget(2), semctl(2) and semop(2).

/usr/src/sys/kern/sysv_sem.c:

  • semctl(semid, semnum, cmd, ...): semctl does the specified cmd on the semaphore queue indicated by semid.

  • semget(key, nsems, flag): semget creates an array of semaphores, corresponding to key.

    key and flag take on the same meaning as they do in msgget.

  • semop(semid, array, nops): semop performs a group of operations indicated by array, to the set of semaphores identified by semid.

System V IPC allows for processes to share memory. Processes can communicate directly with each other by sharing parts of their virtual address space and then reading and writing data stored in the shared memory. These system calls are blocked within a jailed environment: shmdt(2), shmat(2), shmctl(2) and shmget(2).

/usr/src/sys/kern/sysv_shm.c:

  • shmctl(shmid, cmd, buf): shmctl does various control operations on the shared memory region identified by shmid.

  • shmget(key, size, flag): shmget accesses or creates a shared memory region of size bytes.

  • shmat(shmid, addr, flag): shmat attaches a shared memory region identified by shmid to the address space of a process.

  • shmdt(addr): shmdt detaches the shared memory region previously attached at addr.


4.2.2 Sockets

Jail treats the socket(2) system call and related lower-level socket functions in a special manner. In order to determine whether a certain socket is allowed to be created, it first checks to see if the sysctl security.jail.socket_unixiproute_only is set. If set, sockets are only allowed to be created if the family specified is either PF_LOCAL, PF_INET or PF_ROUTE. Otherwise, it returns an error.

/usr/src/sys/kern/uipc_socket.c:
int
socreate(int dom, struct socket **aso, int type, int proto,
    struct ucred *cred, struct thread *td)
{
    struct protosw *prp;
...
    if (jailed(cred) && jail_socket_unixiproute_only &&
        prp->pr_domain->dom_family != PF_LOCAL &&
        prp->pr_domain->dom_family != PF_INET &&
        prp->pr_domain->dom_family != PF_ROUTE) {
        return (EPROTONOSUPPORT);
    }
...
}

4.2.3 Berkeley Packet Filter

The Berkeley Packet Filter provides a raw interface to data link layers in a protocol independent fashion. BPF is now controlled by the devfs(8) whether it can be used in a jailed environment.


4.2.4 Protocols

There are certain protocols which are very common, such as TCP, UDP, IP and ICMP. IP and ICMP are on the same level: the network layer 2. There are certain precautions which are taken in order to prevent a jailed process from binding a protocol to a certain address only if the nam parameter is set. nam is a pointer to a sockaddr structure, which describes the address on which to bind the service. A more exact definition is that sockaddr "may be used as a template for referring to the identifying tag and length of each address". In the function in_pcbbind_setup(), sin is a pointer to a sockaddr_in structure, which contains the port, address, length and domain family of the socket which is to be bound. Basically, this disallows any processes from jail to be able to specify the address that doesn't belong to the jail in which the calling process exists.

/usr/src/sys/netinet/in_pcb.c: 
int
in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
    u_short *lportp, struct ucred *cred)
{
    ...
    struct sockaddr_in *sin;
    ...
    if (nam) {
        sin = (struct sockaddr_in *)nam;
        ...
        if (sin->sin_addr.s_addr != INADDR_ANY)
            if (prison_ip(cred, 0, &sin->sin_addr.s_addr))
                return(EINVAL);
        ...
        if (lport) {
            ...
            if (prison && prison_ip(cred, 0, &sin->sin_addr.s_addr))
                return (EADDRNOTAVAIL);
            ...
        }
    }
    if (lport == 0) {
        ...
        if (laddr.s_addr != INADDR_ANY)
            if (prison_ip(cred, 0, &laddr.s_addr))
                return (EINVAL);
        ...
    }
...
    if (prison_ip(cred, 0, &laddr.s_addr))
        return (EINVAL);
...
}

You might be wondering what function prison_ip() does. prison_ip() is given three arguments, a pointer to the credential(represented by cred), any flags, and an IP address. It returns 1 if the IP address does NOT belong to the jail or 0 otherwise. As you can see from the code, if it is indeed an IP address not belonging to the jail, the protcol is not allowed to bind to that address.

/usr/src/sys/kern/kern_jail.c:
int
prison_ip(struct ucred *cred, int flag, u_int32_t *ip)
{
    u_int32_t tmp;

    if (!jailed(cred))
        return (0);
    if (flag)
        tmp = *ip;
    else
        tmp = ntohl(*ip);
    if (tmp == INADDR_ANY) {
        if (flag)
            *ip = cred->cr_prison->pr_ip;
        else
            *ip = htonl(cred->cr_prison->pr_ip);
        return (0);
    }
    if (tmp == INADDR_LOOPBACK) {
        if (flag)
            *ip = cred->cr_prison->pr_ip;
        else
            *ip = htonl(cred->cr_prison->pr_ip);
        return (0);
    }
    if (cred->cr_prison->pr_ip != tmp)
        return (1);
    return (0);
}

4.2.5 Filesystem

Even root users within the jail are not allowed to unset or modify any file flags, such as immutable, append-only, and undeleteable flags, if the securelevel is greater than 0.

/usr/src/sys/ufs/ufs/ufs_vnops.c:
static int
ufs_setattr(ap)
    ...
{
    ...
        if (!priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0)) {
            if (ip->i_flags
                & (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
                    error = securelevel_gt(cred, 0);
                    if (error)
                        return (error);
            }
            ...
        }
}
/usr/src/sys/kern/kern_priv.c
int
priv_check_cred(struct ucred *cred, int priv, int flags)
{
    ...
    error = prison_priv_check(cred, priv);
    if (error)
        return (error);
    ...
}
/usr/src/sys/kern/kern_jail.c
int
prison_priv_check(struct ucred *cred, int priv)
{
    ...
    switch (priv) {
    ...
    case PRIV_VFS_SYSFLAGS:
        if (jail_chflags_allowed)
            return (0);
        else
            return (EPERM);
    ...
    }
    ...
}

Chapter 5 The SYSINIT Framework

SYSINIT is the framework for a generic call sort and dispatch mechanism. FreeBSD currently uses it for the dynamic initialization of the kernel. SYSINIT allows FreeBSD's kernel subsystems to be reordered, and added, removed, and replaced at kernel link time when the kernel or one of its modules is loaded without having to edit a statically ordered initialization routing and recompile the kernel. This system also allows kernel modules, currently called KLD's, to be separately compiled, linked, and initialized at boot time and loaded even later while the system is already running. This is accomplished using the “kernel linker” and “linker sets”.


5.1 Terminology

Linker Set

A linker technique in which the linker gathers statically declared data throughout a program's source files into a single contiguously addressable unit of data.


5.2 SYSINIT Operation

SYSINIT relies on the ability of the linker to take static data declared at multiple locations throughout a program's source and group it together as a single contiguous chunk of data. This linker technique is called a “linker set”. SYSINIT uses two linker sets to maintain two data sets containing each consumer's call order, function, and a pointer to the data to pass to that function.

SYSINIT uses two priorities when ordering the functions for execution. The first priority is a subsystem ID giving an overall order for SYSINIT's dispatch of functions. Current predeclared ID's are in <sys/kernel.h> in the enum list sysinit_sub_id. The second priority used is an element order within the subsystem. Current predeclared subsystem element orders are in <sys/kernel.h> in the enum list sysinit_elem_order.

There are currently two uses for SYSINIT. Function dispatch at system startup and kernel module loads, and function dispatch at system shutdown and kernel module unload. Kernel subsystems often use system startup SYSINIT's to initialize data structures, for example the process scheduling subsystem uses a SYSINIT to initialize the run queue data structure. Device drivers should avoid using SYSINIT() directly. Instead drivers for real devices that are part of a bus structure should use DRIVER_MODULE() to provide a function that detects the device and, if it is present, initializes the device. It will do a few things specific to devices and then call SYSINIT() itself. For pseudo-devices, which are not part of a bus structure, use DEV_MODULE().


5.3 Using SYSINIT

5.3.1 Interface

5.3.1.1 Headers

<sys/kernel.h>

5.3.1.2 Macros

SYSINIT(uniquifier, subsystem, order, func, ident)
SYSUNINIT(uniquifier, subsystem, order, func, ident)

5.3.2 Startup

The SYSINIT() macro creates the necessary SYSINIT data in SYSINIT's startup data set for SYSINIT to sort and dispatch a function at system startup and module load. SYSINIT() takes a uniquifier that SYSINIT uses to identify the particular function dispatch data, the subsystem order, the subsystem element order, the function to call, and the data to pass the function. All functions must take a constant pointer argument.

Example 5-1. Example of a SYSINIT()

#include <sys/kernel.h>

void foo_null(void *unused)
{
        foo_doo();
}
SYSINIT(foo, SI_SUB_FOO, SI_ORDER_FOO, foo_null, NULL);

struct foo foo_voodoo = {
        FOO_VOODOO;
}

void foo_arg(void *vdata)
{
        struct foo *foo = (struct foo *)vdata;
        foo_data(foo);
}
SYSINIT(bar, SI_SUB_FOO, SI_ORDER_FOO, foo_arg, &foo_voodoo);
   

Note that SI_SUB_FOO and SI_ORDER_FOO need to be in the sysinit_sub_id and sysinit_elem_order enum's as mentioned above. Either use existing ones or add your own to the enum's. You can also use math for fine-tuning the order a SYSINIT will run in. This example shows a SYSINIT that needs to be run just barely before the SYSINIT's that handle tuning kernel parameters.

Example 5-2. Example of Adjusting SYSINIT() Order

static void
mptable_register(void *dummy __unused)
{

    apic_register_enumerator(&mptable_enumerator);
}

SYSINIT(mptable_register, SI_SUB_TUNABLES - 1, SI_ORDER_FIRST,
    mptable_register, NULL);

5.3.3 Shutdown

The SYSUNINIT() macro behaves similarly to the SYSINIT() macro except that it adds the SYSINIT data to SYSINIT's shutdown data set.

Example 5-3. Example of a SYSUNINIT()

#include <sys/kernel.h>

void foo_cleanup(void *unused)
{
        foo_kill();
}
SYSUNINIT(foobar, SI_SUB_FOO, SI_ORDER_FOO, foo_cleanup, NULL);

struct foo_stack foo_stack = {
        FOO_STACK_VOODOO;
}

void foo_flush(void *vdata)
{
}
SYSUNINIT(barfoo, SI_SUB_FOO, SI_ORDER_FOO, foo_flush, &foo_stack);
   

Chapter 6 The TrustedBSD MAC Framework

Chris Costello and Robert Watson.

6.1 MAC Documentation Copyright

This documentation was developed for the FreeBSD Project by Chris Costello at Safeport Network Services and Network Associates Laboratories, the Security Research Division of Network Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 (“CBOSS”), as part of the DARPA CHATS research program.

Redistribution and use in source (SGML DocBook) and 'compiled' forms (SGML, HTML, PDF, PostScript, RTF and so forth) with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code (SGML DocBook) must retain the above copyright notice, this list of conditions and the following disclaimer as the first lines of this file unmodified.

  2. Redistributions in compiled form (transformed to other DTDs, converted to PDF, PostScript, RTF and other formats) must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Important: THIS DOCUMENTATION IS PROVIDED BY THE NETWORKS ASSOCIATES TECHNOLOGY, INC "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NETWORKS ASSOCIATES TECHNOLOGY, INC BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


6.2 Synopsis

FreeBSD includes experimental support for several mandatory access control policies, as well as a framework for kernel security extensibility, the TrustedBSD MAC Framework. The MAC Framework is a pluggable access control framework, permitting new security policies to be easily linked into the kernel, loaded at boot, or loaded dynamically at run-time. The framework provides a variety of features to make it easier to implement new security policies, including the ability to easily tag security labels (such as confidentiality information) onto system objects.

This chapter introduces the MAC policy framework and provides documentation for a sample MAC policy module.


6.3 Introduction

The TrustedBSD MAC framework provides a mechanism to allow the compile-time or run-time extension of the kernel access control model. New system policies may be implemented as kernel modules and linked to the kernel; if multiple policy modules are present, their results will be composed. The MAC Framework provides a variety of access control infrastructure services to assist policy writers, including support for transient and persistent policy-agnostic object security labels. This support is currently considered experimental.

This chapter provides information appropriate for developers of policy modules, as well as potential consumers of MAC-enabled environments, to learn about how the MAC Framework supports access control extension of the kernel.


6.4 Policy Background

Mandatory Access Control (MAC), refers to a set of access control policies that are mandatorily enforced on users by the operating system. MAC policies may be contrasted with Discretionary Access Control (DAC) protections, by which non-administrative users may (at their discretion) protect objects. In traditional UNIX systems, DAC protections include file permissions and access control lists; MAC protections include process controls preventing inter-user debugging and firewalls. A variety of MAC policies have been formulated by operating system designers and security researches, including the Multi-Level Security (MLS) confidentiality policy, the Biba integrity policy, Role-Based Access Control (RBAC), Domain and Type Enforcement (DTE), and Type Enforcement (TE). Each model bases decisions on a variety of factors, including user identity, role, and security clearance, as well as security labels on objects representing concepts such as data sensitivity and integrity.

The TrustedBSD MAC Framework is capable of supporting policy modules that implement all of these policies, as well as a broad class of system hardening policies, which may use existing security attributes, such as user and group IDs, as well as extended attributes on files, and other system properties. In addition, despite the name, the MAC Framework can also be used to implement purely discretionary policies, as policy modules are given substantial flexibility in how they authorize protections.


6.5 MAC Framework Kernel Architecture

The TrustedBSD MAC Framework permits kernel modules to extend the operating system security policy, as well as providing infrastructure functionality required by many access control modules. If multiple policies are simultaneously loaded, the MAC Framework will usefully (for some definition of useful) compose the results of the policies.


6.5.1 Kernel Elements

The MAC Framework contains a number of kernel elements:

  • Framework management interfaces

  • Concurrency and synchronization primitives.

  • Policy registration

  • Extensible security label for kernel objects

  • Policy entry point composition operators

  • Label management primitives

  • Entry point API invoked by kernel services

  • Entry point API to policy modules

  • Entry points implementations (policy life cycle, object life cycle/label management, access control checks).

  • Policy-agnostic label-management system calls

  • mac_syscall() multiplex system call

  • Various security policies implemented as MAC policy modules


6.5.2 Framework Management Interfaces

The TrustedBSD MAC Framework may be directly managed using sysctl's, loader tunables, and system calls.

In most cases, sysctl's and loader tunables of the same name modify the same parameters, and control behavior such as enforcement of protections relating to various kernel subsystems. In addition, if MAC debugging support is compiled into the kernel, several counters will be maintained tracking label allocation. It is generally advisable that per-subsystem enforcement controls not be used to control policy behavior in production environments, as they broadly impact the operation of all active policies. Instead, per-policy controls should be preferred, as they provide greater granularity and greater operational consistency for policy modules.

Loading and unloading of policy modules is performed using the system module management system calls and other system interfaces, including boot loader variables; policy modules will have the opportunity to influence load and unload events, including preventing undesired unloading of the policy.


6.5.3 Policy List Concurrency and Synchronization

As the set of active policies may change at run-time, and the invocation of entry points is non-atomic, synchronization is required to prevent loading or unloading of policies while an entry point invocation is in progress, freezing the set of active policies for the duration. This is accomplished by means of a framework busy count: whenever an entry point is entered, the busy count is incremented; whenever it is exited, the busy count is decremented. While the busy count is elevated, policy list changes are not permitted, and threads attempting to modify the policy list will sleep until the list is not busy. The busy count is protected by a mutex, and a condition variable is used to wake up sleepers waiting on policy list modifications. One side effect of this synchronization model is that recursion into the MAC Framework from within a policy module is permitted, although not generally used.

Various optimizations are used to reduce the overhead of the busy count, including avoiding the full cost of incrementing and decrementing if the list is empty or contains only static entries (policies that are loaded before the system starts, and cannot be unloaded). A compile-time option is also provided which prevents any change in the set of loaded policies at run-time, which eliminates the mutex locking costs associated with supporting dynamically loaded and unloaded policies as synchronization is no longer required.

As the MAC Framework is not permitted to block in some entry points, a normal sleep lock cannot be used; as a result, it is possible for the load or unload attempt to block for a substantial period of time waiting for the framework to become idle.


6.5.4 Label Synchronization

As kernel objects of interest may generally be accessed from more than one thread at a time, and simultaneous entry of more than one thread into the MAC Framework is permitted, security attribute storage maintained by the MAC Framework is carefully synchronized. In general, existing kernel synchronization on kernel object data is used to protect MAC Framework security labels on the object: for example, MAC labels on sockets are protected using the existing socket mutex. Likewise, semantics for concurrent access are generally identical to those of the container objects: for credentials, copy-on-write semantics are maintained for label contents as with the remainder of the credential structure. The MAC Framework asserts necessary locks on objects when invoked with an object reference. Policy authors must be aware of these synchronization semantics, as they will sometimes limit the types of accesses permitted on labels: for example, when a read-only reference to a credential is passed to a policy via an entry point, only read operations are permitted on the label state attached to the credential.


6.5.5 Policy Synchronization and Concurrency

Policy modules must be written to assume that many kernel threads may simultaneously enter one more policy entry points due to the parallel and preemptive nature of the FreeBSD kernel. If the policy module makes use of mutable state, this may require the use of synchronization primitives within the policy to prevent inconsistent views on that state resulting in incorrect operation of the policy. Policies will generally be able to make use of existing FreeBSD synchronization primitives for this purpose, including mutexes, sleep locks, condition variables, and counting semaphores. However, policies should be written to employ these primitives carefully, respecting existing kernel lock orders, and recognizing that some entry points are not permitted to sleep, limiting the use of primitives in those entry points to mutexes and wakeup operations.

When policy modules call out to other kernel subsytems, they will generally need to release any in-policy locks in order to avoid violating the kernel lock order or risking lock recursion. This will maintain policy locks as leaf locks in the global lock order, helping to avoid deadlock.


6.5.6 Policy Registration

The MAC Framework maintains two lists of active policies: a static list, and a dynamic list. The lists differ only with regards to their locking semantics: an elevated reference count is not required to make use of the static list. When kernel modules containing MAC Framework policies are loaded, the policy module will use SYSINIT to invoke a registration function; when a policy module is unloaded, SYSINIT will likewise invoke a de-registration function. Registration may fail if a policy module is loaded more than once, if insufficient resources are available for the registration (for example, the policy might require labeling and insufficient labeling state might be available), or other policy prerequisites might not be met (some policies may only be loaded prior to boot). Likewise, de-registration may fail if a policy is flagged as not unloadable.


6.5.7 Entry Points

Kernel services interact with the MAC Framework in two ways: they invoke a series of APIs to notify the framework of relevant events, and they provide a policy-agnostic label structure pointer in security-relevant objects. The label pointer is maintained by the MAC Framework via label management entry points, and permits the Framework to offer a labeling service to policy modules through relatively non-invasive changes to the kernel subsystem maintaining the object. For example, label pointers have been added to processes, process credentials, sockets, pipes, vnodes, Mbufs, network interfaces, IP reassembly queues, and a variety of other security-relevant structures. Kernel services also invoke the MAC Framework when they perform important security decisions, permitting policy modules to augment those decisions based on their own criteria (possibly including data stored in security labels). Most of these security critical decisions will be explicit access control checks; however, some affect more general decision functions such as packet matching for sockets and label transition at program execution.


6.5.8 Policy Composition

When more than one policy module is loaded into the kernel at a time, the results of the policy modules will be composed by the framework using a composition operator. This operator is currently hard-coded, and requires that all active policies must approve a request for it to return success. As policies may return a variety of error conditions (success, access denied, object does not exist, ...), a precedence operator selects the resulting error from the set of errors returned by policies. In general, errors indicating that an object does not exist will be preferred to errors indicating that access to an object is denied. While it is not guaranteed that the resulting composition will be useful or secure, we have found that it is for many useful selections of policies. For example, traditional trusted systems often ship with two or more policies using a similar composition.


6.5.9 Labeling Support

As many interesting access control extensions rely on security labels on objects, the MAC Framework provides a set of policy-agnostic label management system calls covering a variety of user-expos