Kernel/VFS - (minor) Logging changes to select
[tpg/acess2.git] / KernelLand / Kernel / vfs / select.c
1 /*
2  * Acess2 VFS
3  * - By thePowersGang (John Hodge)
4  * 
5  * select.c
6  * - Implements the select() system call (and supporting code)
7  *
8  * TODO: Remove malloc for read/write queues
9  */
10 #define DEBUG   0
11 #include <acess.h>
12 #include "vfs.h"
13 #include "vfs_int.h"
14 #include "vfs_ext.h"
15 #include <semaphore.h>
16 #include <threads.h>
17 #include <events.h>
18 #include <timers.h>
19
20 // === CONSTANTS ===
21 #define NUM_THREADS_PER_ALLOC   4
22
23 // === TYPES ===
24 typedef struct sVFS_SelectListEnt       tVFS_SelectListEnt;
25
26 // === STRUCTURES ===
27 struct sVFS_SelectListEnt
28 {
29         tVFS_SelectListEnt      *Next;
30         tThread *Threads[NUM_THREADS_PER_ALLOC];
31 };
32
33 // NOTE: Typedef is in vfs.h
34 struct sVFS_SelectList
35 {
36         tMutex  Lock;
37         tVFS_SelectListEnt      FirstEnt;
38 };
39
40 // === PROTOTYPES ===
41 // int  VFS_SelectNode(tVFS_Node *Node, enum eVFS_SelectTypes Type, tTime *Timeout);
42 // int  VFS_Select(int MaxHandle, fd_set *ReadHandles, fd_set *WriteHandles, fd_set *ErrHandles, tTime *Timeout, Uint32 ExtraEvents, BOOL IsKernel);
43 // int  VFS_MarkFull(tVFS_Node *Node, BOOL IsBufferFull);
44 // int  VFS_MarkAvaliable(tVFS_Node *Node, BOOL IsDataAvaliable);
45 // int  VFS_MarkError(tVFS_Node *Node, BOOL IsErrorState);
46  int    VFS_int_Select_GetType(int Type, tVFS_Node *Node, tVFS_SelectList ***List, int **Flag, int *WantedFlag, int *MaxAllowed);
47  int    VFS_int_Select_Register(tThread *Thread, int MaxHandle, fd_set *Handles, int Type, BOOL IsKernel);
48  int    VFS_int_Select_Deregister(tThread *Thread, int MaxHandle, fd_set *Handles, int Type, BOOL IsKernel);
49  int    VFS_int_Select_AddThread(tVFS_SelectList *List, tThread *Thread, int MaxAllowed);
50 void    VFS_int_Select_RemThread(tVFS_SelectList *List, tThread *Thread);
51 void    VFS_int_Select_SignalAll(tVFS_SelectList *List);
52
53 // === GLOBALS ===
54
55 // === FUNCTIONS ===
56 int VFS_SelectNode(tVFS_Node *Node, int TypeFlags, tTime *Timeout, const char *Name)
57 {
58         tThread *thisthread = Proc_GetCurThread();
59          int    ret, type;
60         
61         ENTER("pNode iTypeFlags pTimeout sName", Node, TypeFlags, Timeout, Name);
62         
63         // Initialise
64         for( type = 0; type < 3; type ++ )
65         {
66                 tVFS_SelectList **list;
67                  int    *flag, wanted, maxAllowed;
68                 if( !(TypeFlags & (1 << type)) )        continue;
69                 if( VFS_int_Select_GetType(type, Node, &list, &flag, &wanted, &maxAllowed) ) {
70                         LEAVE('i', -1);
71                         return -1;
72                 }
73         
74                 // Alloc if needed
75                 if( !*list )    *list = calloc(1, sizeof(tVFS_SelectList));
76         
77                 VFS_int_Select_AddThread(*list, thisthread, maxAllowed);
78                 if( *flag == wanted )
79                 {
80                         VFS_int_Select_RemThread(*list, thisthread);
81                         LEAVE('i', 1);
82                         return 1;
83                 }
84         }
85
86         // Wait for things      
87         if( !Timeout )
88         {
89                 LOG("Semaphore_Wait()");
90                 // TODO: Actual timeout
91                 Threads_WaitEvents( THREAD_EVENT_VFS|THREAD_EVENT_SIGNAL );
92         }
93         else if( *Timeout > 0 )
94         {
95                 tTimer *t = Time_AllocateTimer(NULL, NULL);
96                 // Clear timer event
97                 Threads_ClearEvent( THREAD_EVENT_TIMER );
98                 // TODO: Convert *Timeout?
99                 LOG("Timeout %lli ms", *Timeout);
100                 Time_ScheduleTimer( t, *Timeout );
101                 // Wait for the timer or a VFS event
102                 Threads_WaitEvents( THREAD_EVENT_VFS|THREAD_EVENT_TIMER|THREAD_EVENT_SIGNAL );
103                 Time_FreeTimer(t);
104         }
105         
106         // Get return value
107         ret = 0;
108         for( type = 0; type < 3; type ++ )
109         {
110                 tVFS_SelectList **list;
111                  int    *flag, wanted, maxAllowed;
112                 if( !(TypeFlags & (1 << type)) )        continue;
113                 VFS_int_Select_GetType(type, Node, &list, &flag, &wanted, &maxAllowed);
114                 LOG("VFS_int_Select_RemThread()");
115                 ASSERT(*list);
116                 VFS_int_Select_RemThread(*list, thisthread);
117                 ret = ret || *flag == wanted;
118         }
119
120         Threads_ClearEvent( THREAD_EVENT_VFS );
121         Threads_ClearEvent( THREAD_EVENT_TIMER );
122         
123         LEAVE('i', ret);
124         return ret;
125 }
126
127 int VFS_Select(int MaxHandle, fd_set *ReadHandles, fd_set *WriteHandles, fd_set *ErrHandles, tTime *Timeout, Uint32 ExtraEvents, BOOL IsKernel)
128 {
129         tThread *thisthread = Proc_GetCurThread();
130          int    ret;
131         
132         ENTER("iMaxHandle pReadHandles pWriteHandles pErrHandles pTimeout xExtraEvents bIsKernel",
133                 MaxHandle, ReadHandles, WriteHandles, ErrHandles, Timeout, ExtraEvents, IsKernel);
134         
135         // Notes: The idea is to make sure we only enter wait (Threads_WaitEvents)
136         // if we are going to be woken up (either by an event at a later time,
137         // or by an event that happened while or before we were registering).
138         // Hence, register must happen _before_ we check the state flag
139         // (See VFS_int_Select_Register), that way either we pick up the flag,
140         // or the semaphore is incremeneted (or both, but never none)
141         
142         // Register with nodes
143         if( ReadHandles )
144                 LOG(" - ReadHandles[0] = %x", ReadHandles->flags[0]);
145         ret  = VFS_int_Select_Register(thisthread, MaxHandle, ReadHandles, 0, IsKernel);
146         ret += VFS_int_Select_Register(thisthread, MaxHandle, WriteHandles, 1, IsKernel);
147         ret += VFS_int_Select_Register(thisthread, MaxHandle, ErrHandles, 2, IsKernel);
148         
149         LOG("Register ret = %i", ret);
150         
151         // If there were events waiting, de-register and return
152         if( ret > 0 )
153         {
154                 LOG(" - ReadHandles[0] = %x", ReadHandles->flags[0]);
155                 ret  = VFS_int_Select_Deregister(thisthread, MaxHandle, ReadHandles, 0, IsKernel);
156                 ret += VFS_int_Select_Deregister(thisthread, MaxHandle, WriteHandles, 1, IsKernel);
157                 ret += VFS_int_Select_Deregister(thisthread, MaxHandle, ErrHandles, 2, IsKernel);
158                 LOG(" - ReadHandles[0] = %x", ReadHandles->flags[0]);
159                 LEAVE('i', ret);
160                 return ret;
161         }
162
163         // Wait for things      
164         if( !Timeout )
165         {
166                 LOG("Waiting for VFS/SIGNAL events (Plus 0x%x)", ExtraEvents);
167                 // TODO: Actual timeout
168                 Threads_WaitEvents( THREAD_EVENT_VFS|THREAD_EVENT_SIGNAL|ExtraEvents );
169         }
170         else if( *Timeout > 0 )
171         {
172                 tTimer *t = Time_AllocateTimer(NULL, NULL);
173                 // Clear timer event
174                 Threads_ClearEvent( THREAD_EVENT_TIMER );
175                 // TODO: Convert *Timeout?
176                 LOG("Timeout %lli ms", *Timeout);
177                 Time_ScheduleTimer( t, *Timeout );
178                 // Wait for the timer or a VFS event
179                 Threads_WaitEvents( THREAD_EVENT_VFS|THREAD_EVENT_TIMER|ExtraEvents );
180                 Time_FreeTimer(t);
181         }
182         // Fill output (modify *Handles)
183         LOG("De-registering");
184         // - Also, de-register
185         ret  = VFS_int_Select_Deregister(thisthread, MaxHandle, ReadHandles, 0, IsKernel);
186         ret += VFS_int_Select_Deregister(thisthread, MaxHandle, WriteHandles, 1, IsKernel);
187         ret += VFS_int_Select_Deregister(thisthread, MaxHandle, ErrHandles, 2, IsKernel);
188         
189         Threads_ClearEvent( THREAD_EVENT_VFS );
190         Threads_ClearEvent( THREAD_EVENT_TIMER );
191         
192         LEAVE('i', ret);
193         return ret;
194 }
195
196 // Mark a node as having data ready for reading
197 int VFS_MarkAvaliable(tVFS_Node *Node, BOOL IsDataAvaliable)
198 {
199         ENTER("pNode bIsDataAvaliable", Node, IsDataAvaliable);
200         Node->DataAvaliable = !!IsDataAvaliable;
201         if( Node->DataAvaliable )
202                 VFS_int_Select_SignalAll(Node->ReadThreads);
203         LEAVE('i', 0);
204         return 0;
205 }
206
207 // Mark a node as having a full buffer
208 int VFS_MarkFull(tVFS_Node *Node, BOOL IsBufferFull)
209 {
210         ENTER("pNode bIsBufferFull", Node, IsBufferFull);
211         Node->BufferFull = !!IsBufferFull;
212         if( !Node->BufferFull )
213                 VFS_int_Select_SignalAll(Node->WriteThreads);
214         LEAVE('i', 0);
215         return 0;
216 }
217
218 // Mark a node as errored
219 int VFS_MarkError(tVFS_Node *Node, BOOL IsErrorState)
220 {
221         ENTER("pNode bIsErrorState", Node, IsErrorState);
222         Node->ErrorOccurred = !!IsErrorState;
223         if( Node->ErrorOccurred )
224                 VFS_int_Select_SignalAll(Node->ErrorThreads);
225         LEAVE('i', 0);
226         return 0;
227 }
228
229 // --- Internal ---
230 int VFS_int_Select_GetType(int Type, tVFS_Node *Node, tVFS_SelectList ***List, int **Flag, int *WantedFlag, int *MaxAllowed)
231 {
232         // Get the type of the listen
233         switch(Type)
234         {
235         case 0: // Read
236                 if(List)        *List = &Node->ReadThreads;
237                 if(Flag)        *Flag = &Node->DataAvaliable;
238                 if(WantedFlag)  *WantedFlag = 1;
239                 if(MaxAllowed)  *MaxAllowed = 1;        // Max of 1 for read
240                 break;
241         case 1: // Write
242                 if(List)        *List = &Node->WriteThreads;
243                 if(Flag)        *Flag = &Node->BufferFull;
244                 if(WantedFlag)  *WantedFlag = 0;
245                 if(MaxAllowed)  *MaxAllowed = 1;        // Max of 1 for write
246                 break;
247         case 2: // Error
248                 if(List)        *List = &Node->ErrorThreads;
249                 if(Flag)        *Flag = &Node->ErrorOccurred;
250                 if(WantedFlag)  *WantedFlag = 1;
251                 if(MaxAllowed)  *MaxAllowed = -1;       // No max for error listeners
252                 break;
253         default:
254                 Log_Error("VFS", "VFS_int_Select_GetType: BUG CHECK, Unknown Type %i", Type);
255                 return 1;
256         }
257         return 0;
258 }
259
260 /**
261  * \return Number of files with an action
262  */
263 int VFS_int_Select_Register(tThread *Thread, int MaxHandle, fd_set *Handles, int Type, BOOL IsKernel)
264 {
265          int    i, numFlagged = 0;
266         tVFS_SelectList **list;
267          int    *flag, wantedFlagValue;
268          int    maxAllowed;
269         
270         if( !Handles )  return 0;
271         
272         ENTER("pThread iMaxHandle pHandles iType iIsKernel", Thread, MaxHandle, Handles, Type, IsKernel);
273         
274         for( i = 0; i < MaxHandle; i ++ )
275         {
276                 tVFS_Handle     *handle;
277                 
278                 // Is the descriptor set
279                 if( !FD_ISSET(i, Handles) )     continue;
280                 LOG("FD #%i", i);
281                 
282                 handle = VFS_GetHandle( i | (IsKernel?VFS_KERNEL_FLAG:0) );
283                 // Is the handle valid?
284                 if( !handle || !handle->Node )
285                 {
286                         if( Type == 2 ) {       // Bad FD counts as an error
287                                 numFlagged ++;
288                         }
289                         else {
290                                 FD_CLR(i, Handles);
291                         }
292                         continue;
293                 }
294         
295                 // Get the type of the listen
296                 if( VFS_int_Select_GetType(Type, handle->Node, &list, &flag, &wantedFlagValue, &maxAllowed) ) {
297                         LEAVE('i', 0);
298                         return 0;
299                 }
300                 
301                 // Alloc if needed
302                 if( !*list ) {
303                         *list = calloc(1, sizeof(tVFS_SelectList));
304                 }
305                 
306                 // Register
307                 if( VFS_int_Select_AddThread(*list, Thread, maxAllowed ) )
308                 {
309                         // Oops, error (or just no space)
310                         FD_CLR(i, Handles);
311                 }
312                 
313                 // Check for the flag
314                 if( !!*flag == !!wantedFlagValue ) {
315                         LOG(" %i == want %i", !!*flag, !!wantedFlagValue);
316                         numFlagged ++;
317                 }
318         }
319         
320         LEAVE('i', numFlagged);
321         
322         return numFlagged;
323 }
324 /**
325  * \return Number of files with an action
326  */
327 int VFS_int_Select_Deregister(tThread *Thread, int MaxHandle, fd_set *Handles, int Type, BOOL IsKernel)
328 {
329          int    i, numFlagged = 0;
330         tVFS_SelectList **list;
331          int    *flag, wantedFlagValue;
332         
333         if( !Handles )  return 0;
334         
335         ENTER("pThread iMaxHandle pHandles iType iIsKernel", Thread, MaxHandle, Handles, Type, IsKernel);
336         
337         for( i = 0; i < MaxHandle; i ++ )
338         {
339                 tVFS_Handle     *handle;
340                 
341                 // Is the descriptor set
342                 if( !FD_ISSET(i, Handles) )     continue;
343                 LOG("FD #%i", i);
344                 
345                 handle = VFS_GetHandle( i | (IsKernel?VFS_KERNEL_FLAG:0) );
346                 // Is the handle valid?
347                 if( !handle || !handle->Node )
348                 {
349                         if( Type == 2 ) {       // Bad FD counts as an error
350                                 numFlagged ++;
351                         }
352                         else {
353                                 FD_CLR(i, Handles);
354                         }
355                         continue;
356                 }
357         
358                 // Get the type of the listen
359                 if( VFS_int_Select_GetType(Type, handle->Node, &list, &flag, &wantedFlagValue, NULL) ) {
360                         LEAVE('i', 0);
361                         return 0;
362                 }
363                 
364                 // Remove
365                 VFS_int_Select_RemThread(*list, Thread );
366                 
367                 // Check for the flag
368                 if( !!*flag == !!wantedFlagValue ) {
369                         numFlagged ++;
370                         LOG(" %i == want %i", !!*flag, !!wantedFlagValue);
371                         FD_SET(i, Handles);
372                 }
373                 else {
374                         FD_CLR(i, Handles);
375                 }
376         }
377         
378         LEAVE('i', numFlagged);
379         
380         return numFlagged;
381 }
382
383 /**
384  * \return Boolean failure
385  */
386 int VFS_int_Select_AddThread(tVFS_SelectList *List, tThread *Thread, int MaxAllowed)
387 {
388          int    i, count = 0;
389         tVFS_SelectListEnt      *block, *prev;
390         
391         ENTER("pList pThread iMaxAllowed", List, Thread, MaxAllowed);
392         
393         // Lock to avoid concurrency issues
394         Mutex_Acquire(&List->Lock);
395         
396         block = &List->FirstEnt;
397         
398         // Look for free space
399         do
400         {
401                 for( i = 0; i < NUM_THREADS_PER_ALLOC; i ++ )
402                 {
403                         if( block->Threads[i] == NULL )
404                         {
405                                 block->Threads[i] = Thread;
406                                 Mutex_Release(&List->Lock);
407                                 LEAVE('i', 0);
408                                 return 0;
409                         }
410                         count ++;
411                         if( MaxAllowed && count >= MaxAllowed ) {
412                                 Mutex_Release(&List->Lock);
413                                 LEAVE('i', 1);
414                                 return 1;
415                         }
416                 }
417                 
418                 prev = block;
419                 block = block->Next;
420         } while(block);
421         
422         LOG("New block");
423         
424         // Create new block
425         block = malloc( sizeof(tVFS_SelectListEnt) );
426         if( !block ) {
427                 Log_Warning("VFS", "VFS_int_Select_AddThread: malloc() failed");
428                 Mutex_Release(&List->Lock);
429                 return -1;
430         }
431         block->Next = NULL;
432         block->Threads[0] = Thread;
433         for( i = 1; i < NUM_THREADS_PER_ALLOC; i ++ )
434         {
435                 block->Threads[i] = NULL;
436         }
437         
438         // Add to list
439         prev->Next = block;
440         
441         // Release
442         Mutex_Release(&List->Lock);
443         
444         LEAVE('i', 0);
445         return 0;
446 }
447
448 void VFS_int_Select_RemThread(tVFS_SelectList *List, tThread *Thread)
449 {
450         tVFS_SelectListEnt      *block, *prev = NULL;
451         
452         ENTER("pList pThread", List, Thread);
453         
454         // Lock to avoid concurrency issues
455         Mutex_Acquire(&List->Lock);
456         
457         block = &List->FirstEnt;
458         
459         // Look for the thread
460         do
461         {
462                 for( int i = 0; i < NUM_THREADS_PER_ALLOC; i ++ )
463                 {
464                         if( block->Threads[i] == Thread )
465                         {
466                                 block->Threads[i] = NULL;
467                                 
468                                 // Check if this block is empty
469                                 if( block != &List->FirstEnt )
470                                 {
471                                         for( i = 0; i < NUM_THREADS_PER_ALLOC; i ++ )
472                                                 if( block->Threads[i] )
473                                                         break;
474                                         // If empty, free it
475                                         if( i == NUM_THREADS_PER_ALLOC ) {
476                                                 LOG("Deleting block");
477                                                 prev->Next = block->Next;
478                                                 free(block);
479                                         }
480                                         //TODO: If not empty, check if it can be merged downwards
481                                 }
482                                 
483                                 Mutex_Release(&List->Lock);
484                                 LEAVE('-');
485                                 return ;
486                         }
487                 }
488                 
489                 prev = block;
490                 block = block->Next;
491         } while(block);
492         
493         // Not on list, is this an error?
494         
495         Mutex_Release(&List->Lock);
496         
497         LOG("Not on list");
498         LEAVE('-');
499 }
500
501 /**
502  * \brief Signal all threads on a list
503  */
504 void VFS_int_Select_SignalAll(tVFS_SelectList *List)
505 {
506          int    i;
507         tVFS_SelectListEnt      *block;
508         
509         if( !List )     return ;
510         
511         ENTER("pList", List);
512         
513         // Lock to avoid concurrency issues
514         Mutex_Acquire(&List->Lock);
515         
516         block = &List->FirstEnt;
517         
518         // Look for the thread
519         do
520         {
521                 for( i = 0; i < NUM_THREADS_PER_ALLOC; i ++ )
522                 {
523                         if( block->Threads[i]  )
524                         {
525                                 LOG("block(%p)->Threads[%i] = %p", block, i, block->Threads[i]);
526                                 Threads_PostEvent( block->Threads[i], THREAD_EVENT_VFS );
527                         }
528                 }
529                 
530                 block = block->Next;
531         } while(block);
532         
533         Mutex_Release(&List->Lock);
534         
535         LEAVE('-');
536 }

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