[CMAKE]
[reactos.git] / drivers / usb / usbehci / physmem.c
1 /*
2 * PROJECT: ReactOS Universal Serial Bus Bulk Enhanced Host Controller Interface
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: drivers/usb/usbehci/physmem.c
5 * PURPOSE: Common Buffer routines.
6 * PROGRAMMERS:
7 * Michael Martin (michael.martin@reactos.org)
8 */
9
10 #include "physmem.h"
11 #include "debug.h"
12
13 #define SMALL_ALLOCATION_SIZE 32
14
15 VOID
16 DumpPages()
17 {
18 //PMEM_HEADER MemBlock = (PMEM_HEADER)EhciSharedMemory.VirtualAddr;
19 }
20
21 // Returns Virtual Address of Allocated Memory
22 ULONG
23 AllocateMemory(PEHCI_HOST_CONTROLLER hcd, ULONG Size, ULONG *PhysicalAddress)
24 {
25 PMEM_HEADER MemoryPage = (PMEM_HEADER)hcd->CommonBufferVA;
26 ULONG PageCount = 0;
27 ULONG NumberOfPages = hcd->CommonBufferSize / PAGE_SIZE;
28 ULONG BlocksNeeded;
29 ULONG i,j, freeCount;
30 ULONG RetAddr = 0;
31
32 Size = ((Size + SMALL_ALLOCATION_SIZE - 1) / SMALL_ALLOCATION_SIZE) * SMALL_ALLOCATION_SIZE;
33 BlocksNeeded = Size / SMALL_ALLOCATION_SIZE;
34
35 do
36 {
37 if (MemoryPage->IsFull)
38 {
39 PageCount++;
40 MemoryPage = (PMEM_HEADER)((ULONG)MemoryPage + PAGE_SIZE);
41 continue;
42 }
43 freeCount = 0;
44 for (i = 0; i < sizeof(MemoryPage->Entry); i++)
45 {
46 if (!MemoryPage->Entry[i].InUse)
47 {
48 freeCount++;
49 }
50 else
51 {
52 freeCount = 0;
53 }
54
55 if (freeCount == BlocksNeeded)
56 {
57 for (j = 0; j < freeCount; j++)
58 {
59 MemoryPage->Entry[i-j].InUse = 1;
60 MemoryPage->Entry[i-j].Blocks = 0;
61 }
62
63 MemoryPage->Entry[i-freeCount + 1].Blocks = BlocksNeeded;
64
65 RetAddr = (ULONG)MemoryPage + (SMALL_ALLOCATION_SIZE * (i - freeCount + 1)) + sizeof(MEM_HEADER);
66
67 *PhysicalAddress = (ULONG)hcd->CommonBufferPA.LowPart + (RetAddr - (ULONG)hcd->CommonBufferVA);
68 return RetAddr;
69 }
70 }
71
72 PageCount++;
73 MemoryPage = (PMEM_HEADER)((ULONG)MemoryPage + PAGE_SIZE);
74 } while (PageCount < NumberOfPages);
75
76 return 0;
77 }
78
79 VOID
80 ReleaseMemory(ULONG Address)
81 {
82 PMEM_HEADER MemoryPage;
83 ULONG Index, i;
84
85 MemoryPage = (PMEM_HEADER)(Address & ~(PAGE_SIZE - 1));
86
87 Index = (Address - ((ULONG)MemoryPage + sizeof(MEM_HEADER))) / SMALL_ALLOCATION_SIZE;
88
89 for (i = 0; i < MemoryPage->Entry[Index].Blocks; i++)
90 {
91 MemoryPage->Entry[Index + i].InUse = 0;
92 MemoryPage->Entry[Index + i].Blocks = 0;
93 }
94 }