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

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