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

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