Kernel - Cleaning up a little (implemented MIN and MAX functions)
[tpg/acess2.git] / Kernel / include / acess.h
1 /*
2  * AcessOS Microkernel Version
3  * acess.h
4  */
5 #ifndef _ACESS_H
6 #define _ACESS_H
7 /**
8  * \file acess.h
9  * \brief Acess2 Kernel API Core
10  */
11
12 //! NULL Pointer
13 #define NULL    ((void*)0)
14 //! Pack a structure
15 #define PACKED  __attribute__((packed))
16 //! Mark a function as not returning
17 #define NORETURN        __attribute__((noreturn))
18 //! Mark a parameter as unused
19 #define UNUSED(x)       UNUSED_##x __attribute__((unused))
20 //! Get the offset of a member in a structure
21 #define offsetof(st, m) ((Uint)((char *)&((st *)(0))->m - (char *)0 ))
22
23 /**
24  * \name Boolean constants
25  * \{
26  */
27 #define TRUE    1
28 #define FALSE   0
29 /**
30  * \}
31  */
32
33 #include <arch.h>
34 #include <stdarg.h>
35 #include "errno.h"
36
37 // --- Types ---
38 typedef  int    tPID;   //!< Process ID type
39 typedef  int    tTID;   //!< Thread ID Type
40 typedef Uint    tUID;   //!< User ID Type
41 typedef Uint    tGID;   //!< Group ID Type
42 typedef Sint64  tTimestamp;     //!< Timestamp (miliseconds since 00:00 1 Jan 1970)
43 typedef Sint64  tTime;  //!< Same again
44 typedef struct sShortSpinlock   tShortSpinlock; //!< Opaque (kinda) spinlock
45 typedef int     bool;   //!< Boolean type
46
47 // --- Helper Macros ---
48 /**
49  * \name Helper Macros
50  * \{
51  */
52 #define CONCAT(x,y) x ## y
53 #define EXPAND_CONCAT(x,y) CONCAT(x,y)
54 #define STR(x) #x
55 #define EXPAND_STR(x) STR(x)
56
57 extern char     __buildnum[];
58 #define BUILD_NUM       ((int)(Uint)&__buildnum)
59 extern const char gsGitHash[];
60
61 #define VER2(major,minor)       ((((major)&0xFF)<<8)|((minor)&0xFF))
62 /**
63  * \}
64  */
65
66 /**
67  * \name Per-Thread Configuration Settings
68  * \{
69  */
70 enum eConfigTypes {
71         CFGT_NULL,
72         CFGT_INT,
73         CFGT_HEAPSTR,
74         CFGT_PTR
75 };
76 enum eConfigs {
77         CFG_VFS_CWD,
78         CFG_VFS_MAXFILES,
79         CFG_VFS_CHROOT,
80         CFG_ERRNO,
81         NUM_CFG_ENTRIES
82 };
83 #define CFGINT(id)      (*Threads_GetCfgPtr(id))
84 #define CFGPTR(id)      (*(void**)Threads_GetCfgPtr(id))
85
86 #define errno   (CFGINT(CFG_ERRNO))
87 /**
88  * \}
89  */
90
91 // === CONSTANTS ===
92 // --- Memory Flags --
93 /**
94  * \name Memory Flags
95  * \{
96  * \todo Move to mm_virt.h
97  */
98 #define MM_PFLAG_RO             0x01    // Writes disallowed
99 #define MM_PFLAG_EXEC   0x02    // Allow execution
100 #define MM_PFLAG_NOPAGE 0x04    // Prevent from being paged out
101 #define MM_PFLAG_COW    0x08    // Copy-On-Write
102 #define MM_PFLAG_KERNEL 0x10    // Kernel-Only (Ring0)
103 /**
104  * \}
105  */
106 // --- Interface Flags & Macros
107 /**
108  * \name Flags for Proc_Clone
109  * \{
110  */
111 //! Clone the entire process
112 #define CLONE_VM        0x10
113 /**
114  * \}
115  */
116
117 // === Types ===
118 /**
119  * \brief Thread root function
120  * 
121  * Function pointer prototype of a thread entrypoint. When it
122  * returns, Threads_Exit is called
123  */
124 typedef void (*tThreadFunction)(void*);
125
126 // === Kernel Export Macros ===
127 /**
128  * \name Kernel exports
129  * \{
130  */
131 //! Kernel symbol definition
132 typedef struct sKernelSymbol {
133         const char      *Name;  //!< Symbolic name
134         tVAddr  Value;  //!< Value of the symbol
135 } tKernelSymbol;
136 //! Export a pointer symbol (function/array)
137 #define EXPORT(_name)   tKernelSymbol _kexp_##_name __attribute__((section ("KEXPORT"),unused))={#_name, (tVAddr)_name}
138 //! Export a variable
139 #define EXPORTV(_name)  tKernelSymbol _kexp_##_name __attribute__((section ("KEXPORT"),unused))={#_name, (tVAddr)&_name}
140 //! Export a symbol under another name
141 #define EXPORTAS(_sym,_name)    tKernelSymbol _kexp_##_name __attribute__((section ("KEXPORT"),unused))={#_name, (tVAddr)_sym}
142 /**
143  * \}
144  */
145
146 // === FUNCTIONS ===
147 // --- IRQs ---
148 /**
149  * \name IRQ hander registration
150  * \{
151  */
152 extern int      IRQ_AddHandler(int Num, void (*Callback)(int, void*), void *Ptr);
153 extern void     IRQ_RemHandler(int Handle);
154 /**
155  * \}
156  */
157
158 // --- Logging ---
159 /**
160  * \name Logging to kernel ring buffer
161  * \{
162  */
163 extern void     Log_KernelPanic(const char *Ident, const char *Message, ...);
164 extern void     Log_Panic(const char *Ident, const char *Message, ...);
165 extern void     Log_Error(const char *Ident, const char *Message, ...);
166 extern void     Log_Warning(const char *Ident, const char *Message, ...);
167 extern void     Log_Notice(const char *Ident, const char *Message, ...);
168 extern void     Log_Log(const char *Ident, const char *Message, ...);
169 extern void     Log_Debug(const char *Ident, const char *Message, ...);
170 /**
171  * \}
172  */
173
174 // --- Debug ---
175 /**
176  * \name Debugging and Errors
177  * \{
178  */
179 extern void     Debug_KernelPanic(void);        //!< Initiate a kernel panic
180 extern void     Panic(const char *Msg, ...);    //!< Print a panic message (initiates a kernel panic)
181 extern void     Warning(const char *Msg, ...);  //!< Print a warning message
182 extern void     LogF(const char *Fmt, ...);     //!< Print a log message without a trailing newline
183 extern void     Log(const char *Fmt, ...);      //!< Print a log message
184 extern void     Debug(const char *Fmt, ...);    //!< Print a debug message (doesn't go to KTerm)
185 extern void     LogV(const char *Fmt, va_list Args);    //!< va_list Log message
186 extern void     Debug_Enter(const char *FuncName, const char *ArgTypes, ...);
187 extern void     Debug_Log(const char *FuncName, const char *Fmt, ...);
188 extern void     Debug_Leave(const char *FuncName, char RetType, ...);
189 extern void     Debug_HexDump(const char *Header, const void *Data, Uint Length);
190 #define UNIMPLEMENTED() Warning("'%s' unimplemented", __func__)
191 #if DEBUG
192 # define ENTER(_types...)       Debug_Enter((char*)__func__, _types)
193 # define LOG(_fmt...)   Debug_Log((char*)__func__, _fmt)
194 # define LEAVE(_t...)   Debug_Leave((char*)__func__, _t)
195 # define LEAVE_RET(_t,_v...)    do{LEAVE(_t,_v);return _v;}while(0)
196 # define LEAVE_RET0()   do{LEAVE('-');return;}while(0)
197 #else
198 # define ENTER(...)
199 # define LOG(...)
200 # define LEAVE(...)
201 # define LEAVE_RET(_t,_v...)    return (_v)
202 # define LEAVE_RET0()   return
203 #endif
204 #if SANITY
205 # define ASSERT(expr) do{if(!(expr))Panic("%s: Assertion '"#expr"' failed",(char*)__func__);}while(0)
206 #else
207 # define ASSERT(expr)
208 #endif
209 /**
210  * \}
211  */
212
213 // --- IO ---
214 #if NO_IO_BUS
215 #define inb(a)  (Log_Panic("Arch", "ARMv7 does not support in*/out* (%s:%i)", __FILE__, __LINE__),0)
216 #define inw(a)  inb(a)
217 #define ind(a)  inb(a)
218 #define inq(a)  inb(a)
219 #define outb(a,b)       inb(a)
220 #define outw(a,b)       inb(a)
221 #define outd(a,b)       inb(a)
222 #define outq(a,b)       inb(a)
223 #else
224 /**
225  * \name I/O Memory Access
226  * \{
227  */
228 extern void     outb(Uint16 Port, Uint8 Data);
229 extern void     outw(Uint16 Port, Uint16 Data);
230 extern void     outd(Uint16 Port, Uint32 Data);
231 extern void     outq(Uint16 Port, Uint64 Data);
232 extern Uint8    inb(Uint16 Port);
233 extern Uint16   inw(Uint16 Port);
234 extern Uint32   ind(Uint16 Port);
235 extern Uint64   inq(Uint16 Port);
236 /**
237  * \}
238  */
239 #endif
240 // --- Memory Management ---
241 /**
242  * \name Memory Management
243  * \{
244  * \todo Move to mm_virt.h
245  */
246 /**
247  * \brief Allocate a physical page at \a VAddr
248  * \param VAddr Virtual Address to allocate at
249  * \return Physical address allocated
250  */
251 extern tPAddr   MM_Allocate(tVAddr VAddr) __attribute__ ((warn_unused_result));
252 /**
253  * \brief Deallocate a page
254  * \param VAddr Virtual address to unmap
255  */
256 extern void     MM_Deallocate(tVAddr VAddr);
257 /**
258  * \brief Map a physical page at \a PAddr to \a VAddr
259  * \param VAddr Target virtual address
260  * \param PAddr Physical address to map
261  * \return Boolean Success
262  */
263 extern int      MM_Map(tVAddr VAddr, tPAddr PAddr);
264 /**
265  * \brief Get the physical address of \a Addr
266  * \param Addr  Address of the page to get the physical address of
267  * \return Physical page mapped at \a Addr
268  */
269 extern tPAddr   MM_GetPhysAddr(tVAddr Addr);
270 /**
271  * \brief Set the access flags on a page
272  * \param VAddr Virtual address of the page
273  * \param Flags New flags value
274  * \param Mask  Flags to set
275  */
276 extern void     MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask);
277 /**
278  * \brief Get the flags on a flag
279  * \param VAddr Virtual address of page
280  * \return Flags value of the page
281  */
282 extern Uint     MM_GetFlags(tVAddr VAddr);
283 /**
284  * \brief Checks is a memory range is user accessable
285  * \param VAddr Base address to check
286  * \return 1 if the memory is all user-accessable, 0 otherwise
287  */
288 #define MM_IsUser(VAddr)        (!(MM_GetFlags((VAddr))&MM_PFLAG_KERNEL))
289 /**
290  * \brief Temporarily map a page into the address space
291  * \param PAddr Physical addres to map
292  * \return Virtual address of page in memory
293  * \note There is only a limited ammount of slots avaliable
294  */
295 extern tVAddr   MM_MapTemp(tPAddr PAddr);
296 /**
297  * \brief Free a temporarily mapped page
298  * \param VAddr Allocate virtual addres of page
299  */
300 extern void     MM_FreeTemp(tVAddr VAddr);
301 /**
302  * \brief Map a physcal address range into the virtual address space
303  * \param PAddr Physical address to map in
304  * \param Number        Number of pages to map
305  */
306 extern tVAddr   MM_MapHWPages(tPAddr PAddr, Uint Number);
307 /**
308  * \brief Allocates DMA physical memory
309  * \param Pages Number of pages required
310  * \param MaxBits       Maximum number of bits the physical address can have
311  * \param PhysAddr      Pointer to the location to place the physical address allocated
312  * \return Virtual address allocate
313  */
314 extern tVAddr   MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr);
315 /**
316  * \brief Unmaps an allocated hardware range
317  * \param VAddr Virtual address allocate by ::MM_MapHWPages or ::MM_AllocDMA
318  * \param Number        Number of pages to free
319  */
320 extern void     MM_UnmapHWPages(tVAddr VAddr, Uint Number);
321 /**
322  * \brief Allocate a single physical page
323  * \return Physical address allocated
324  */
325 extern tPAddr   MM_AllocPhys(void);
326 /**
327  * \brief Allocate a contiguous range of physical pages
328  * \param Pages Number of pages to allocate
329  * \param MaxBits       Maximum number of address bits allowed
330  * \return First physical address allocated
331  */
332 extern tPAddr   MM_AllocPhysRange(int Pages, int MaxBits);
333 /**
334  * \brief Reference a physical page
335  * \param PAddr Page to mark as referenced
336  */
337 extern void     MM_RefPhys(tPAddr PAddr);
338 /**
339  * \brief Dereference a physical page
340  * \param PAddr Page to dereference
341  */
342 extern void     MM_DerefPhys(tPAddr PAddr);
343 /**
344  * \brief Get the number of times a page has been referenced
345  * \param PAddr Address to check
346  * \return Reference count for the page
347  */
348 extern int      MM_GetRefCount(tPAddr PAddr);
349 /**
350  * \brief Set the node associated with a page
351  * \param PAddr Physical address of page
352  * \param Node  Node pointer (tVFS_Node)
353  * \return Boolean failure
354  * \retval 0    Success
355  * \retval 1    Page not allocated
356  */
357 extern int      MM_SetPageNode(tPAddr PAddr, void *Node);
358 /**
359  * \brief Get the node associated with a page
360  * \param PAddr Physical address of page
361  * \param Node  Node pointer (tVFS_Node) destination
362  * \return Boolean failure
363  * \retval 0    Success
364  * \retval 1    Page not allocated
365  */
366 extern int      MM_GetPageNode(tPAddr PAddr, void **Node);
367 /**
368  * \}
369  */
370
371 // --- Memory Manipulation ---
372 /**
373  * \name Memory Manipulation
374  * \{
375  */
376 extern int      memcmp(const void *m1, const void *m2, size_t count);
377 extern void     *memcpy(void *dest, const void *src, size_t count);
378 extern void     *memcpyd(void *dest, const void *src, size_t count);
379 extern void     *memmove(void *dest, const void *src, size_t len);
380 extern void     *memset(void *dest, int val, size_t count);
381 extern void     *memsetd(void *dest, Uint32 val, size_t count);
382 /**
383  * \}
384  */
385 /**
386  * \name Memory Validation
387  * \{
388  */
389 extern int      CheckString(const char *String);
390 extern int      CheckMem(const void *Mem, int Num);
391 /**
392  * \}
393  */
394
395 // --- Endianness ---
396 /**
397  * \name Endianness Swapping
398  * \{
399  */
400 #ifdef __BIG_ENDIAN__
401 #define LittleEndian16(_val)    SwapEndian16(_val)
402 #define LittleEndian32(_val)    SwapEndian32(_val)
403 #define BigEndian16(_val)       (_val)
404 #define BigEndian32(_val)       (_val)
405 #else
406 #define LittleEndian16(_val)    (_val)
407 #define LittleEndian32(_val)    (_val)
408 #define BigEndian16(_val)       SwapEndian16(_val)
409 #define BigEndian32(_val)       SwapEndian32(_val)
410 #endif
411 extern Uint16   SwapEndian16(Uint16 Val);
412 extern Uint32   SwapEndian32(Uint32 Val);
413 /**
414  * \}
415  */
416
417 // --- Strings ---
418 /**
419  * \name Strings
420  * \{
421  */
422 extern int      vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args);
423 extern int      sprintf(char *__s, const char *__format, ...);
424 extern size_t   strlen(const char *Str);
425 extern char     *strcpy(char *__dest, const char *__src);
426 extern char     *strncpy(char *__dest, const char *__src, size_t max);
427 extern char     *strcat(char *__dest, const char *__src);
428 extern char     *strncat(char *__dest, const char *__src, size_t n);
429 extern int      strcmp(const char *__str1, const char *__str2);
430 extern int      strncmp(const char *Str1, const char *Str2, size_t num);
431 extern int      strucmp(const char *Str1, const char *Str2);
432 // strdup macro is defined in heap.h
433 extern char     *_strdup(const char *File, int Line, const char *Str);
434 extern char     **str_split(const char *__str, char __ch);
435 extern char     *strchr(const char *__s, int __c);
436 extern int      strpos(const char *Str, char Ch);
437 extern int      strpos8(const char *str, Uint32 search);
438 extern void     itoa(char *buf, Uint64 num, int base, int minLength, char pad);
439 extern int      atoi(const char *string);
440 extern int      ReadUTF8(const Uint8 *str, Uint32 *Val);
441 extern int      WriteUTF8(Uint8 *str, Uint32 Val);
442 extern int      ModUtil_SetIdent(char *Dest, const char *Value);
443 extern int      ModUtil_LookupString(const char **Array, const char *Needle);
444
445 extern Uint8    ByteSum(const void *Ptr, int Size);
446 extern int      UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
447 /**
448  * \}
449  */
450
451 /**
452  * \brief Get a random number
453  * \return Random number
454  * \note Current implementation is a linear congruency
455  */
456 extern int      rand(void);
457 /**
458  * \brief Call a function with a variable number of arguments
459  * \param Function      Function address
460  * \param NArgs Number of entries in \a Args
461  * \param Args  Array of arguments
462  * \return Integer from called Function
463  */
464 extern int      CallWithArgArray(void *Function, int NArgs, Uint *Args);
465
466 // --- Heap ---
467 #include <heap.h>
468
469 // --- Modules ---
470 /**
471  * \name Modules
472  * \{
473  */
474 extern int      Module_LoadMem(void *Buffer, Uint Length, const char *ArgStr);
475 extern int      Module_LoadFile(const char *Path, const char *ArgStr);
476 /**
477  * \}
478  */
479
480 // --- Timing ---
481 /**
482  * \name Time and Timing
483  * \{
484  */
485 /**
486  * \brief Create a timestamp from a time
487  */
488 extern Sint64   timestamp(int sec, int mins, int hrs, int day, int month, int year);
489 /**
490  * \brief Gets the current timestamp (miliseconds since Midnight 1st January 1970)
491  */
492 extern Sint64   now(void);
493 /**
494  * \brief Timer callback function
495  */
496 typedef void (tTimerCallback)(void *);
497 /**
498  * \brief Creates a one-shot timer
499  * \param Delta Period of the timer
500  * \param Callback      Function to call each time
501  * \param Argument      Argument to pass to the callback
502  */
503 extern int      Time_CreateTimer(int Delta, tTimerCallback *Callback, void *Argument);
504 /**
505  * \brief Removed an active timer
506  */
507 extern void     Time_RemoveTimer(int ID);
508 /**
509  * \brief Wait for a period of milliseconds
510  */
511 extern void     Time_Delay(int Delay);
512 /**
513  * \}
514  */
515
516 // --- Threads ---
517 /**
518  * \name Threads and Processes
519  * \{
520  */
521 extern int      Proc_SpawnWorker(void (*Fcn)(void*), void *Data);
522 extern int      Proc_Spawn(const char *Path);
523 extern void     Threads_Exit(int TID, int Status);
524 extern void     Threads_Yield(void);
525 extern void     Threads_Sleep(void);
526 extern int      Threads_WakeTID(tTID Thread);
527 extern tPID     Threads_GetPID(void);
528 extern tTID     Threads_GetTID(void);
529 extern tUID     Threads_GetUID(void);
530 extern tGID     Threads_GetGID(void);
531 extern int      SpawnTask(tThreadFunction Function, void *Arg);
532 extern Uint     *Threads_GetCfgPtr(int Id);
533 extern int      Threads_SetName(const char *NewName);
534 /**
535  * \}
536  */
537
538 // --- Simple Math ---
539 //! Divide and round up
540 extern int      DivUp(int num, int dem);
541 //! Divide and Modulo 64-bit unsigned integer
542 extern Uint64   DivMod64U(Uint64 Num, Uint64 Den, Uint64 *Rem);
543
544 static inline int MIN(int a, int b) { return a < b ? a : b; }
545 static inline int MAX(int a, int b) { return a > b ? a : b; }
546
547 #include <binary_ext.h>
548 #include <vfs_ext.h>
549 #include <mutex.h>
550
551 #endif

UCC git Repository :: git.ucc.asn.au