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

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