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

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