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

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