433feaac97dec9574b185c4b8837943afef6663b
[tpg/acess2.git] / KernelLand / Kernel / arch / x86 / acpica.c
1 /*
2  * Acess2 Kernel (x86 Core)
3  * - By John Hodge (thePowersGang)
4  *
5  * acpica.c
6  * - ACPICA Interface
7  */
8 #define ACPI_DEBUG_OUTPUT       0
9 #define DEBUG   0
10 #define _AcpiModuleName "Shim"
11 #define _COMPONENT      "Acess"
12 #include <acpi.h>
13 #include <timers.h>
14 #include <mutex.h>
15 #include <semaphore.h>
16
17 #define ONEMEG  (1024*1024)
18
19 // === GLOBALS ===
20 // - RSDP Address from uEFI
21 tPAddr  gACPI_RSDPOverride = 0;
22
23 // === PROTOTYPES ===
24 int     ACPICA_Initialise(void);
25 void    ACPI_int_InterruptProxy(int IRQ, void *data);
26
27
28 // === CODE ===
29 int ACPICA_Initialise(void)
30 {
31         ACPI_STATUS     rv;
32
33         #ifdef ACPI_DEBUG_OUTPUT
34         AcpiDbgLevel = ACPI_DB_ALL;
35         #endif
36
37         rv = AcpiInitializeSubsystem();
38         if( ACPI_FAILURE(rv) )
39         {
40                 Log_Error("ACPI", "AcpiInitializeSubsystem: %i", rv);
41                 return -1;
42         }
43         
44         rv = AcpiInitializeTables(NULL, 16, FALSE);
45         if( ACPI_FAILURE(rv) )
46         {
47                 Log_Error("ACPI", "AcpiInitializeTables: %i", rv);
48                 AcpiTerminate();
49                 return -1;
50         }
51
52         rv = AcpiLoadTables();
53         if( ACPI_FAILURE(rv) )
54         {
55                 Log_Error("ACPI", "AcpiLoadTables: %i", rv);
56                 AcpiTerminate();
57                 return -1;
58         }
59         
60         rv = AcpiEnableSubsystem(ACPI_FULL_INITIALIZATION);
61         if( ACPI_FAILURE(rv) )
62         {
63                 Log_Error("ACPI", "AcpiEnableSubsystem: %i", rv);
64                 AcpiTerminate();
65                 return -1;
66         }
67
68         return 0;
69 }
70
71 // ---------------
72 // --- Exports ---
73 // ---------------
74 ACPI_STATUS AcpiOsInitialize(void)
75 {
76         return AE_OK;
77 }
78
79 ACPI_STATUS AcpiOsTerminate(void)
80 {
81         return AE_OK;
82 }
83
84 ACPI_PHYSICAL_ADDRESS AcpiOsGetRootPointer(void)
85 {
86         ACPI_SIZE       val;
87         ACPI_STATUS     rv;
88
89         if( gACPI_RSDPOverride )
90                 return gACPI_RSDPOverride;      
91
92         rv = AcpiFindRootPointer(&val);
93         if( ACPI_FAILURE(rv) )
94                 return 0;
95
96         LOG("val=0x%x", val);
97         
98         return val;
99         // (Or use EFI)
100 }
101
102 ACPI_STATUS AcpiOsPredefinedOverride(const ACPI_PREDEFINED_NAMES *PredefinedObject, ACPI_STRING *NewValue)
103 {
104         *NewValue = NULL;
105         return AE_OK;
106 }
107
108 ACPI_STATUS AcpiOsTableOverride(ACPI_TABLE_HEADER *ExisitingTable, ACPI_TABLE_HEADER **NewTable)
109 {
110         *NewTable = NULL;
111         return AE_OK;
112 }
113
114 ACPI_STATUS AcpiOsPhysicalTableOverride(ACPI_TABLE_HEADER *ExisitingTable, ACPI_PHYSICAL_ADDRESS *NewAddress, UINT32 *NewTableLength)
115 {
116         *NewAddress = 0;
117         return AE_OK;
118 }
119
120 // -- Memory Management ---
121 #if USE_ACESS_ACPI_CACHE
122 struct sACPICache
123 {
124         Uint16  nObj;
125         Uint16  ObjectSize;
126         char    *Name;
127         void    *First;
128         char    ObjectStates[];
129 };
130
131 ACPI_STATUS AcpiOsCreateCache(char *CacheName, UINT16 ObjectSize, UINT16 MaxDepth, ACPI_CACHE_T **ReturnCache)
132 {
133         tACPICache      *ret;
134          int    namelen = (CacheName ? strlen(CacheName) : 0) + 1;
135         LOG("CacheName=%s, ObjSize=%x, MaxDepth=%x", CacheName, ObjectSize, MaxDepth);
136
137         if( ReturnCache == NULL || ObjectSize < 16) {
138                 return AE_BAD_PARAMETER;
139         }
140
141         namelen = (namelen + 3) & ~3;
142
143         ret = malloc(sizeof(*ret) + MaxDepth*sizeof(char) + namelen + MaxDepth*ObjectSize);
144         if( !ret ) {
145                 Log_Notice("ACPICA", "%s: malloc() fail", __func__);
146                 return AE_NO_MEMORY;
147         }
148
149         ret->nObj = MaxDepth;
150         ret->ObjectSize = ObjectSize;
151         ret->Name = (char*)(ret->ObjectStates + MaxDepth);
152         ret->First = ret->Name + namelen;
153         if( CacheName )
154                 strcpy(ret->Name, CacheName);
155         else
156                 ret->Name[0] = 0;
157         memset(ret->ObjectStates, 0, sizeof(char)*MaxDepth);
158         
159         LOG("Allocated cache %p '%s' (%i x 0x%x)", ret, CacheName, MaxDepth, ObjectSize);
160         
161         *ReturnCache = ret;
162         
163         return AE_OK;
164 }
165
166 ACPI_STATUS AcpiOsDeleteCache(ACPI_CACHE_T *Cache)
167 {
168         if( Cache == NULL )
169                 return AE_BAD_PARAMETER;
170
171         free(Cache);
172         return AE_OK;
173 }
174
175 ACPI_STATUS AcpiOsPurgeCache(ACPI_CACHE_T *Cache)
176 {
177         ENTER("pCache", Cache);
178         if( Cache == NULL ) {
179                 LEAVE('i', AE_BAD_PARAMETER);
180                 return AE_BAD_PARAMETER;
181         }
182
183         memset(Cache->ObjectStates, 0, sizeof(char)*Cache->nObj);
184
185         LEAVE('i', AE_OK);
186         return AE_OK;
187 }
188
189 void *AcpiOsAcquireObject(ACPI_CACHE_T *Cache)
190 {
191         ENTER("pCache", Cache);
192         LOG("Called by %p", __builtin_return_address(0));
193         for(int i = 0; i < Cache->nObj; i ++ )
194         {
195                 if( !Cache->ObjectStates[i] ) {
196                         Cache->ObjectStates[i] = 1;
197                         void *rv = (char*)Cache->First + i*Cache->ObjectSize;
198                         if(!rv) {
199                                 LEAVE('n');
200                                 return NULL;
201                         }
202                         memset(rv, 0, Cache->ObjectSize);
203                         LEAVE('p', rv);
204                         return rv;
205                 }
206         }
207
208         Log_Debug("ACPICA", "AcpiOsAcquireObject: All %i objects used in '%s'",
209                 Cache->nObj, Cache->Name);
210
211         LEAVE('n');
212         return NULL;
213 }
214
215 ACPI_STATUS AcpiOsReleaseObject(ACPI_CACHE_T *Cache, void *Object)
216 {
217         if( Cache == NULL || Object == NULL )
218                 return AE_BAD_PARAMETER;
219         ENTER("pCache pObject", Cache, Object);
220
221         tVAddr delta = (tVAddr)Object - (tVAddr)Cache->First;
222         delta /= Cache->ObjectSize;
223         LOG("Cache=%p, delta = %i, (limit %i)", Cache, delta, Cache->nObj);
224         
225         if( delta >= Cache->nObj ) {
226                 LEAVE('i', AE_BAD_PARAMETER);
227                 return AE_BAD_PARAMETER;
228         }
229         
230         Cache->ObjectStates[delta] = 0;
231
232         LEAVE('i', AE_OK);
233         return AE_OK;
234 }
235 #endif
236
237 void *AcpiOsMapMemory(ACPI_PHYSICAL_ADDRESS PhysicalAddress, ACPI_SIZE Length)
238 {
239         if( PhysicalAddress < ONEMEG )
240                 return (void*)(KERNEL_BASE | PhysicalAddress);
241         
242         Uint    ofs = PhysicalAddress & (PAGE_SIZE-1);
243         int npages = (ofs + Length + (PAGE_SIZE-1)) / PAGE_SIZE;
244         char *maploc = (void*)MM_MapHWPages(PhysicalAddress, npages);
245         if(!maploc) {
246                 LOG("Mapping %P+0x%x failed", PhysicalAddress, Length);
247                 return NULL;
248         }
249 //      MM_DumpTables(0, -1);
250         void *rv = maploc + ofs;
251         LOG("Map (%P+%i pg) to %p", PhysicalAddress, npages, rv);
252         return rv;
253 }
254
255 void AcpiOsUnmapMemory(void *LogicalAddress, ACPI_SIZE Length)
256 {
257         if( (tVAddr)LogicalAddress - KERNEL_BASE < ONEMEG )
258                 return ;
259
260         LOG("%p", LogicalAddress);
261
262         Uint    ofs = (tVAddr)LogicalAddress & (PAGE_SIZE-1);
263         int npages = (ofs + Length + (PAGE_SIZE-1)) / PAGE_SIZE;
264         // TODO: Validate `Length` is the same as was passed to AcpiOsMapMemory
265         MM_UnmapHWPages( (tVAddr)LogicalAddress, npages);
266 }
267
268 ACPI_STATUS AcpiOsGetPhysicalAddress(void *LogicalAddress, ACPI_PHYSICAL_ADDRESS *PhysicalAddress)
269 {
270         if( LogicalAddress == NULL || PhysicalAddress == NULL )
271                 return AE_BAD_PARAMETER;
272         
273         tPAddr  rv = MM_GetPhysAddr(LogicalAddress);
274         if( rv == 0 )
275                 return AE_ERROR;
276         *PhysicalAddress = rv;
277         return AE_OK;
278 }
279
280 void *AcpiOsAllocate(ACPI_SIZE Size)
281 {
282         return malloc(Size);
283 }
284
285 void AcpiOsFree(void *Memory)
286 {
287         return free(Memory);
288 }
289
290 BOOLEAN AcpiOsReadable(void *Memory, ACPI_SIZE Length)
291 {
292         return CheckMem(Memory, Length);
293 }
294
295 BOOLEAN AcpiOsWritable(void *Memory, ACPI_SIZE Length)
296 {
297         // TODO: Actually check if it's writable
298         return CheckMem(Memory, Length);
299 }
300
301
302 // --- Threads ---
303 ACPI_THREAD_ID AcpiOsGetThreadId(void)
304 {
305         return Threads_GetTID() + 1;
306 }
307
308 ACPI_STATUS AcpiOsExecute(ACPI_EXECUTE_TYPE Type, ACPI_OSD_EXEC_CALLBACK Function, void *Context)
309 {
310         // TODO: Need to store currently executing functions
311         if( Function == NULL )
312                 return AE_BAD_PARAMETER;
313         Proc_SpawnWorker(Function, Context);
314         return AE_OK;
315 }
316
317 void AcpiOsSleep(UINT64 Milliseconds)
318 {
319         Time_Delay(Milliseconds);
320 }
321
322 void AcpiOsStall(UINT32 Microseconds)
323 {
324         // TODO: need a microsleep function
325         Microseconds += (1000-1);
326         Microseconds /= 1000;
327         Time_Delay(Microseconds);
328 }
329
330 void AcpiOsWaitEventsComplete(void)
331 {
332         // TODO: 
333 }
334
335 // --- Mutexes etc ---
336 ACPI_STATUS AcpiOsCreateMutex(ACPI_MUTEX *OutHandle)
337 {
338         LOG("()");
339         if( !OutHandle )
340                 return AE_BAD_PARAMETER;
341         tMutex  *ret = calloc( sizeof(tMutex), 1 );
342         if( !ret ) {
343                 Log_Notice("ACPICA", "%s: malloc() fail", __func__);
344                 return AE_NO_MEMORY;
345         }
346         ret->Name = "AcpiOsCreateMutex";
347         *OutHandle = ret;
348         
349         return AE_OK;
350 }
351
352 void AcpiOsDeleteMutex(ACPI_MUTEX Handle)
353 {
354         //  TODO: Need `Mutex_Destroy`
355         Mutex_Acquire(Handle);
356         free(Handle);
357 }
358
359 ACPI_STATUS AcpiOsAcquireMutex(ACPI_MUTEX Handle, UINT16 Timeout)
360 {
361         if( Handle == NULL )
362                 return AE_BAD_PARAMETER;
363
364         Mutex_Acquire(Handle);  
365
366         return AE_OK;
367 }
368
369 void AcpiOsReleaseMutex(ACPI_MUTEX Handle)
370 {
371         Mutex_Release(Handle);
372 }
373
374 ACPI_STATUS AcpiOsCreateSemaphore(UINT32 MaxUnits, UINT32 InitialUnits, ACPI_SEMAPHORE *OutHandle)
375 {
376         LOG("(MaxUnits=%i,InitialUnits=%i)", MaxUnits, InitialUnits);
377         if( !OutHandle )
378                 return AE_BAD_PARAMETER;
379         tSemaphore      *ret = calloc( sizeof(tSemaphore), 1 );
380         if( !ret ) {
381                 Log_Notice("ACPICA", "%s: malloc() fail", __func__);
382                 return AE_NO_MEMORY;
383         }
384         
385         Semaphore_Init(ret, InitialUnits, MaxUnits, "AcpiOsCreateSemaphore", "");
386         *OutHandle = ret;
387         return AE_OK;
388 }
389
390 ACPI_STATUS AcpiOsDeleteSemaphore(ACPI_SEMAPHORE Handle)
391 {
392         if( !Handle )
393                 return AE_BAD_PARAMETER;
394
395         free(Handle);   
396
397         return AE_OK;
398 }
399
400 ACPI_STATUS AcpiOsWaitSemaphore(ACPI_SEMAPHORE Handle, UINT32 Units, UINT16 Timeout)
401 {
402         if( !Handle )
403                 return AE_BAD_PARAMETER;
404
405         // Special case
406         if( Timeout == 0 )
407         {
408                 // NOTE: Possible race condition
409                 if( Semaphore_GetValue(Handle) >= Units ) {
410                         Semaphore_Wait(Handle, Units);
411                         return AE_OK;
412                 }
413                 return AE_TIME;
414         }
415
416         tTime   start = now();
417         UINT32  rem = Units;
418         while(rem && now() - start < Timeout)
419         {
420                 rem -= Semaphore_Wait(Handle, rem);
421         }
422
423         if( rem ) {
424                 Semaphore_Signal(Handle, Units - rem);
425                 return AE_TIME;
426         }
427
428         return AE_OK;
429 }
430
431 ACPI_STATUS AcpiOsSignalSemaphore(ACPI_SEMAPHORE Handle, UINT32 Units)
432 {
433         if( !Handle )
434                 return AE_BAD_PARAMETER;
435
436         // TODO: Support AE_LIMIT detection early (to avoid blocks)
437
438         // NOTE: Blocks
439         int rv = Semaphore_Signal(Handle, Units);
440         if( rv != Units )
441                 return AE_LIMIT;
442         
443         return AE_OK;
444 }
445
446 ACPI_STATUS AcpiOsCreateLock(ACPI_SPINLOCK *OutHandle)
447 {
448         LOG("()");
449         if( !OutHandle )
450                 return AE_BAD_PARAMETER;
451         tShortSpinlock  *lock = calloc(sizeof(tShortSpinlock), 1);
452         if( !lock )
453                 return AE_NO_MEMORY;
454         
455         *OutHandle = lock;
456         return AE_OK;
457 }
458
459 void AcpiOsDeleteLock(ACPI_SPINLOCK Handle)
460 {
461         free(Handle);
462 }
463
464 ACPI_CPU_FLAGS AcpiOsAcquireLock(ACPI_SPINLOCK Handle)
465 {
466         SHORTLOCK(Handle);
467         return 0;
468 }
469
470 void AcpiOsReleaseLock(ACPI_SPINLOCK Handle, ACPI_CPU_FLAGS Flags)
471 {
472         SHORTREL(Handle);
473 }
474
475 // --- Interrupt handling ---
476 #define N_INT_LEVELS    16
477 ACPI_OSD_HANDLER        gaACPI_InterruptHandlers[N_INT_LEVELS];
478 void    *gaACPI_InterruptData[N_INT_LEVELS];
479  int    gaACPI_InterruptHandles[N_INT_LEVELS];
480
481 void ACPI_int_InterruptProxy(int IRQ, void *data)
482 {
483         if( !gaACPI_InterruptHandlers[IRQ] )
484                 return ;
485         gaACPI_InterruptHandlers[IRQ](gaACPI_InterruptData[IRQ]);
486 }
487
488 ACPI_STATUS AcpiOsInstallInterruptHandler(UINT32 InterruptLevel, ACPI_OSD_HANDLER Handler, void *Context)
489 {
490         if( InterruptLevel >= N_INT_LEVELS || Handler == NULL )
491                 return AE_BAD_PARAMETER;
492         if( gaACPI_InterruptHandlers[InterruptLevel] )
493                 return AE_ALREADY_EXISTS;
494
495         gaACPI_InterruptHandlers[InterruptLevel] = Handler;
496         gaACPI_InterruptData[InterruptLevel] = Context;
497
498         gaACPI_InterruptHandles[InterruptLevel] = IRQ_AddHandler(InterruptLevel, ACPI_int_InterruptProxy, NULL);
499         return AE_OK;
500 }
501
502 ACPI_STATUS AcpiOsRemoveInterruptHandler(UINT32 InterruptLevel, ACPI_OSD_HANDLER Handler)
503 {
504         if( InterruptLevel >= N_INT_LEVELS || Handler == NULL )
505                 return AE_BAD_PARAMETER;
506         if( gaACPI_InterruptHandlers[InterruptLevel] != Handler )
507                 return AE_NOT_EXIST;
508         gaACPI_InterruptHandlers[InterruptLevel] = NULL;
509         IRQ_RemHandler(gaACPI_InterruptHandles[InterruptLevel]);
510         return AE_OK;
511 }
512
513 // --- Memory Access ---
514 ACPI_STATUS AcpiOsReadMemory(ACPI_PHYSICAL_ADDRESS Address, UINT64 *Value, UINT32 Width)
515 {
516         void *ptr;
517         if( Address < ONEMEG ) {
518                 ptr = (void*)(KERNEL_BASE | Address);
519         }
520         else {
521                 ptr = (char*)MM_MapTemp(Address) + (Address & 0xFFF);
522         }
523
524         switch(Width)
525         {
526         case 8:         *Value = *(Uint8 *)ptr; break;
527         case 16:        *Value = *(Uint16*)ptr; break;
528         case 32:        *Value = *(Uint32*)ptr; break;
529         case 64:        *Value = *(Uint64*)ptr; break;
530         }
531
532         if( Address >= ONEMEG ) {
533                 MM_FreeTemp(ptr);
534         }
535
536         LOG("*%P = [%i]%X", Address, Width, *Value);
537
538         return AE_OK;
539 }
540
541 ACPI_STATUS AcpiOsWriteMemory(ACPI_PHYSICAL_ADDRESS Address, UINT64 Value, UINT32 Width)
542 {
543         void *ptr;
544         if( Address < ONEMEG ) {
545                 ptr = (void*)(KERNEL_BASE | Address);
546         }
547         else {
548                 ptr = (char*)MM_MapTemp(Address) + (Address & 0xFFF);
549         }
550
551         switch(Width)
552         {
553         case 8:         *(Uint8 *)ptr = Value;  break;
554         case 16:        *(Uint16*)ptr = Value;  break;
555         case 32:        *(Uint32*)ptr = Value;  break;
556         case 64:        *(Uint64*)ptr = Value;  break;
557         default:
558                 return AE_BAD_PARAMETER;
559         }
560
561         if( Address >= ONEMEG ) {
562                 MM_FreeTemp(ptr);
563         }
564         
565         return AE_OK;
566 }
567
568 // --- Port Input / Output ---
569 ACPI_STATUS AcpiOsReadPort(ACPI_IO_ADDRESS Address, UINT32 *Value, UINT32 Width)
570 {
571         switch(Width)
572         {
573         case 8:         *Value = inb(Address);  break;
574         case 16:        *Value = inw(Address);  break;
575         case 32:        *Value = ind(Address);  break;
576         default:
577                 return AE_BAD_PARAMETER;
578         }
579         return AE_OK;
580 }
581
582 ACPI_STATUS AcpiOsWritePort(ACPI_IO_ADDRESS Address, UINT32 Value, UINT32 Width)
583 {
584         switch(Width)
585         {
586         case 8:         outb(Address, Value);   break;
587         case 16:        outw(Address, Value);   break;
588         case 32:        outd(Address, Value);   break;
589         default:
590                 return AE_BAD_PARAMETER;
591         }
592         return AE_OK;
593 }
594
595 // --- PCI Configuration Space Access ---
596 ACPI_STATUS AcpiOsReadPciConfiguration(ACPI_PCI_ID *PciId, UINT32 Register, UINT64 *Value, UINT32 Width)
597 {
598         UNIMPLEMENTED();
599         return AE_NOT_IMPLEMENTED;
600 }
601
602 ACPI_STATUS AcpiOsWritePciConfiguration(ACPI_PCI_ID *PciId, UINT32 Register, UINT64 Value, UINT32 Width)
603 {
604         UNIMPLEMENTED();
605         return AE_NOT_IMPLEMENTED;
606 }
607
608 // --- Formatted Output ---
609 void AcpiOsPrintf(const char *Format, ...)
610 {
611         va_list args;
612         va_start(args, Format);
613
614         LogFV(Format, args);
615
616         va_end(args);
617 }
618
619 void AcpiOsVprintf(const char *Format, va_list Args)
620 {
621         LogFV(Format, Args);
622 }
623
624 void AcpiOsRedirectOutput(void *Destination)
625 {
626         // TODO: Do I even need to impliment this?
627 }
628
629 // --- Miscellaneous ---
630 UINT64 AcpiOsGetTimer(void)
631 {
632         return now() * 10 * 1000;
633 }
634
635 ACPI_STATUS AcpiOsSignal(UINT32 Function, void *Info)
636 {
637         switch(Function)
638         {
639         case ACPI_SIGNAL_FATAL: {
640                 ACPI_SIGNAL_FATAL_INFO  *finfo = Info;
641                 Log_Error("ACPI AML", "Fatal %x %x %x", finfo->Type, finfo->Code, finfo->Argument);
642                 break; }
643         case ACPI_SIGNAL_BREAKPOINT: {
644                 Log_Notice("ACPI AML", "Breakpoint %s", Info);
645                 break; };
646         }
647         return AE_OK;
648 }
649
650 ACPI_STATUS AcpiOsGetLine(char *Buffer, UINT32 BufferLength, UINT32 *BytesRead)
651 {
652         UNIMPLEMENTED();
653         return AE_NOT_IMPLEMENTED;
654 }
655

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