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

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