Modules/UHCI - Fixed edge case NULL dereference
[tpg/acess2.git] / Kernel / arch / x86 / lib.c
1 /*
2  * Acess2
3  *
4  * arch/x86/lib.c
5  * - General arch-specific stuff
6  */
7 #include <acess.h>
8 #include <threads_int.h>
9
10 #define TRACE_LOCKS     0
11
12 #define DEBUG_TO_E9     1
13 #define DEBUG_TO_SERIAL 1
14 #define SERIAL_PORT     0x3F8
15 #define GDB_SERIAL_PORT 0x2F8
16
17 // === IMPRORTS ===
18 #if TRACE_LOCKS
19 extern struct sShortSpinlock    glDebug_Lock;
20 extern tMutex   glPhysAlloc;
21 #define TRACE_LOCK_COND (Lock != &glDebug_Lock && Lock != &glThreadListLock && Lock != &glPhysAlloc.Protector)
22 //#define TRACE_LOCK_COND       (Lock != &glDebug_Lock && Lock != &glPhysAlloc.Protector)
23 #endif
24
25 extern int      GetCPUNum(void);
26
27 // === PROTOTYPES ==
28 Uint64  __divmod64(Uint64 Num, Uint64 Den, Uint64 *Rem);
29 Uint64  __udivdi3(Uint64 Num, Uint64 Den);
30 Uint64  __umoddi3(Uint64 Num, Uint64 Den);
31
32 // === GLOBALS ===
33  int    gbDebug_SerialSetup = 0;
34  int    gbGDB_SerialSetup = 0;
35
36 // === CODE ===
37 /**
38  * \brief Determine if a short spinlock is locked
39  * \param Lock  Lock pointer
40  */
41 int IS_LOCKED(struct sShortSpinlock *Lock)
42 {
43         return !!Lock->Lock;
44 }
45
46 /**
47  * \brief Check if the current CPU has the lock
48  * \param Lock  Lock pointer
49  */
50 int CPU_HAS_LOCK(struct sShortSpinlock *Lock)
51 {
52         return Lock->Lock == GetCPUNum() + 1;
53 }
54
55 /**
56  * \brief Acquire a Short Spinlock
57  * \param Lock  Lock pointer
58  * 
59  * This type of mutex should only be used for very short sections of code,
60  * or in places where a Mutex_* would be overkill, such as appending
61  * an element to linked list (usually two assignement lines in C)
62  * 
63  * \note This type of lock halts interrupts, so ensure that no timing
64  * functions are called while it is held. As a matter of fact, spend as
65  * little time as possible with this lock held
66  * \note If \a STACKED_LOCKS is set, this type of spinlock can be nested
67  */
68 void SHORTLOCK(struct sShortSpinlock *Lock)
69 {
70          int    IF;
71          int    cpu = GetCPUNum() + 1;
72         
73         // Save interrupt state
74         __ASM__ ("pushf;\n\tpop %0" : "=r"(IF));
75         IF &= 0x200;    // AND out all but the interrupt flag
76         
77         #if TRACE_LOCKS
78         if( TRACE_LOCK_COND )
79         {
80                 //Log_Log("LOCK", "%p locked by %p", Lock, __builtin_return_address(0));
81                 Debug("%i %p obtaining %p (Called by %p)", cpu-1,  __builtin_return_address(0), Lock, __builtin_return_address(1));
82         }
83         #endif
84         
85         __ASM__("cli");
86         
87         // Wait for another CPU to release
88         __ASM__(
89                 "1:\n\t"
90                 "xor %%eax, %%eax;\n\t"
91                 "lock cmpxchgl %0, (%1);\n\t"
92                 "jnz 1b;\n\t"
93                 :: "r"(cpu), "r"(&Lock->Lock)
94                 : "eax" // EAX clobbered
95                 );
96         
97         Lock->IF = IF;
98         
99         #if TRACE_LOCKS
100         if( TRACE_LOCK_COND )
101         {
102                 //Log_Log("LOCK", "%p locked by %p", Lock, __builtin_return_address(0));
103                 Debug("%i %p locked by %p\t%p", cpu-1, Lock, __builtin_return_address(0), __builtin_return_address(1));
104 //              Debug("got it");
105         }
106         #endif
107 }
108 /**
109  * \brief Release a short lock
110  * \param Lock  Lock pointer
111  */
112 void SHORTREL(struct sShortSpinlock *Lock)
113 {       
114         #if TRACE_LOCKS
115         if( TRACE_LOCK_COND )
116         {
117                 //Log_Log("LOCK", "%p released by %p", Lock, __builtin_return_address(0));
118                 Debug("Lock %p released by %p\t%p", Lock, __builtin_return_address(0), __builtin_return_address(1));
119         }
120         #endif
121         
122         // Lock->IF can change anytime once Lock->Lock is zeroed
123         if(Lock->IF) {
124                 Lock->Lock = 0;
125                 __ASM__ ("sti");
126         }
127         else {
128                 Lock->Lock = 0;
129         }
130 }
131
132 // === DEBUG IO ===
133 #if USE_GDB_STUB
134 int putDebugChar(char ch)
135 {
136         if(!gbGDB_SerialSetup) {
137                 outb(GDB_SERIAL_PORT + 1, 0x00);    // Disable all interrupts
138                 outb(GDB_SERIAL_PORT + 3, 0x80);    // Enable DLAB (set baud rate divisor)
139                 outb(GDB_SERIAL_PORT + 0, 0x0C);    // Set divisor to 12 (lo byte) 9600 baud
140                 outb(GDB_SERIAL_PORT + 1, 0x00);    //  (base is         (hi byte)
141                 outb(GDB_SERIAL_PORT + 3, 0x03);    // 8 bits, no parity, one stop bit (8N1)
142                 outb(GDB_SERIAL_PORT + 2, 0xC7);    // Enable FIFO with 14-byte threshold and clear it
143                 outb(GDB_SERIAL_PORT + 4, 0x0B);    // IRQs enabled, RTS/DSR set
144                 gbGDB_SerialSetup = 1;
145         }
146         while( (inb(GDB_SERIAL_PORT + 5) & 0x20) == 0 );
147         outb(GDB_SERIAL_PORT, ch);
148         return 0;
149 }
150 int getDebugChar(void)
151 {
152         if(!gbGDB_SerialSetup) {
153                 outb(GDB_SERIAL_PORT + 1, 0x00);    // Disable all interrupts
154                 outb(GDB_SERIAL_PORT + 3, 0x80);    // Enable DLAB (set baud rate divisor)
155                 outb(GDB_SERIAL_PORT + 0, 0x0C);    // Set divisor to 12 (lo byte) 9600 baud
156                 outb(GDB_SERIAL_PORT + 1, 0x00);    //                   (hi byte)
157                 outb(GDB_SERIAL_PORT + 3, 0x03);    // 8 bits, no parity, one stop bit
158                 outb(GDB_SERIAL_PORT + 2, 0xC7);    // Enable FIFO with 14-byte threshold and clear it
159                 outb(GDB_SERIAL_PORT + 4, 0x0B);    // IRQs enabled, RTS/DSR set
160                 gbGDB_SerialSetup = 1;
161         }
162         while( (inb(GDB_SERIAL_PORT + 5) & 1) == 0)     ;
163         return inb(GDB_SERIAL_PORT);
164 }
165 #endif  /* USE_GDB_STUB */
166
167 void Debug_PutCharDebug(char ch)
168 {
169         #if DEBUG_TO_E9
170         __asm__ __volatile__ ( "outb %%al, $0xe9" :: "a"(((Uint8)ch)) );
171         #endif
172         
173         #if DEBUG_TO_SERIAL
174         if(!gbDebug_SerialSetup) {
175                 outb(SERIAL_PORT + 1, 0x00);    // Disable all interrupts
176                 outb(SERIAL_PORT + 3, 0x80);    // Enable DLAB (set baud rate divisor)
177                 outb(SERIAL_PORT + 0, 0x0C);    // Set divisor to 12 (lo byte) 9600 baud
178                 outb(SERIAL_PORT + 1, 0x00);    //                   (hi byte)
179                 outb(SERIAL_PORT + 3, 0x03);    // 8 bits, no parity, one stop bit
180                 outb(SERIAL_PORT + 2, 0xC7);    // Enable FIFO with 14-byte threshold and clear it
181                 outb(SERIAL_PORT + 4, 0x0B);    // IRQs enabled, RTS/DSR set
182                 gbDebug_SerialSetup = 1;
183         }
184         while( (inb(SERIAL_PORT + 5) & 0x20) == 0 );
185         outb(SERIAL_PORT, ch);
186         #endif
187 }
188
189 void Debug_PutStringDebug(const char *String)
190 {
191         while(*String)
192                 Debug_PutCharDebug(*String++);
193 }
194
195 // === IO Commands ===
196 void outb(Uint16 Port, Uint8 Data)
197 {
198         __asm__ __volatile__ ("outb %%al, %%dx"::"d"(Port),"a"(Data));
199 }
200 void outw(Uint16 Port, Uint16 Data)
201 {
202         __asm__ __volatile__ ("outw %%ax, %%dx"::"d"(Port),"a"(Data));
203 }
204 void outd(Uint16 Port, Uint32 Data)
205 {
206         __asm__ __volatile__ ("outl %%eax, %%dx"::"d"(Port),"a"(Data));
207 }
208 Uint8 inb(Uint16 Port)
209 {
210         Uint8   ret;
211         __asm__ __volatile__ ("inb %%dx, %%al":"=a"(ret):"d"(Port));
212         return ret;
213 }
214 Uint16 inw(Uint16 Port)
215 {
216         Uint16  ret;
217         __asm__ __volatile__ ("inw %%dx, %%ax":"=a"(ret):"d"(Port));
218         return ret;
219 }
220 Uint32 ind(Uint16 Port)
221 {
222         Uint32  ret;
223         __asm__ __volatile__ ("inl %%dx, %%eax":"=a"(ret):"d"(Port));
224         return ret;
225 }
226
227 /**
228  * \fn void *memset(void *Dest, int Val, size_t Num)
229  * \brief Do a byte granuality set of Dest
230  */
231 void *memset(void *Dest, int Val, size_t Num)
232 {
233         Uint32  val = Val&0xFF;
234         val |= val << 8;
235         val |= val << 16;
236         __asm__ __volatile__ (
237                 "rep stosl;\n\t"
238                 "mov %3, %%ecx;\n\t"
239                 "rep stosb"
240                 :: "D" (Dest), "a" (val), "c" (Num/4), "r" (Num&3));
241         return Dest;
242 }
243 /**
244  * \brief Set double words
245  */
246 void *memsetd(void *Dest, Uint32 Val, size_t Num)
247 {
248         __asm__ __volatile__ ("rep stosl" :: "D" (Dest), "a" (Val), "c" (Num));
249         return Dest;
250 }
251
252 /**
253  * \fn int memcmp(const void *m1, const void *m2, size_t Num)
254  * \brief Compare two pieces of memory
255  */
256 int memcmp(const void *m1, const void *m2, size_t Num)
257 {
258         const Uint8     *d1 = m1;
259         const Uint8     *d2 = m2;
260         if( Num == 0 )  return 0;       // No bytes are always identical
261         
262         while(Num--)
263         {
264                 if(*d1 != *d2)
265                         return *d1 - *d2;
266                 d1 ++;
267                 d2 ++;
268         }
269         return 0;
270 }
271
272 /**
273  * \fn void *memcpy(void *Dest, const void *Src, size_t Num)
274  * \brief Copy \a Num bytes from \a Src to \a Dest
275  */
276 void *memcpy(void *Dest, const void *Src, size_t Num)
277 {
278         tVAddr  dst = (tVAddr)Dest;
279         tVAddr  src = (tVAddr)Src;
280         if( (dst & 3) != (src & 3) )
281         {
282                 __asm__ __volatile__ ("rep movsb" :: "D" (dst), "S" (src), "c" (Num));
283 //              Debug("\nmemcpy:Num=0x%x by %p (UA)", Num, __builtin_return_address(0));
284         }
285         #if 1
286         else if( Num > 128 && (dst & 15) == (src & 15) )
287         {
288                 char    tmp[16+15];     // Note, this is a hack to save/restor xmm0
289                  int    count = 16 - (dst & 15);
290 //              Debug("\nmemcpy:Num=0x%x by %p (SSE)", Num, __builtin_return_address(0));
291                 if( count < 16 )
292                 {
293                         Num -= count;
294                         __asm__ __volatile__ ("rep movsb" : "=D"(dst),"=S"(src): "0"(dst), "1"(src), "c"(count));
295                 }
296                 
297                 count = Num / 16;
298                 __asm__ __volatile__ (
299                         "movdqa 0(%5), %%xmm0;\n\t"
300                         "1:\n\t"
301                         "movdqa 0(%1), %%xmm0;\n\t"
302                         "movdqa %%xmm0, 0(%0);\n\t"
303                         "add $16,%0;\n\t"
304                         "add $16,%1;\n\t"
305                         "loop 1b;\n\t"
306                         "movdqa %%xmm0, 0(%5);\n\t"
307                         : "=r"(dst),"=r"(src)
308                         : "0"(dst), "1"(src), "c"(count), "r" (((tVAddr)tmp+15)&~15)
309                         );
310
311                 count = Num & 15;
312                 if(count)
313                         __asm__ __volatile__ ("rep movsb" :: "D"(dst), "S"(src), "c"(count));
314         }
315         #endif
316         else
317         {
318 //              Debug("\nmemcpy:Num=0x%x by %p", Num, __builtin_return_address(0));
319                 __asm__ __volatile__ (
320                         "rep movsl;\n\t"
321                         "mov %3, %%ecx;\n\t"
322                         "rep movsb"
323                         :: "D" (Dest), "S" (Src), "c" (Num/4), "r" (Num&3));
324         }
325         return Dest;
326 }
327
328 /**
329  * \fn void *memcpyd(void *Dest, const void *Src, size_t Num)
330  * \brief Copy \a Num DWORDs from \a Src to \a Dest
331  */
332 void *memcpyd(void *Dest, const void *Src, size_t Num)
333 {
334         __asm__ __volatile__ ("rep movsl" :: "D" (Dest), "S" (Src), "c" (Num));
335         return Dest;
336 }
337
338 #include "../helpers.h"
339
340 DEF_DIVMOD(64);
341
342 Uint64 DivMod64U(Uint64 Num, Uint64 Div, Uint64 *Rem)
343 {
344         if( Div < 0x100000000ULL && Num < 0xFFFFFFFF * Div ) {
345                 Uint32  rem, ret_32;
346                 __asm__ __volatile__(
347                         "div %4"
348                         : "=a" (ret_32), "=d" (rem)
349                         : "a" ( (Uint32)(Num & 0xFFFFFFFF) ), "d" ((Uint32)(Num >> 32)), "r" (Div)
350                         );
351                 if(Rem) *Rem = rem;
352                 return ret_32;
353         }
354
355         return __divmod64(Num, Div, Rem);
356 }
357
358 /**
359  * \fn Uint64 __udivdi3(Uint64 Num, Uint64 Den)
360  * \brief Divide two 64-bit integers
361  */
362 Uint64 __udivdi3(Uint64 Num, Uint64 Den)
363 {
364         if(Den == 0) {
365                 __asm__ __volatile__ ("int $0x0");
366                 return -1;
367         }
368         // Common speedups
369         if(Num <= 0xFFFFFFFF && Den <= 0xFFFFFFFF)
370                 return (Uint32)Num / (Uint32)Den;
371         if(Den == 1)    return Num;
372         if(Den == 2)    return Num >> 1;        // Speed Hacks
373         if(Den == 4)    return Num >> 2;        // Speed Hacks
374         if(Den == 8)    return Num >> 3;        // Speed Hacks
375         if(Den == 16)   return Num >> 4;        // Speed Hacks
376         if(Den == 32)   return Num >> 5;        // Speed Hacks
377         if(Den == 1024) return Num >> 10;       // Speed Hacks
378         if(Den == 2048) return Num >> 11;       // Speed Hacks
379         if(Den == 4096) return Num >> 12;
380         if(Num < Den)   return 0;
381         if(Num < Den*2) return 1;
382         if(Num == Den*2)        return 2;
383
384         return __divmod64(Num, Den, NULL);
385 }
386
387 /**
388  * \fn Uint64 __umoddi3(Uint64 Num, Uint64 Den)
389  * \brief Get the modulus of two 64-bit integers
390  */
391 Uint64 __umoddi3(Uint64 Num, Uint64 Den)
392 {
393         Uint64  ret = 0;
394         if(Den == 0) {
395                 __asm__ __volatile__ ("int $0x0");      // Call Div by Zero Error
396                 return -1;
397         }
398         if(Den == 1)    return 0;       // Speed Hacks
399         if(Den == 2)    return Num & 1; // Speed Hacks
400         if(Den == 4)    return Num & 3; // Speed Hacks
401         if(Den == 8)    return Num & 7; // Speed Hacks
402         if(Den == 16)   return Num & 15;        // Speed Hacks
403         if(Den == 32)   return Num & 31;        // Speed Hacks
404         if(Den == 1024) return Num & 1023;      // Speed Hacks
405         if(Den == 2048) return Num & 2047;      // Speed Hacks
406         if(Den == 4096) return Num & 4095;      // Speed Hacks
407         
408         if(Num >> 32 == 0 && Den >> 32 == 0)
409                 return (Uint32)Num % (Uint32)Den;
410         
411         __divmod64(Num, Den, &ret);
412         return ret;
413 }
414
415
416 // --- EXPORTS ---
417 EXPORT(memcpy); EXPORT(memset);
418 EXPORT(memcmp);
419 //EXPORT(memcpyw);      EXPORT(memsetw);
420 EXPORT(memcpyd);        EXPORT(memsetd);
421 EXPORT(inb);    EXPORT(inw);    EXPORT(ind);
422 EXPORT(outb);   EXPORT(outw);   EXPORT(outd);
423 EXPORT(__udivdi3);      EXPORT(__umoddi3);
424
425 EXPORT(SHORTLOCK);
426 EXPORT(SHORTREL);
427 EXPORT(IS_LOCKED);

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