kernel
KrnAddExceptionHandler()
Synopsis
void * KrnAddExceptionHandler(
uint8_t num,
exhandler_t * handler,
void * handlerData,
void * handlerData2 );
Function
Register a CPU exception handler.
Inputs
num - CPU-specific exception number.
handler - Exception callback with the signature:
int ExceptionHandler(void *ctx, void *handlerData,
void *handlerData2);
handlerData - First user-defined callback argument.
handlerData2 - Second user-defined callback argument.
Result
Opaque handler handle, or NULL if registration fails.
Notes
The ctx callback argument is an opaque CPU context handle. Return a nonzero value from the callback to handle the exception and continue execution. If every handler returns zero, the exception is passed to the task's tc_TrapCode handler. This interface is preliminary and should be treated as private.
See also
KrnAddIRQHandler()
Synopsis
void * KrnAddIRQHandler(
uint32_t irq,
irqhandler_t * handler,
void * handlerData,
void * handlerData2 );
Function
Register a hardware IRQ handler.
Inputs
irq - Hardware-specific interrupt number.
handler - IRQ callback with the signature:
void IRQHandler(void *handlerData, void *handlerData2);
handlerData - First argument passed to the callback.
handlerData2 - Second argument passed to the callback.
Result
Opaque handler handle, or NULL if registration fails.
See also
KrnAllocCPUMask()
Synopsis
void * KrnAllocCPUMask();
Function
Allocate a zero-initialized CPU affinity mask.
Result
Pointer to the allocated mask, or NULL if allocation fails.
KrnAllocIRQ()
Synopsis
ULONG KrnAllocIRQ(
ULONG irq_type,
ULONG count );
Function
Allocate a consecutive range of interrupt identifiers.
Inputs
irq_type - Platform-defined interrupt type to allocate. count - Number of consecutive interrupt identifiers.
Result
First allocated interrupt identifier, or (ULONG)-1 on failure.
See also
KrnAllocPages()
Synopsis
void * KrnAllocPages(
void * addr,
uintptr_t length,
uint32_t flags );
Function
Allocate physical memory pages
Inputs
addr - Starting address of region which must be included in the
allocated region or NULL for the system to choose the
starting address. Normally you will supply NULL here.
length - Length of the memory region to allocate
flags - Flags describing type of needed memory. These are the same
flags as passed to exec.library/AllocMem().
Result
Real starting address of the allocated region.
Notes
Since this allocator is page-based, length will always be round up to system's memory page size. The same applies to starting address (if specified), it will be rounded down to page boundary. This function works only on systems with MMU support. Without MMU it will always return NULL.
See also
KrnBacktraceFromFrame()
Synopsis
ULONG KrnBacktraceFromFrame(
APTR frame_in,
APTR * out_pcs,
ULONG max_depth );
Function
Walks the current call stack using frame-pointer chaining and stores the return addresses into the provided array. The function starts from the frame pointer value supplied in frame_in and follows the saved link fields until the maximum depth is reached or the chain becomes invalid. This is a low-level helper used to capture a stack backtrace for diagnostic and crash reporting purposes.
Inputs
frame_in - Frame pointer of the starting stack frame. Typically this
should be the current function's frame pointer.
out_pcs - Pointer to an array of addresses which will receive the
collected return addresses.
max_depth - Maximum number of entries to store in the output array.
Result
Returns the number of valid entries written into the output array.
Example
APTR pcs[64];
ULONG depth;
depth = KrnBacktraceFromFrame((APTR)__builtin_frame_address(0), pcs, 64);
KrnPrintBacktrace("[Kernel] ", pcs, depth);
Notes
This function relies on standard frame-link conventions and requires code to be compiled with frame pointers enabled (for GCC or Clang, use -fno-omit-frame-pointer). The function performs basic safety checks on the frame chain and stops if the next frame pointer is invalid, unaligned, or lower than the previous one. It is safe to call from an exception or trap context.
Bugs
The function may produce incomplete results if compiler optimizations omit frame pointers, or if stack corruption has occurred prior to the call.
KrnBug()
Synopsis
int KrnBug(
const char * format,
va_list args );
Function
Output a formatted string to low-level debug output stream. The function supports the same set of formatting specifiers as standard C printf() function.
Inputs
format - A format string args - A list of arguments
Result
Number of successfully printed characters
KrnCause()
Synopsis
void KrnCause();
Function
Run software interrupt processing sequence
Inputs
None
Result
None
Notes
This entry point directly calls interrupt processing routine in supervisor mode. It neither performs any checks of caller status nor obeys interrupt enable state. This function is safe to call only from within user mode. This function is considered internal, and not meant to be called by user's software.
KrnClearCPUMask()
Synopsis
void KrnClearCPUMask(
void * mask );
Function
Clear all CPU selections in an affinity mask.
Inputs
mask - CPU affinity mask allocated by KrnAllocCPUMask().
Result
None.
KrnCli()
Synopsis
void KrnCli();
Function
Instantly disable interrupts.
Inputs
None
Result
None
Notes
This is low level function, it does not have nesting count and state tracking mechanism. It operates directly on the CPU. Normal applications should consider using exec.library/Disable(). This function isn't implemented on all platforms.
See also
KrnCPUInMask()
Synopsis
BOOL KrnCPUInMask(
uint32_t id,
void * mask );
Function
Determine whether a CPU is selected in an affinity mask.
Inputs
id - CPU number to test. mask - CPU affinity mask allocated by KrnAllocCPUMask().
Result
TRUE if the CPU is selected; FALSE otherwise.
KrnCreateContext()
Synopsis
void * KrnCreateContext();
Function
Allocate and initialize CPU context storage area.
Inputs
None.
Result
A pointer to a CPU context storage area.
Notes
CPU context storage is considered private and accessible only from within supevisor mode.
See also
KrnDeleteContext()
Synopsis
void KrnDeleteContext(
void * context );
Function
Free CPU context storage area
Inputs
context - a pointer to a CPU context storage previously allocated using
KrnCreateContext()
Result
None.
See also
KrnDispatch()
Synopsis
void KrnDispatch();
Function
Run the next available task
Inputs
None
Result
None
Notes
This entry point directly calls task dispatch routine in supervisor mode. It neither performs any checks of caller status nor obeys interrupt enable state. After calling this function, caller's task will be replaced by another one, and caller's state will be lost. This function is safe to call only from within user mode. This function is considered internal, and not meant to be called by user's software.
KrnDisplayAlert()
Synopsis
void KrnDisplayAlert(
uint32_t code,
const char * text );
Function
Inform the user about critical system failure.
Inputs
code - Corresponding alert code. text - A NULL-terminated text to print out. First three lines are assumed to be a header. Some implementations may print them centered inside a frame.
Result
None. This function is not guaranteed to return.
Notes
This function exists for system internal purposes. Please do not call it from within regular applications! In 99% of cases this function will halt or reboot the machine. Certain structures in RAM, as well as video hardware state, will be irreversibly destroyed. 'code' parameter is passed for convenience. Based on it, the system can make a decision to log the alert in debug output and continue, instead of displaying a message and halting. This function is currently experimental. Its definition may change.
KrnExitInterrupt()
Synopsis
void KrnExitInterrupt(
APTR ctx );
Function
Leave an interrupt using an architecture-defined saved context.
Inputs
ctx - Saved interrupt context to restore.
Notes
The architecture-specific implementation owns context restoration. The generic fallback performs no operation.
KrnFmtAlertInfo()
Synopsis
void KrnFmtAlertInfo(
STRPTR * TemplatePtr,
IPTR * ParamPtr );
Function
Supply architecture-specific details for an alert message.
Inputs
TemplatePtr - Pointer to storage for an alert format string. ParamPtr - Pointer to storage for its format parameters.
Notes
The generic implementation leaves both outputs unchanged. The all-pc implementation may replace the template and two parameter entries when an interrupt context is available. ParamPtr must provide space for at least two IPTR values.
See also
KrnFormatStr()
Synopsis
int KrnFormatStr(
void * putch,
const char * format,
va_list args );
Function
Format a string using C printf() convention, using 'putch' as character output function.
Inputs
putch - A pointer to the output function format - A format string args - A list of arguments A character output function needs to be declared as: int myPutCh(int char, void *KernelBase) It is expected to return 1 on success and 0 on failure.
Result
Number of successfully printed characters
KrnFreeCPUMask()
Synopsis
void KrnFreeCPUMask(
void * mask );
Function
Release storage used by a CPU affinity mask.
Inputs
mask - CPU affinity mask returned by KrnAllocCPUMask().
KrnFreeIRQ()
Synopsis
void KrnFreeIRQ(
ULONG start,
ULONG count );
Function
Release a range of interrupt identifiers allocated by KrnAllocIRQ().
Inputs
start - First interrupt identifier in the allocated range. count - Number of consecutive identifiers to release.
Result
None.
Notes
Release support depends on the target.
See also
KrnFreePages()
Synopsis
void KrnFreePages(
void * addr,
uintptr_t length );
Function
Release a region allocated by KrnAllocPages().
Inputs
addr - Starting address returned by KrnAllocPages(). length - Length of the region in bytes.
Result
None.
Notes
This function works only on systems with MMU support.
KrnGetBootInfo()
Synopsis
struct TagItem * KrnGetBootInfo();
Function
Return the kernel boot-information tag list.
Result
Pointer to the boot-information TagItem list (BootMsg).
See also
KrnGetCPUAttr()
Synopsis
intptr_t KrnGetCPUAttr(
uint32_t id,
uint32_t cpu );
Function
Get the value of a per-CPU attribute, for the given CPU. Currently defined attributes are: KATTR_CPULoad [.G] (ULONG) - Load of the CPU, 0 - 0xffffffff. KATTR_CPUFrequencyKHz [.G] (IPTR) - Current core clock, in kHz.
Inputs
id - ID of the attribute to get cpu - CPU number, 0 .. KrnGetCPUCount() - 1
Result
Value of the attribute, or -1 when the attribute (or the CPU) is not known.
Notes
This supersedes querying KrnGetSystemAttr() with the KATTR_CPULoad + n attribute range, which cannot scale beyond the range's size.
See also
KrnGetCPUCount()
Synopsis
unsigned int KrnGetCPUCount();
Function
Return total number of processors in the system
Inputs
None
Result
Number of running CPUs in this system
KrnGetCPUMask()
Synopsis
void KrnGetCPUMask(
uint32_t id,
void * mask );
Function
Add a CPU to an affinity mask.
Inputs
id - CPU number to select. mask - CPU affinity mask allocated by KrnAllocCPUMask().
Result
None.
KrnGetCPUNumber()
Synopsis
uint32_t KrnGetCPUNumber();
Function
Return number of the caller CPU
Inputs
None
Result
Number of the CPU on which the function is called
KrnGetIRQA()
Synopsis
void KrnGetIRQA(
ULONG irq,
struct TagItem * attribs );
void KrnGetIRQ(
ULONG irq,
TAG tag, ... );
Function
Query an IRQ using the passed in tags.
KrnGetScheduler()
Synopsis
KRN_SchedType KrnGetScheduler();
Function
Return the kernel scheduling policy.
Result
SCHED_RR (round-robin scheduling).
KrnGetSystemAttr()
Synopsis
intptr_t KrnGetSystemAttr(
uint32_t id );
Function
Get value of internal system attributes.
Currently defined attributes are:
KATTR_Architecture [.G] (char *) - Name of architecture the kernel built for.
KATTR_ClockSource [.G] APTR - Used Time Source Resource, or -1 if not set.
KATTR_SystemLoad [.G]
KATTR_CPULoad [.G] - Base of the legacy per-CPU load
attribute range. Add the CPU index;
KATTR_CPULoad_END is exclusive.
KATTR_AffinityMask [.G]
KATTR_PeripheralBase [.G] IPTR - (ARM only) peripheral IO Base address.
Inputs
id - ID of the attribute to get
Result
Value of the attribute
KrnInitMemory()
Synopsis
void KrnInitMemory(
struct MemHeader * mh );
Function
Initialize kernel memory management on a given memory region
Inputs
mh - Address of a filled in structure describing the region.
Result
None.
KrnIsSuper()
Synopsis
int KrnIsSuper();
Function
Determine if the caller is running in supervisor mode
Inputs
None
Result
Nonzero for supervisor mode, zero for user mode
Notes
Callers should only test the return value against zero. Nonzero values may actually be different, since they may carry some private implementation-dependent information (like CPU privilege level, for example).
KrnMapGlobal()
Synopsis
int KrnMapGlobal(
void * virt,
void * phys,
uint32_t length,
KRN_MapAttr flags );
Function
Map a physical memory region into the virtual address space.
Inputs
virt - Starting virtual address of the mapping. phys - Starting physical address of the region. length - Length of the mapping in bytes. flags - Mapping attributes specified by KRN_MapAttr.
KrnMayGetChar()
Synopsis
int KrnMayGetChar();
Function
Read a single character from low-level debug input stream
Inputs
None
Result
An ASCII code of the character or -1 if there's no character available
Notes
This function never waits. If there is no character available on the stream it just returns with -1
KrnModifyIRQA()
Synopsis
ULONG KrnModifyIRQA(
ULONG irq,
struct TagItem * attribs );
ULONG KrnModifyIRQ(
ULONG irq,
TAG tag, ... );
Function
Configure platform-specific attributes of an interrupt source.
Inputs
irq - Interrupt identifier to configure. attribs - Tag list of platform-specific interrupt attributes.
KrnModifyIRQHandler()
Synopsis
void KrnModifyIRQHandler(
void * handle,
void * handlerData,
void * handlerData2 );
Function
Update the arguments passed to a registered IRQ handler.
Inputs
handle - Handle returned by KrnAddIRQHandler(). handlerData - First argument passed to the callback. handlerData2 - Second argument passed to the callback.
Result
None.
See also
KrnObtainInput()
Synopsis
int KrnObtainInput();
Function
Take over low-level debug input hardware and initialize the input
Inputs
None
Result
Nonzero for success, zero for failure (for example there's no input channel)
KrnPrintBacktrace()
Synopsis
void KrnPrintBacktrace(
const STRPTR prefix,
APTR * pcs,
ULONG depth );
Function
Prints a formatted stack backtrace to the kernel debug output. Each entry in the provided address list is optionally resolved to a module and symbol name using the currently registered symbol resolver (if any). The output includes one line per program counter, showing the address and, when available, the function or symbol name with offset.
Inputs
prefix - Optional string prefix printed before the "Backtrace" header.
If NULL, "[Kernel] " is used.
pcs - Pointer to an array of program counter values representing the
captured call stack.
depth - Number of valid entries in the pcs array.
Result
None
Example
APTR pcs[64];
ULONG depth = KrnBacktraceFromFrame((APTR)__builtin_frame_address(0), pcs, 64);
KrnPrintBacktrace("[Crash] ", pcs, depth);
Notes
The function relies on an optional symbol resolver that can be registered with KrnRegisterSymResolver(). If no resolver is present, only raw addresses are printed. This function is safe to call from exception and trap context.
Bugs
None known.
KrnPutChar()
Synopsis
void KrnPutChar(
char c );
Function
Output a single character to low-level debug output stream
Inputs
c - A character to output
Result
None
KrnRegisterClockSource()
Synopsis
void KrnRegisterClockSource(
APTR CSBase,
struct TagItem * tstags );
void KrnRegisterClockSourceTags(
APTR CSBase,
TAG tag, ... );
Function
Select a clock source for the kernel when none is registered.
Inputs
CSBase - ClockSource resource base to register. tstags - Tag list; unused by this implementation.
Notes
A NULL CSBase or an existing clock source leaves the selection unchanged. Registration also requires AllocCSUnit() to succeed.
KrnRegisterSymResolver()
Synopsis
LONG KrnRegisterSymResolver(
KrnSymResolver_t resolver,
APTR priv );
Function
Registers a global kernel symbol resolver callback used for decoding instruction addresses into symbolic names. The resolver is used by the kernel when printing diagnostic backtraces or exception dumps. Only one resolver can be active at any time. The function fails if a resolver is already registered.
Inputs
resolver - Pointer to the resolver callback function. This function will
be called by the kernel with an instruction address and must
fill a KrnSymResolve structure with module and symbol
information.
priv - Optional user data pointer passed unmodified to the resolver
each time it is invoked.
Result
Returns 0 on success, or a negative value on error:
-1 resolver argument was NULL
-2 a resolver is already registered
Example
static LONG MyResolver(APTR addr, struct KrnSymResolve *out, APTR priv)
{
return DecodeLocationA(addr, priv);
}
if (KrnRegisterSymResolver(MyResolver, DebugBase) == 0)
KrnBug("Symbol resolver registered.\n");
Notes
This API allows an external component (typically debug.library) to provide symbol resolution for kernel stack traces. Once registered, the resolver will be used automatically by KrnPrintBacktrace() and the kernel crash handler. The function is safe to call from user or supervisor context.
Bugs
Only one resolver can be registered globally. There is currently no queuing or stacking mechanism.
KrnReleaseInput()
Synopsis
void KrnReleaseInput();
Function
Release low-level debug input hardware and hand it back to the operating system
Inputs
None
Result
None
KrnRemExceptionHandler()
Synopsis
void KrnRemExceptionHandler(
void * handle );
Function
Remove a registered CPU exception handler.
Inputs
handle - Handle returned by KrnAddExceptionHandler().
Result
None.
See also
KrnRemIRQHandler()
Synopsis
void KrnRemIRQHandler(
void * handle );
Function
Remove a registered hardware IRQ handler.
Inputs
handle - Handle returned by KrnAddIRQHandler().
Result
None.
See also
KrnSchedule()
Synopsis
void KrnSchedule();
Function
Run task scheduling sequence
Inputs
None
Result
None
Notes
This entry point directly calls task scheduling routine in supervisor mode. It neither performs any checks of caller status nor obeys interrupt enable state. This function is safe to call only from within user mode. This function is considered internal, and not meant to be called by user's software.
KrnScheduleCPU()
Synopsis
void KrnScheduleCPU(
void * cpu_mask );
Function
Run task scheduling sequence on all CPUs given in the cpu_mask
Inputs
Pointer to CPU Affinity mask.
Result
None
Notes
This entry point directly calls task scheduling routine in supervisor mode. It neither performs any checks of caller status nor obeys interrupt enable state. This function is safe to call only from within user mode. This function is considered internal, and not meant to be called by user's software.
KrnSetProtection()
Synopsis
void KrnSetProtection(
void * address,
uint32_t length,
KRN_MapAttr flags );
Function
Set the access permissions of a memory region.
Inputs
address - Start of the region.
length - Length of the region in bytes.
flags - Requested access permissions, expressed as KRN_MapAttr
attributes.
Result
None.
KrnSetScheduler()
Synopsis
void KrnSetScheduler(
KRN_SchedType sched );
Function
Currently leaves the kernel scheduling policy unchanged.
Inputs
sched - Requested scheduling policy (currently ignored).
See also
KrnSpinInit()
Synopsis
void KrnSpinInit(
spinlock_t * lock );
Function
Initialize a spinlock to its unlocked state.
Inputs
lock - Spinlock to initialize.
Notes
Initialization is architecture-specific; the generic fallback does not modify the lock.
See also
KrnSpinIsLocked()
Synopsis
int KrnSpinIsLocked(
spinlock_t * lock );
Function
Report whether a spinlock is locked.
Inputs
lock - Pointer to the spinlock to inspect.
Result
Nonzero if the spinlock is locked; zero if it is unlocked.
KrnSpinLock()
Synopsis
spinlock_t * KrnSpinLock(
spinlock_t * lock,
struct Hook * failhook,
ULONG mode );
Function
Acquire a spinlock in read or write mode, waiting if it is held on supported architectures.
Inputs
lock - Spinlock to acquire. failhook - Optional contention callback on supported targets. mode - SPINLOCK_MODE_READ or SPINLOCK_MODE_WRITE.
Result
The supplied spinlock pointer.
Notes
The all-pc implementation invokes failhook while waiting for a contended lock. ARM implementations do not invoke it. The generic fallback returns lock without acquiring it.
See also
KrnSpinTryLock()
Synopsis
spinlock_t * KrnSpinTryLock(
spinlock_t * lock,
ULONG mode );
Function
Attempt to acquire a spinlock in read or write mode without waiting for a current lock holder to release it.
Inputs
lock - Spinlock to acquire. mode - SPINLOCK_MODE_READ or SPINLOCK_MODE_WRITE.
Result
Lock pointer if acquired; NULL if the requested mode cannot be obtained on an implementation with spinlock support.
Notes
The generic fallback returns lock without acquiring it. The implementation and availability are architecture-specific.
See also
KrnSpinUnLock()
Synopsis
void KrnSpinUnLock(
spinlock_t * lock );
Function
Release one read or write acquisition of a spinlock.
Inputs
lock - Spinlock to release.
Notes
Unlocking is architecture-specific; the generic fallback does not modify the lock.
See also
KrnStatMemoryA()
Synopsis
ULONG KrnStatMemoryA(
ULONG flags,
struct TagItem * query );
ULONG KrnStatMemory(
ULONG flags,
TAG tag, ... );
Function
Get various statistics about memory usage
Inputs
query - An array of TagItems containing query specification. Each
TagItem consists of tag ID and a pointer to a value of
specified type which will contain the result of the query.
Available tag IDs are:
KMS_Free (IPTR) - Get amount of free memory in bytes
KMS_Total (IPTR) - Get total amount of memory in bytes
KMS_LargestAlloc (IPTR) - Get size of the largest allocated chunk in bytes
KMS_SmallestAlloc (IPTR) - Get size of the smallest allocated chunk in bytes
KMS_LargestFree (IPTR) - Get size of the largest free chunk in bytes
KMS_SmallestFree (IPTR) - Get size of the smallest free chunk in bytes
KMS_NumAlloc (IPTR) - Get number of allocated chunks
KMS_NumFree (IPTR) - Get number of free chunks
KMS_PageSize (ULONG) - Get memory page size
flags - Flags which specify physical properties of the memory to query.
These are the same flags as passed to exec.library/AllocMem().
Result
TRUE if the function worked, FALSE if MMU is not up and running on the system. If the function returns FALSE, values will stay uninitialized.
Notes
For all unknown tag IDs result values will be set to 0.
KrnSti()
Synopsis
void KrnSti();
Function
Instantly enable interrupts.
Inputs
None
Result
None
Notes
This is low level function, it does not have nesting count and state tracking mechanism. It operates directly on the CPU. Normal applications should consider using exec.library/Enable(). This function isn't implemented on all platforms.
See also
KrnSwitch()
Synopsis
void KrnSwitch();
Function
Save context of caller's task and dispatch the next available task
Inputs
None
Result
None
Notes
This entry point directly calls task switch routine in supervisor mode. It neither performs any checks of caller status nor obeys interrupt enable state. After calling this function, caller's task will be replaced by another one, and it's caller's responsibility to do anything to prevent task loss. This function is safe to call only from within user mode. This function is considered internal, and not meant to be called by user's software.
KrnTimeStamp()
Synopsis
UQUAD KrnTimeStamp();
Function
Read the architecture-specific timestamp counter.
Result
Architecture-specific timestamp value.
Notes
The timestamp unit and frequency depend on the architecture. The generic fallback returns zero. This is not wall-clock time.
KrnUnmapGlobal()
Synopsis
int KrnUnmapGlobal(
void * virt,
uint32_t length );
Function
Unmap a region of virtual address space.
Inputs
virt - Starting virtual address of the region. length - Length of the region in bytes.
See also
KrnUnregisterSymResolver()
Synopsis
LONG KrnUnregisterSymResolver(
KrnSymResolver_t resolver );
Function
Unregisters the previously installed kernel symbol resolver callback. The resolver function is used by the kernel to translate instruction addresses into module and symbol information when printing diagnostic or crash reports. Only one resolver can be active at a time.
Inputs
resolver - The resolver callback previously registered with
KrnRegisterSymResolver(). If this value does not match
the currently active resolver, no action is taken.
Result
0 if resolver matches the stored callback; -1 otherwise.
Example
if (old_resolver && KrnUnregisterSymResolver(old_resolver) == 0)
KrnBug("Symbol resolver removed.\n");
Notes
The resolver is typically implemented by debug.library and used by the kernel to produce symbolic backtraces when handling traps or exceptions. The function performs no locking and is safe to call from within the resolver itself, or from kernel exception context.
Bugs
None known.
KrnVirtualToPhysical()
Synopsis
void * KrnVirtualToPhysical(
void * virtual );
Function
Translate a virtual address to a physical address.
Inputs
virtual - Virtual address to translate.
Result
Translated address, or the original address when the target's translation rules leave it unchanged.


