psx.wiki

Kernel Library (libapi)

Provides an interface between applications and the PlayStation OS.

Kernel Library (libapi)
Librarylibapi.lib
Header Filelibapi.h, kernel.h

This is an old revision of this page, as edited by RemmyLee at 02:58, 23 October 2026. Edit this revision | Latest revision

Overview

The Kernel Library (libapi) provides the interface (API) by which applications control the basic parts of the PlayStation OS. These parts include the CPU and other hardware. Its services are root counter processing, event processing, thread processing, I/O processing, module processing, the controller and others.1

A program that uses libapi links with libapi.lib and includes libapi.h and kernel.h.1

System Designation File

SYSTEM.CNF is a system designation file. It reserves memory for the stack, the tasks and the events, and the kernel reads it at boot. Each line has the form KEYWORD = CONTENT. Keywords are uppercase one-byte characters with a space on either side of the equal sign, and when a keyword appears twice the first line takes precedence. The keywords are the following:1

Table 1: SYSTEM.CNF keywords
Keyword Contents Default Minimum
BOOT Device name, product number and version, for example cdrom:\SLUS_123.45;1 cdrom:PSX.EXE;1
STACK Stack pointer value at boot 0x801FFF00 0x8010000
TCB Number of task control blocks (hex) 4 1
EVENT Number of event control blocks (hex) 0x10 0

The numbers of task and event control blocks must satisfy TCB x 192 + EVENT x 32 + 544 < 4096.1

System Table Information

The task control blocks and the event control blocks are two of the tables that the kernel uses. To access them in a uniform way, the ToT (Table of Tables) structure at address 0x00000100 describes them, and the head member of each entry points to the actual table. The entries are the following:2

Table 2: ToT entries
Entry Table
0 System reserved
1 TCBH (pointer to the execution TCB)
2 Task control block (TCB) array
3 System reserved
4 Event control block array
5 to 31 System reserved

A TCB holds the information of one task, and the TCBH structure points to the TCB that is executing now. A program can therefore find the executing TCB through entry 1 of the ToT.2

Descriptors

The kernel refers to resources such as files and threads by descriptors. A descriptor is an unsigned 32-bit integer whose bits 31 to 24 hold the descriptor class, bits 23 to 16 are reserved and bits 15 to 0 hold the number of the entry in the kernel table. The classes are defined in kernel.h:3

Table 3: Descriptor classes
Macro Class Notes
DescTH Thread
DescHW Hardware Internal use
DescEV Event
DescRC Root counter
DescUEV User-defined flag
DescSW System call Internal use

A program obtains a descriptor from the Open function of the resource, such as OpenTh(), open() or OpenEvent(), uses it to name the resource, and releases it with the matching Close function.34

Callbacks

Libraries such as libgpu and libsnd that drive devices by DMA register callback functions in the kernel, which are executed after an event occurs. A callback runs in the callback context on its own callback stack, which is declared in libetc and lies in the application data area. The callback is called automatically when a DMA transfer completes, and it can report the end of the transfer by setting a flag or issuing an event.4

Critical Sections

Any function that modifies data in the kernel must run with interrupts inhibited, and such a section of code is called a critical section. Interrupts are inhibited right after system start until ResetCallback() enables them. EnterCriticalSection() inhibits them and ExitCriticalSection() enables them again. They are also inhibited at the start of an event handler, which returns to the original context with ReturnFromException().4

Interrupt Context

The normal execution of a program is its main flow. When an interrupt or exception occurs, the registers are saved in the execution TCB as the main flow context, and processing jumps to address 0x00000080, which holds the jump to the kernel interrupt dispatcher. When the interrupt has been processed the main flow context is restored.4

Event handlers and callbacks run in this interrupt context. Event handlers use the interrupt stack and callbacks use the callback stack. Halting interrupts for a long time affects the whole PlayStation. Such code is therefore designed to complete in the shortest possible time. It does not call functions that depend on interrupts, non-re-entrant functions that the main flow may call, or ReturnFromException() inside a callback.45

Kernel Reserved Memory

The kernel uses the first 64 KB of memory. The addresses that the user may use therefore begin at 0x00010000.5

Root Counters

The root counters provide time limits and timing adjustments for game programs. A counter counts up from zero to a 16-bit target value. At the target it generates an interrupt, which can be masked, clears itself to zero and counts again, so the values that can be read run from 0 to the target value minus 1. The vertical synch counter has a fixed target of 1 and therefore interrupts at each vertical blank. The counters are the following:5

Table 4: Root counters
Macro Root counter Notes
RCntCNT1 System clock Target value more than 2
RCntCNT2 System clock (8 spaces) Target value more than 2
RCntCNT3 Vertical synch Target value fixed at 1

One system clock tick is about 0.03 microseconds. The display timings are the following:6

Table 5: Counter timing
Counter event NTSC PAL Unit
Vertical sync 1/60 1/50 Second
Horizontal sync 63.56 64.00 Microsecond
Pixel display N x 0.0186243 N x 0.01879578 Microsecond

N depends on the display width:6

Table 6: Pixel display timing and display width
Display width N
256 pixels 10
320 pixels 8
384 pixels 7
512 pixels 5
640 pixels 4

The root counters use the hardware counting function, so the count continues while interrupts are disabled. StopRCnt() only stops the interrupts of the counter while the count goes on, and StartRCnt() only allows the interrupts. The mode of each counter selects interrupt or polling (RCntMdINTR, RCntMdNOINTR), the clock source and whether a gate condition applies (RCntMdGATE). With the gate, RCntCNT0 counts only outside the horizontal blank and RCntCNT1 only outside the vertical blank.67

All counters are stopped or free running right after the kernel starts, so a program always initializes a counter before it uses it. A counter interrupt cannot occur inside a critical section. The kernel itself reads the controller buttons on root counter 3, and the buttons cannot be read while that counter is stopped or uninitialized.7

Events

An event is a CPU exception or an interrupt from an external device. Because an event occurs asynchronously with the main program, the program either polls for it or installs an event handler that the kernel runs when it occurs. Handlers run in interrupt context on a 4 KB interrupt stack in the kernel area, and GetSysSp() returns the top address of that stack.7

An event is specified by two 32-bit integers called the cause descriptor and the event type:8

Table 7: Cause descriptors
Cause descriptor Contents Event type
RCntCNT0 to RCntCNT3 Root counter interrupt EvSpINT
File descriptor File input/output EvSpEIO
File descriptor File close EvSpCLOSE
HwCdRom CD-ROM decoder interrupt Described in libcd
HwSPU SPU interrupt EvSpTRAP
HwGPU GPU interrupt EvSpTRAP
HwPIO Extension parallel port interrupt EvSpTRAP
HwSIO Extension serial port interrupt EvSpTRAP
HwCPU Exceptions EvSpTRAP

OpenEvent() installs a handler from the cause descriptor, the event type, the event mode and the address of the handler. It returns a 32-bit event descriptor, which identifies the event to EnableEvent() and the other functions, and the kernel keeps the event in an event control block. When the event occurs the registers are saved and the handler runs. It ends with ReturnFromException(), which restores the registers and returns to the previous context.8

An event has one of four states. It is EvStUNUSED before it is opened, EvStWAIT after OpenEvent() and EvStACTIVE after EnableEvent(), when it may occur. DisableEvent() returns it to EvStWAIT:9

Table 8: Event states
Macro Contents Generation
EvStUNUSED Not opened Prohibited
EvStWAIT Event generation prohibited Prohibited
EvStACTIVE Event not yet generated Possible
EvStALREADY Event already generated Prohibited

With the mode EvMdINTR a handler is called when the event occurs and the event returns to EvStACTIVE. With EvMdNOINTR no handler is given, the event goes to EvStALREADY and the program must test it. DeliverEvent() generates an event from a cause descriptor and event type. UnDeliverEvent() or TestEvent() clears it from EvStALREADY back to EvStACTIVE. A program defines its own events with the DescUEV class.910

Threads

Threads give an application several flows of control, and the context changes when a switching function is called. The context of a thread is the complete contents of the registers, and a TCB stores it. When the kernel starts, the TCB array is allocated and element zero is opened as the execution TCB.10

OpenTh() opens further TCBs, whose status becomes TcbStACTIVE, and ChangeTh() runs one of them. ChangeTh() issues a software interrupt, saves its own context in the previous TCB, links the new TCB into the task status queue and resumes from it when the dispatcher ends. The context at an interrupt is stored in the TCB being executed and stays there until the next interrupt.1011

I/O Management

The kernel gives low-level access to files and logical devices. The structures it uses for input and output are defined in sys/file.h. Each device has a block size, and all data access is in multiples of it, so a fraction of a block in a request is discarded. The devices are the following:12

Table 9: I/O devices
Device name Contents Example of file designation
cdrom CD-ROM file system cdrom:PSX.EXE;1
bu Memory Card file system bu00:ABCD12345

The CD-ROM file system follows level 1 of ISO-9660 and has a block size of 2048 bytes. A file name is a base name of 8 characters and an extension of up to 3, with a version number, in capital letters, digits and underscore. Directories are at most 8 levels deep, and all sectors of a file are contiguous. A directory list is read only as far as it fits in one 2048-byte sector, which allows up to 45 directories and 30 files per directory with 8.3 names.12

The Memory Card file system has the device name buXY, where X is the port and Y the extension connector number. It has no directories, its file names are ASCII strings of up to 20 bytes without an extension, and its block size is 128 bytes. libcard mounts and initializes it.13

File descriptors 0 and 1 are the standard I/O stream. On the game unit both are a NULL device, and in the development environment standard output goes to Debug Message Window #0.13

Module Control

libapi loads and executes application modules in the PlayStation EXE format. An execution file contains code and data linked to fixed addresses, a start address, an initial gp value, and the start address and size of the initial data area. It begins with a header of 2048 bytes. The text section and the data section follow in multiples of 2048 bytes.13

The EXEC structure in the header holds the start address pc0 and the initial gp0 together with the address and size of the text and initialized data. It also holds the uninitialized data area (b_addr, b_size), which Exec() clears, and the stack area (s_addr, s_size). Exec() sets the stack pointer to s_addr + s_size unless s_addr is zero, so the stack must be defined explicitly or the current context is used.1314

Controller

libapi provides a low-level interface to the controllers, in which the application processes the received data directly and identifies each controller type. InitPAD() sets up two receive buffers with their maximum lengths, and StartPAD() starts reading at each vertical blank interrupt. The presence and state of a device are found from the contents of the buffer.14

The first byte of the buffer is 0x00 on success. The upper 4 bits of the second byte hold the terminal type, and the lower 4 bits hold half the number of bytes received:15

Table 10: Terminal types
Terminal type Controller name Model number
1 Mouse SCPH-1030
2 16-Button Analog SLPH-00001 (Namco)
3 Gun Controller SLPH-00014 (Konami)
4 16-Button SCPH-1080, 1150
5 Analog Joystick SCPH-1110
6 Gun Controller SLPH-00034 (Namco)
7 Analog Controller SCPH-1150
8 Multi Tap SCPH-1070

Bytes 2 and 3 hold the button status. A button bit is 1 when released and 0 when pressed. A mouse adds X and Y movement from -128 to 127, an analog joystick or analog controller adds four stick positions from 0 to 255 with 128 at center, and a Namco gun adds 16-bit X and Y positions. A Multi Tap returns 0x80 in byte 1 and then the data of ports A to D at offsets 2, 10, 18 and 26.151617

Kanji Fonts

The kernel ROM includes 16 x 16 dot bitmap kanji fonts. The characters are 15 x 15 dots and cover the JIS first standard kanji and non-kanji in Shift-JIS code. The font data is not stored consecutively. Krom2RawAdd() therefore returns the ROM address of the pattern of each character, which is read directly, with the upper left byte first and the most significant bit on the left.1718

Memory Allocation

There are three systems of memory allocation, all of which allocate by first fit. The malloc system calls the ROM routines and has a bug in which free() cannot release the whole area, which cannot be corrected in ROM. The malloc2 system is RAM-based and fixes the bug, and the malloc3 system, added in library 4.0, is a faster RAM-based version:1819

Table 11: Memory allocation systems
System Initialization Functions Speed and size
malloc InitHeap() malloc(), calloc(), realloc(), free() Small code
malloc2 InitHeap2() malloc2(), calloc2(), realloc2(), free2() Slow, large code
malloc3 InitHeap3() malloc3(), calloc3(), realloc3(), free3() Fast

Structures

In the tables below, Introduced is the run-time library version that added the item.20

libapi has the following structures:20

Table 12: libapi structures
Structure Introduced Purpose
DIRENTRY 2.x Directory entries.
EvCB 2.x Event Control Block.
EXEC 2.x Execution file data structure.
TCB 2.x Task Control Block.
TCBH 2.x Task Control Block Header.
ToT 2.x System Table Information.

Functions

libapi has the following functions:21

Table 13: libapi functions
Function Introduced Purpose
calloc2 3.6 Allocate a block in main memory.
calloc3 4.0 Allocate a block in main memory.
cd 2.x Change default directory.
ChangeClearPAD 2.x Set the control driver.
ChangeTh 2.x Change the thread to be executed.
close 2.x Close a file.
CloseEvent 2.x Close an event.
CloseTh 2.x Close a thread.
DeliverEvent 2.x Generate an event.
DisableEvent 2.x Disable an event.
DisablePAD 2.x Disable communication with the controller.
EnableEvent 2.x Enable occurrence of an event.
EnablePAD 2.x Enable communication with the controller.
EnterCriticalSection 2.x Disable interrupts.
erase 2.x Delete a file.
Exception 2.x Cause an interrupt.
Exec 2.x Execute an execution file.
ExitCriticalSection 2.x Enable interrupts.
firstfile 2.x Find the first file matching a filename.
FlushCache 2.x Flush instruction cache.
format 2.x Initialize file system.
free2 3.6 Free allocated memory blocks.
free3 4.0 Free allocated memory blocks.
GetConf 3.0 Get the kernel configuration.
GetCr 3.0 Get cause register value.
GetGp 3.0 Get value of gp register.
GetRCnt 2.x Get value of a root counter.
GetSp 3.0 Get value of stack pointer.
GetSr 3.0 Get value of status register.
GetSysSp 3.0 Get address of system stack.
InitHeap 2.0 Initialize heap area.
InitHeap2 3.6 Initialize heap area.
InitHeap3 4.0 Initialize heap area.
InitPAD 2.x Initialize the controller.
ioctl 2.x Control devices.
Krom2RawAdd 3.0 Get Kanji font pattern addresses.
Krom2RawAdd2 3.2 Get shift-JIS font pattern addresses.
Load 2.x Load an execution file.
LoadExec 2.x Load and execute an execution file.
LoadTest 2.x Load test.
lseek 2.x Move a file pointer.
malloc2 3.6 Allocate main memory.
malloc3 4.0 Allocate main memory.
nextfile 2.x Find the next file matching a filename.
open 2.x Open a file.
OpenEvent 2.x Open an event.
OpenTh 2.x Open a thread.
read 2.x Read data from a file.
realloc2 3.6 Change a block’s memory allocation.
realloc3 4.0 Change a block’s memory allocation.
rename 2.x Change a file name.
ResetRCnt 2.x Reset a root counter.
ReturnFromException 2.x Return from exception.
SetConf 2.x Modify the kernel configuration.
SetMem 2.x Modify the valid memory size.
SetRCnt 2.x Set a root counter.
SetSp 2.x Set the stack pointer.
StartPAD 2.x Start reading the controller.
StartRCnt 2.x Start a root counter.
StopPAD 2.x Stop reading the controller.
StopRCnt 2.x Stop a root counter.
SwEnterCriticalSection 2.x Suppress interrupts.
SwExitCriticalSection 2.x Enable interrupts.
SystemError 2.x Display the system error screen.
TestEvent 2.x Test an event.
undelete 2.x Resurrect a file.
UnDeliverEvent 2.x Cancel an event.
WaitEvent 2.x Wait for the occurrence of an event.
write 2.x Write data to a file.
_96_init 2.x Install the ISO-9660 file system.
_96_remove 2.x Remove the ISO-9660 file system.
_boot 2.x Reboot the system.
_get_errno 3.0 Get the latest I/O error code.
_get_error 3.0 Get an error code for a file descriptor.

References


  1. ^ a b c d Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-3.

  2. ^ a b Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-4.

  3. ^ a b Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-5.

  4. ^ a b c d e Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-6.

  5. ^ a b c Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-7.

  6. ^ a b c Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-8.

  7. ^ a b c Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-9.

  8. ^ a b Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-10.

  9. ^ a b Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-11.

  10. ^ a b c Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-12.

  11. ^ Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-13.

  12. ^ a b Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-15.

  13. ^ a b c d Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-16.

  14. ^ a b Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-17.

  15. ^ a b Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-18.

  16. ^ Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-19.

  17. ^ a b Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-20.

  18. ^ a b Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-21.

  19. ^ Sony Computer Entertainment Inc. Run-Time Library Overview. Run-Time Library 4.4. January 1999. Page 2-22.

  20. ^ a b Sony Computer Entertainment Inc. Run-Time Library Reference. Run-Time Library 4.4. January 1999. Pages 1-3 to 1-8.

  21. ^ Sony Computer Entertainment Inc. Run-Time Library Reference. Run-Time Library 4.4. January 1999. Pages 1-9 to 1-82.

Categories: Libraries