Debian Codegraph @

gobi-api/Gobi_2012-06-18-1054/Core/ProtocolServer.cpp

raw
1 /*===========================================================================
2 FILE:
3 ProtocolServer.cpp
4
5 DESCRIPTION:
6 Generic protocol packet server
7
8 PUBLIC CLASSES AND METHODS:
9 cProtocolServer
10 Abstract base class for protocol servers
11
12 Copyright (c) 2012, Code Aurora Forum. All rights reserved.
13
14 Redistribution and use in source and binary forms, with or without
15 modification, are permitted provided that the following conditions are met:
16 * Redistributions of source code must retain the above copyright
17 notice, this list of conditions and the following disclaimer.
18 * Redistributions in binary form must reproduce the above copyright
19 notice, this list of conditions and the following disclaimer in the
20 documentation and/or other materials provided with the distribution.
21 * Neither the name of Code Aurora Forum nor
22 the names of its contributors may be used to endorse or promote
23 products derived from this software without specific prior written
24 permission.
25
26
27 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
28 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
31 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 POSSIBILITY OF SUCH DAMAGE.
38 ===========================================================================*/
39
40 //---------------------------------------------------------------------------
41 // Include Files
42 //---------------------------------------------------------------------------
43 #include "StdAfx.h"
44
45 #include "ProtocolServer.h"
46 #include "ProtocolNotification.h"
47
48 #include <climits>
49
50 //---------------------------------------------------------------------------
51 // Definitions
52 //---------------------------------------------------------------------------
53
54 // Invalid request ID
55 const ULONG INVALID_REQUEST_ID = 0;
56
57 // Default activity timeout value
58 const ULONG DEFAULT_WAIT = 100;
59
60 // MTU (Maximum Transmission Unit) for auxiliary data (QC USB imposed)
61 const ULONG MAX_AUX_MTU_SIZE = 1024 * 256;
62
63 // USB's MaxPacketSize
64 const ULONG MAX_PACKET_SIZE = 512;
65
66 // Maximum amount of time to wait on external access synchronization object
67 #ifdef DEBUG
68 // For the sake of debugging do not be so quick to assume failure
69 const ULONG DEADLOCK_TIME = 180000;
70 #else
71 const ULONG DEADLOCK_TIME = 10000;
72 #endif
73
74 // Maximum amount of time to wait for the protocol server to process a command
75 const ULONG COMMAND_TIME = DEADLOCK_TIME;
76
77 /*=========================================================================*/
78 // Free Methods
79 /*=========================================================================*/
80
81 /*===========================================================================
82 METHOD:
83 ScheduleThread (Free Method)
84
85 DESCRIPTION:
86 Watch schedule for event to process or timeout
87
88 PARAMETERS:
89 pArg [ I ] - The protocol server object
90
91 RETURN VALUE:
92 void * - thread exit value (always NULL)
93 ===========================================================================*/
94 void * ScheduleThread( PVOID pArg )
95 {
96 // Do we have a server?
97 cProtocolServer * pServer = (cProtocolServer *)pArg;
98 if (pServer == 0)
99 {
100 TRACE( "ScheduleThread started with empty pArg."
101 " Unable to locate cProtocolServer\n" );
102
103 ASSERT( 0 );
104 return NULL;
105 }
106
107 TRACE( "Schedule thread [%lu] started\n",
108 pthread_self() );
109
110 // Default wait event
111 timespec toTime = TimeIn( DEFAULT_WAIT );
112
113 // Return value checking
114 int nRet;
115
116 while (pServer->mbExiting == false)
117 {
118 DWORD nTemp;
119 nRet = pServer->mThreadScheduleEvent.Wait( TimeFromNow( toTime ), nTemp );
120 if (nRet != 0 && nRet != ETIME)
121 {
122 // Error condition
123 TRACE( "ScheduleThread [%lu] ScheduleThread wait error %d, %s\n",
124 pthread_self(),
125 nRet,
126 strerror( nRet ) );
127 break;
128 }
129
130 // Time to exit?
131 if (pServer->mbExiting == true)
132 {
133 break;
134 }
135
136 // Get Schedule Mutex (non-blocking)
137 nRet = pthread_mutex_trylock( &pServer->mScheduleMutex );
138 if (nRet == EBUSY)
139 {
140 // Not an error, we're just too slow
141 // Someone else got to the ScheduleMutex before us
142 // We'll wait for the signal again
143 toTime = TimeIn( DEFAULT_WAIT );
144 TRACE( "ScheduleThread [%lu] unable to lock ScheduleMutex\n",
145 pthread_self() );
146 continue;
147 }
148 else if (nRet != 0)
149 {
150 // Error condition
151 TRACE( "ScheduleThread [%lu] mScheduleMutex error %d, %s\n",
152 pthread_self(),
153 nRet,
154 strerror( nRet ) );
155 break;
156 }
157
158 // Verify time. In the rare event it does move backward
159 // it would simply place all our schedule items as due now
160 pServer->CheckSystemTime();
161
162 // Default next wait period
163 toTime = TimeIn( DEFAULT_WAIT );
164
165 timespec curTime = TimeIn( 0 );
166
167 if (pServer->mpActiveRequest != 0)
168 {
169 if (pServer->mpActiveRequest->mbWaitingForResponse == true)
170 {
171 // Waiting on a response, this takes priority over the next
172 // scheduled event
173
174 // Has timeout expired?
175 if (pServer->mActiveRequestTimeout <= curTime)
176 {
177 // Response timeout
178
179 // Note: This may clear mpActiveRequest
180 pServer->RxTimeout();
181 }
182 else
183 {
184 // Active response timer is not yet due to expire
185 // Default timeout again, or this response's timeout?
186 if (pServer->mActiveRequestTimeout <= toTime)
187 {
188 toTime = pServer->mActiveRequestTimeout;
189 }
190 }
191 }
192 else
193 {
194 // This should never happen
195
196 TRACE( "ScheduleThread() Sequencing error: "
197 "Active request %lu is not waiting for response ???\n",
198 pServer->mpActiveRequest->mID );
199
200 break;
201 }
202 }
203
204 if (pServer->mpActiveRequest == 0
205 && pServer->mRequestSchedule.size() > 0)
206 {
207 // No response timer active, ready to start the next
208 // scheduled item if due
209
210 timespec scheduledItem = pServer->GetNextRequestTime();
211
212 // Is item due to be scheduled?
213 if (scheduledItem <= curTime)
214 {
215 // Process scheduled item
216 pServer->ProcessRequest();
217 }
218 else
219 {
220 // Scheduled item is not yet due to be processed
221 // Default timeout again, or this item's start time?
222 if (scheduledItem <= toTime)
223 {
224 toTime = scheduledItem;
225 }
226 }
227 }
228
229 /*TRACE( "Updated timer at %llu waiting %lu\n",
230 GetTickCount(),
231 TimeFromNow( toTime ) ); */
232
233 // Unlock schedule mutex
234 nRet = pthread_mutex_unlock( &pServer->mScheduleMutex );
235 if (nRet != 0)
236 {
237 TRACE( "ScheduleThread Unable to unlock schedule mutex."
238 " Error %d: %s\n",
239 nRet,
240 strerror( nRet ) );
241 return false;
242 }
243 }
244
245 TRACE( "Schedule thread [%lu] exited\n",
246 pthread_self() );
247
248 return NULL;
249 }
250
251 /*===========================================================================
252 METHOD:
253 TimeIn (Free Method)
254
255 DESCRIPTION:
256 Fill timespec with the time it will be in specified milliseconds
257 Relative time to Absolute time
258
259 PARAMETERS:
260 millis [ I ] - Milliseconds from current time
261
262 RETURN VALUE:
263 timespec - resulting time (from epoc)
264 NOTE: tv_sec of 0 is an error
265 ===========================================================================*/
266 timespec TimeIn( ULONG millis )
267 {
268 timespec outTime;
269
270 int nRC = clock_gettime( CLOCK_REALTIME, &outTime );
271 if (nRC == 0)
272 {
273 // Add avoiding an overflow on (long)nsec
274 outTime.tv_sec += millis / 1000l;
275 outTime.tv_nsec += ( millis % 1000l ) * 1000000l;
276
277 // Check if we need to carry
278 if (outTime.tv_nsec >= 1000000000l)
279 {
280 outTime.tv_sec += outTime.tv_nsec / 1000000000l;
281 outTime.tv_nsec = outTime.tv_nsec % 1000000000l;
282 }
283 }
284 else
285 {
286 outTime.tv_sec = 0;
287 outTime.tv_nsec = 0;
288 }
289
290 return outTime;
291 }
292
293 /*===========================================================================
294 METHOD:
295 TimeFromNow (Free Method)
296
297 DESCRIPTION:
298 Find the milliseconds from current time this timespec will occur
299 Absolute time to Relative time
300
301 PARAMETERS:
302 time [ I ] - Absolute time
303
304 RETURN VALUE:
305 Milliseconds in which absolute time will occur
306 0 if time has passed or error has occured
307 ===========================================================================*/
308 ULONG TimeFromNow( timespec time )
309 {
310 // Assume failure
311 ULONG nOutTime = 0;
312
313 timespec now;
314 int nRC = clock_gettime( CLOCK_REALTIME, &now );
315 if (nRC == -1)
316 {
317 TRACE( "Error %d with gettime, %s\n", errno, strerror( errno ) );
318 return nOutTime;
319 }
320
321 if (time <= now)
322 {
323 return nOutTime;
324 }
325
326 nOutTime = (time.tv_sec - now.tv_sec) * 1000l;
327 nOutTime += (time.tv_nsec - now.tv_nsec) / 1000000l;
328
329 return nOutTime;
330 }
331
332 /*===========================================================================
333 METHOD:
334 GetTickCount (Free Method)
335
336 DESCRIPTION:
337 Provide a number for sequencing reference, similar to the windows
338 ::GetTickCount().
339
340 NOTE: This number is based on the time since epoc, not
341 uptime.
342
343 PARAMETERS:
344
345 RETURN VALUE:
346 ULONGLONG - Number of milliseconds system has been up
347 ===========================================================================*/
348 ULONGLONG GetTickCount()
349 {
350 timespec curtime = TimeIn( 0 );
351
352 ULONGLONG outtime = curtime.tv_sec * 1000LL;
353 outtime += curtime.tv_nsec / 1000000LL;
354
355 return outtime;
356 }
357
358 /*=========================================================================*/
359 // cProtocolServerRxCallback Methods
360 /*=========================================================================*/
361
362 /*===========================================================================
363 METHOD:
364 IOComplete (Free Method)
365
366 DESCRIPTION:
367 The I/O has been completed, process the results
368
369 PARAMETERS:
370 status [ I ] - Status of operation
371 bytesReceived [ I ] - Bytes received during operation
372
373 RETURN VALUE:
374 None
375 ===========================================================================*/
376 void cProtocolServerRxCallback::IOComplete(
377 DWORD status,
378 DWORD bytesReceived )
379 {
380 if (mpServer != 0)
381 {
382 mpServer->RxComplete( status, bytesReceived );
383 }
384 }
385
386 /*=========================================================================*/
387 // cProtocolServer::sProtocolReqRsp Methods
388 /*=========================================================================*/
389
390 /*===========================================================================
391 METHOD:
392 cProtocolServer::sProtocolReqRsp (Public Method)
393
394 DESCRIPTION:
395 Constructor
396
397 PARAMETERS:
398 requestInfo [ I ] - Underlying request object
399 requestID [ I ] - Request ID
400 auxDataMTU [ I ] - MTU (Maximum Transmission Unit) for auxiliary data
401
402 RETURN VALUE:
403 None
404 ===========================================================================*/
405 cProtocolServer::sProtocolReqRsp::sProtocolReqRsp(
406 const sProtocolRequest & requestInfo,
407 ULONG requestID,
408 ULONG auxDataMTU )
409 : mRequest( requestInfo ),
410 mID( requestID ),
411 mAttempts( 0 ),
412 mEncodedSize( requestInfo.GetSize() ),
413 mRequiredAuxTxs( 0 ),
414 mCurrentAuxTx( 0 ),
415 mbWaitingForResponse( false )
416 {
417 ULONG auxDataSz = 0;
418 const BYTE * pAuxData = requestInfo.GetAuxiliaryData( auxDataSz );
419
420 // Compute the number of required auxiliary data transmissions?
421 if (auxDataMTU > 0 && pAuxData != 0 && auxDataSz > 0)
422 {
423 mRequiredAuxTxs = 1;
424 if (auxDataSz > auxDataMTU)
425 {
426 mRequiredAuxTxs = auxDataSz / auxDataMTU;
427 if ((auxDataSz % auxDataMTU) != 0)
428 {
429 mRequiredAuxTxs++;
430 }
431 }
432 }
433 }
434
435 /*===========================================================================
436 METHOD:
437 cProtocolServer::sProtocolReqRsp (Public Method)
438
439 DESCRIPTION:
440 Copy constructor
441
442 PARAMETERS:
443 reqRsp [ I ] - Object being copied
444
445 RETURN VALUE:
446 None
447 ===========================================================================*/
448 cProtocolServer::sProtocolReqRsp::sProtocolReqRsp(
449 const sProtocolReqRsp & reqRsp )
450 : mRequest( reqRsp.mRequest ),
451 mID( reqRsp.mID ),
452 mAttempts( reqRsp.mAttempts ),
453 mEncodedSize( reqRsp.mEncodedSize ),
454 mRequiredAuxTxs( reqRsp.mRequiredAuxTxs ),
455 mCurrentAuxTx( reqRsp.mCurrentAuxTx ),
456 mbWaitingForResponse( reqRsp.mbWaitingForResponse )
457 {
458 // Nothing to do
459 };
460
461 /*=========================================================================*/
462 // cProtocolServer Methods
463 /*=========================================================================*/
464
465 /*===========================================================================
466 METHOD:
467 cProtocolServer (Public Method)
468
469 DESCRIPTION:
470 Constructor
471
472 PARAMETERS:
473 rxType [ I ] - Protocol type to assign to incoming data
474 txType [ I ] - Protocol type to verify for outgoing data
475 bufferSzRx [ I ] - Size of data buffer for incoming data
476 logSz [ I ] - Size of log (number of buffers)
477
478 SEQUENCING:
479 None (constructs sequencing objects)
480
481 RETURN VALUE:
482 None
483 ===========================================================================*/
484 cProtocolServer::cProtocolServer(
485 eProtocolType rxType,
486 eProtocolType txType,
487 ULONG bufferSzRx,
488 ULONG logSz )
489 : mpConnection( 0 ),
490 mConnectionType( eConnectionType_Begin ),
491 mRxCallback(),
492 mScheduleThreadID( 0 ),
493 mThreadScheduleEvent(),
494 mbExiting( false ),
495 mpServerControl( 0 ),
496 mLastRequestID( 1 ),
497 mpActiveRequest( 0 ),
498 mpRxBuffer( 0 ),
499 mRxBufferSize( bufferSzRx ),
500 mRxType( rxType ),
501 mTxType( txType ),
502 mLog( logSz )
503 {
504 mLastTime = TimeIn( 0 );
505
506 // Allocate receive buffer?
507 if (mRxBufferSize > 0)
508 {
509 mpRxBuffer = new BYTE[mRxBufferSize];
510 }
511
512 // Before continuing verify receive buffer was allocated
513 if (mpRxBuffer != 0)
514 {
515 // Schedule mutex
516 int nRet = pthread_mutex_init( &mScheduleMutex, NULL );
517 if (nRet != 0)
518 {
519 TRACE( "Unable to init schedule mutex. Error %d: %s\n",
520 nRet,
521 strerror( nRet ) );
522 return;
523 }
524 }
525 }
526
527 /*===========================================================================
528 METHOD:
529 ~cProtocolServer (Public Method)
530
531 DESCRIPTION:
532 Destructor
533
534 SEQUENCING:
535 None (destroys sequencing objects)
536
537 RETURN VALUE:
538 None
539 ===========================================================================*/
540 cProtocolServer::~cProtocolServer()
541 {
542 // This should have already been called, but ...
543 Exit();
544
545 // Schedule mutex
546 int nRet = pthread_mutex_destroy( &mScheduleMutex );
547 if (nRet != 0)
548 {
549 TRACE( "Unable to destroy schedule mutex. Error %d: %s\n",
550 nRet,
551 strerror( nRet ) );
552 }
553
554 // Free receive buffer
555 if (mpRxBuffer != 0)
556 {
557 delete [] mpRxBuffer;
558 mpRxBuffer = 0;
559 }
560 }
561
562 /*===========================================================================
563 METHOD:
564 HandleRemoveRequest (Public Method)
565
566 DESCRIPTION:
567 Remove a previously added protocol request
568
569 Note: if a request is being processed, it cannot be inturrupted
570
571 PARAMETERS:
572 reqID [ I ] - Server assigned request ID
573
574 SEQUENCING:
575 Calling process must have lock on mScheduleMutex
576
577 RETURN VALUE:
578 bool
579 ===========================================================================*/
580 bool cProtocolServer::HandleRemoveRequest( ULONG reqID )
581 {
582 // Assume failure
583 bool bRC = false;
584
585 // Find and erase request from request map
586 std::map <ULONG, sProtocolReqRsp *>::iterator pReqIter;
587 pReqIter = mRequestMap.find( reqID );
588
589 if (pReqIter != mRequestMap.end())
590 {
591 sProtocolReqRsp * pReqRsp = pReqIter->second;
592 if (pReqRsp != 0)
593 {
594 delete pReqRsp;
595 }
596
597 mRequestMap.erase( pReqIter );
598
599 // Success!
600 bRC = true;
601
602 // Find and erase request from schedule
603 bool bFound = false;
604 int entryIndex = -1;
605
606 std::set <tSchedule>::iterator pScheduleIter;
607 pScheduleIter = mRequestSchedule.begin();
608
609 while (pScheduleIter != mRequestSchedule.end())
610 {
611 entryIndex++;
612
613 tSchedule entry = *pScheduleIter;
614 if (entry.second == reqID)
615 {
616 bFound = true;
617 mRequestSchedule.erase( pScheduleIter );
618 break;
619 }
620 else
621 {
622 pScheduleIter++;
623 }
624 }
625
626 // Note: schedule will be updated when mutex is unlocked/signaled
627 }
628 else if (mpActiveRequest != 0 && mpActiveRequest->mID == reqID)
629 {
630 const sProtocolRequest & req = mpActiveRequest->mRequest;
631 const cProtocolNotification * pNotifier = req.GetNotifier();
632
633 // Cancel the response timer (when active)
634 if (mpActiveRequest->mbWaitingForResponse == true)
635 {
636 // Schedule will be updated when mutex is unlocked
637
638 // Failure to receive response, notify client
639 if (pNotifier != 0)
640 {
641 pNotifier->Notify( ePROTOCOL_EVT_RSP_ERR,
642 (DWORD)reqID,
643 ECANCELED );
644 }
645 }
646 else
647 {
648 // This is the active request, cancel the underlying transmit
649 // Note: Because ProcessRequest and RemoveRequest are both muxed
650 // with ScheduleMutex, it is impossible to for the write
651 // to actually be in progress when this code is reached.
652 if (mpConnection != 0)
653 {
654 mpConnection->CancelTx();
655 }
656
657 // Failure to send request, notify client
658 if (pNotifier != 0)
659 {
660 pNotifier->Notify( ePROTOCOL_EVT_REQ_ERR,
661 (DWORD)reqID,
662 ECANCELED );
663 }
664 }
665
666 // Now delete the request
667 delete mpActiveRequest;
668 mpActiveRequest = 0;
669
670 // Success!
671 bRC = true;
672 }
673 else
674 {
675 TRACE( "cProtocolServer::RemoveRequest( %lu ),"
676 " invalid request ID\n",
677 reqID );
678 }
679
680 return bRC;
681 }
682
683 /*===========================================================================
684 METHOD:
685 ScheduleRequest (Internal Method)
686
687 DESCRIPTION:
688 Schedule a request for transmission
689
690 PARAMETERS:
691 reqID [ I ] - ID of the request being scheduled this ID must exist
692 in the internal request/schedule maps
693
694 schedule [ I ] - Value in milliseconds that indicates the approximate
695 time from now that the request is to be sent out, the
696 actual time that the request is sent will be greater
697 than or equal to this value dependant on requests
698 scheduled before the request in question and
699 standard server processing time
700
701 SEQUENCING:
702 Calling process must have lock on mScheduleMutex
703
704 RETURN VALUE:
705 bool
706 ===========================================================================*/
707 bool cProtocolServer::ScheduleRequest(
708 ULONG reqID,
709 ULONG schedule )
710 {
711 // Assume failure
712 bool bRC = false;
713
714 // Schedule adjust is in milliseconds
715 timespec schTimer = TimeIn( schedule );
716
717 // Create the schedule entry
718 tSchedule newEntry( schTimer, reqID );
719
720 // Fit this request into the schedule (ordered by scheduled time)
721 mRequestSchedule.insert( newEntry );
722
723 // Note: timer will be updated when mScheduleMutex is unlocked
724
725 return bRC;
726 }
727
728 /*===========================================================================
729 METHOD:
730 RescheduleActiveRequest (Internal Method)
731
732 DESCRIPTION:
733 Reschedule (or cleanup) the active request
734
735 SEQUENCING:
736 Calling process must have lock on mScheduleMutex
737
738 RETURN VALUE:
739 None
740 ===========================================================================*/
741 void cProtocolServer::RescheduleActiveRequest()
742 {
743 // Are there more attempts to be made?
744 if (mpActiveRequest->mAttempts < mpActiveRequest->mRequest.GetRequests())
745 {
746 // Yes, first reset the request
747 mpActiveRequest->Reset();
748
749 // Now add it back to the request map
750 mRequestMap[mpActiveRequest->mID] = mpActiveRequest;
751
752 TRACE( "RescheduleActiveRequest(): req %lu rescheduled\n", mpActiveRequest->mID );
753
754 // Lastly reschedule the request
755 ScheduleRequest( mpActiveRequest->mID,
756 mpActiveRequest->mRequest.GetFrequency() );
757
758 }
759 else
760 {
761 TRACE( "RescheduleActiveRequest(): req %lu removed\n", mpActiveRequest->mID );
762
763 // No, we are through with this request
764 delete mpActiveRequest;
765 }
766
767 // There is no longer an active request
768 mpActiveRequest = 0;
769
770 }
771
772 /*===========================================================================
773 METHOD:
774 ProcessRequest (Internal Method)
775
776 DESCRIPTION:
777 Process a single outgoing protocol request, this consists of removing
778 the request ID from the head of the schedule, looking up the internal
779 request object in the request map, sending out the request, and setting
780 up the response timer (if a response is required)
781
782 SEQUENCING:
783 Calling process must have lock on mScheduleMutex
784
785 RETURN VALUE:
786 ===========================================================================*/
787 void cProtocolServer::ProcessRequest()
788 {
789 // Is there already an active request?
790 if (mpActiveRequest != 0 || mpConnection == 0)
791 {
792 return;
793 }
794
795 // Grab request ID from the schedule
796 std::set <tSchedule>::iterator pScheduleIter;
797 pScheduleIter = mRequestSchedule.begin();
798
799 // Did we find the request?
800 if (pScheduleIter == mRequestSchedule.end())
801 {
802 // No
803 return;
804 }
805
806 // Yes, grab the request ID
807 ULONG reqID = pScheduleIter->second;
808
809 // Remove from schedule
810 mRequestSchedule.erase( pScheduleIter );
811
812 // Look up the internal request object
813 std::map <ULONG, sProtocolReqRsp *>::iterator pReqIter;
814 pReqIter = mRequestMap.find( reqID );
815
816 // Request not found around?
817 if (pReqIter == mRequestMap.end() || pReqIter->second == 0)
818 {
819 // No
820 return;
821 }
822
823 // Set this request as the active request
824 mpActiveRequest = pReqIter->second;
825
826 TRACE( "ProcessRequest(): req %lu started\n", mpActiveRequest->mID );
827
828 // Remove request from pending request map
829 mRequestMap.erase( pReqIter );
830
831 // Extract the underlying request
832 const sProtocolRequest & req = mpActiveRequest->mRequest;
833
834 // Increment attempt count?
835 if (req.GetRequests() != INFINITE_REQS)
836 {
837 // This request isn't an indefinite one, so keep track of each attempt
838 mpActiveRequest->mAttempts++;
839 }
840
841 bool bTxSuccess = false;
842
843 // Encode data for transmission?
844 bool bEncoded = false;
845 sSharedBuffer * pEncoded = 0;
846 pEncoded = EncodeTxData( req.GetSharedBuffer(), bEncoded );
847 if (bEncoded == false)
848 {
849 // Note: no longer asynchronus
850 // Send the request data
851 bTxSuccess = mpConnection->TxData( req.GetBuffer(),
852 req.GetSize() );
853 }
854 else if (bEncoded == true)
855 {
856 if (pEncoded != 0 && pEncoded->IsValid() == true)
857 {
858 // Note: no longer asynchronus
859 // Send the request data
860 mpActiveRequest->mEncodedSize = pEncoded->GetSize();
861 bTxSuccess = mpConnection->TxData( pEncoded->GetBuffer(),
862 pEncoded->GetSize() );
863 }
864 }
865
866 if (bTxSuccess == true)
867 {
868 TRACE( "ProcessRequest(): req %lu finished\n", mpActiveRequest->mID );
869 TxComplete();
870 }
871 else
872 {
873 TxError();
874 TRACE( "ProcessRequest(): req finished with a TxError\n" );
875 }
876
877 return;
878 }
879
880 /*===========================================================================
881 METHOD:
882 CheckSystemTime (Internal Method)
883
884 DESCRIPTION:
885 Check that system time hasn't moved backwards. Since we use the system
886 time for scheduling requests we need to periodically check that the
887 user (or system itself) hasn't reset system time backwards, if it has
888 then we reschedule everything to the current system time. This disrupts
889 the schedule but avoids stranding requests
890
891 Updates mLastTime
892
893 SEQUENCING:
894 Calling process must have lock on mScheduleMutex
895
896 RETURN VALUE:
897 bool: System time moved backwards?
898 ===========================================================================*/
899 bool cProtocolServer::CheckSystemTime()
900 {
901 // Assume that time is still marching forward
902 bool bAdjust = false;
903
904 timespec curTime = TimeIn( 0 );
905
906 if (curTime < mLastTime)
907 {
908 // Looks like the system clock has been adjusted to an earlier
909 // value, go through the current schedule and adjust each timer
910 // to reflect the adjustment. This isn't an exact approach but
911 // it prevents requests from being stranded which is our goal
912
913 // Note: set iterators are constant. This means we need to
914 // create a set with the new data, we can't modify this one
915
916 std::set < tSchedule, std::less <tSchedule> > tempSchedule;
917
918 std::set <tSchedule>::iterator pScheduleIter;
919 pScheduleIter = mRequestSchedule.begin();
920
921 while (pScheduleIter != mRequestSchedule.end())
922 {
923 tSchedule entry = *pScheduleIter;
924 entry.first.tv_sec = curTime.tv_sec;
925 entry.first.tv_nsec = curTime.tv_nsec;
926 tempSchedule.insert( entry );
927
928 pScheduleIter++;
929 }
930
931 mRequestSchedule = tempSchedule;
932
933 // Update mActiveRequestTimeout
934 if ( (mpActiveRequest != 0)
935 && (mpActiveRequest->mbWaitingForResponse == true) )
936 {
937 // Restart active request's timeout
938 ULONG mTimeout = mpActiveRequest->mRequest.GetTimeout();
939 mActiveRequestTimeout = TimeIn( mTimeout );
940 }
941
942 TRACE( "Time has moved backwards, schedule updated\n" );
943
944 // Indicate the change
945 bAdjust = true;
946 }
947
948 mLastTime.tv_sec = curTime.tv_sec;
949 mLastTime.tv_nsec = curTime.tv_nsec;
950
951 return bAdjust;
952 }
953
954 /*===========================================================================
955 METHOD:
956 RxComplete (Internal Method)
957
958 DESCRIPTION:
959 Handle completion of receive data operation
960
961 PARAMETERS:
962 status [ I ] - Status of operation
963 bytesReceived [ I ] - Number of bytes received
964
965 SEQUENCING:
966 This method is sequenced according to the schedule mutex
967 i.e. any other thread that needs to modify the schedule
968 will block until this method completes
969
970 RETURN VALUE:
971 None
972 ===========================================================================*/
973 void cProtocolServer::RxComplete(
974 DWORD status,
975 DWORD bytesReceived )
976 {
977 if (status != NO_ERROR)
978 {
979 TRACE( "cProtocolServer::RxComplete() = %lu\n", status );
980 }
981
982 if (mpConnection == 0)
983 {
984 TRACE( "cProtocolServer::RxComplete() - Not initialized\n" );
985 return;
986 }
987
988 // Error with the read
989 if (status != NO_ERROR || bytesReceived == 0)
990 {
991 // Setup the next read
992 mpConnection->RxData( mpRxBuffer,
993 (ULONG)mRxBufferSize,
994 (cIOCallback *)&mRxCallback );
995
996 return;
997 }
998
999 // Get Schedule Mutex
1000 if (GetScheduleMutex() == false)
1001 {
1002 TRACE( "RxComplete(), unable to get schedule Mutex\n" );
1003 return;
1004 }
1005
1006 TRACE( "RxComplete() - Entry at %llu\n", GetTickCount() );
1007
1008 // Decode data
1009 bool bAbortTx = false;
1010 ULONG rspIdx = INVALID_LOG_INDEX;
1011 bool bRsp = DecodeRxData( bytesReceived, rspIdx, bAbortTx );
1012
1013 // Is there an active request that needs to be aborted
1014 if (mpActiveRequest != 0 && bAbortTx == true)
1015 {
1016 // Yes, terminate the transmission and handle the error
1017 mpConnection->CancelTx();
1018 TxError();
1019 }
1020 // Is there an active request and a valid response?
1021 else if (mpActiveRequest != 0 && bRsp == true)
1022 {
1023 const sProtocolRequest & req = mpActiveRequest->mRequest;
1024 const cProtocolNotification * pNotifier = req.GetNotifier();
1025
1026 // Notify client that response was received
1027 if (pNotifier != 0)
1028 {
1029 pNotifier->Notify( ePROTOCOL_EVT_RSP_RECV,
1030 (DWORD)mpActiveRequest->mID,
1031 (DWORD)rspIdx );
1032 }
1033
1034 // Reschedule request as needed
1035 RescheduleActiveRequest();
1036 }
1037
1038 // Setup the next read
1039 mpConnection->RxData( mpRxBuffer,
1040 (ULONG)mRxBufferSize,
1041 (cIOCallback *)&mRxCallback );
1042
1043 TRACE( "RxComplete() - Exit at %llu\n", GetTickCount() );
1044
1045 // Unlock schedule mutex
1046 if (ReleaseScheduleMutex() == false)
1047 {
1048 // This should never happen
1049 return;
1050 }
1051
1052 return;
1053 }
1054
1055 /*===========================================================================
1056 METHOD:
1057 RxTimeout (Internal Method)
1058
1059 DESCRIPTION:
1060 Handle the response timer expiring
1061
1062 SEQUENCING:
1063 Calling process must have lock on mScheduleMutex
1064
1065 RETURN VALUE:
1066 None
1067 ===========================================================================*/
1068 void cProtocolServer::RxTimeout()
1069 {
1070 // No active request?
1071 if (mpActiveRequest == 0)
1072 {
1073 TRACE( "RxTimeout() with no active request\n" );
1074 ASSERT( 0 );
1075 }
1076
1077 TRACE( "RxTimeout() for req %lu\n", mpActiveRequest->mID );
1078
1079 const sProtocolRequest & req = mpActiveRequest->mRequest;
1080 const cProtocolNotification * pNotifier = req.GetNotifier();
1081
1082 // Failure to receive response, notify client
1083 if (pNotifier != 0)
1084 {
1085 pNotifier->Notify( ePROTOCOL_EVT_RSP_ERR,
1086 (DWORD)mpActiveRequest->mID,
1087 (DWORD)0 );
1088 }
1089
1090 // Reschedule request as needed
1091 RescheduleActiveRequest();
1092 }
1093
1094 /*===========================================================================
1095 METHOD:
1096 TxComplete (Internal Method)
1097
1098 DESCRIPTION:
1099 Handle completion of transmit data operation
1100
1101 PARAMETERS:
1102
1103 SEQUENCING:
1104 Calling process must have lock on mScheduleMutex
1105
1106 RETURN VALUE:
1107 None
1108 ===========================================================================*/
1109 void cProtocolServer::TxComplete()
1110 {
1111 // No active request?
1112 if (mpActiveRequest == 0 || mpConnection == 0)
1113 {
1114 TRACE( "TxComplete() called with no active request\n" );
1115 ASSERT( 0 );
1116 }
1117
1118 TRACE( "TxComplete() req %lu started\n", mpActiveRequest->mID );
1119
1120 ULONG reqID = mpActiveRequest->mID;
1121 const sProtocolRequest & req = mpActiveRequest->mRequest;
1122 const cProtocolNotification * pNotifier = req.GetNotifier();
1123
1124 // Notify client of auxiliary data being sent?
1125 if (mpActiveRequest->mRequiredAuxTxs && mpActiveRequest->mCurrentAuxTx)
1126 {
1127 pNotifier->Notify( ePROTOCOL_EVT_AUX_TU_SENT,
1128 (DWORD)reqID,
1129 (DWORD)mpActiveRequest->mEncodedSize );
1130 }
1131
1132 // Check for more auxiliary data to transmit
1133 if (mpActiveRequest->mCurrentAuxTx < mpActiveRequest->mRequiredAuxTxs)
1134 {
1135 ULONG auxDataSz = 0;
1136 const BYTE * pAuxData = req.GetAuxiliaryData( auxDataSz );
1137 if (auxDataSz > 0 && pAuxData != 0)
1138 {
1139 bool bRC = false;
1140
1141 // Adjust for current MTU
1142 pAuxData += (mpActiveRequest->mCurrentAuxTx * MAX_AUX_MTU_SIZE);
1143 mpActiveRequest->mCurrentAuxTx++;
1144
1145 // Last MTU?
1146 if (mpActiveRequest->mCurrentAuxTx == mpActiveRequest->mRequiredAuxTxs)
1147 {
1148 // More than one MTU?
1149 if (mpActiveRequest->mRequiredAuxTxs > 1)
1150 {
1151 auxDataSz = (auxDataSz % MAX_AUX_MTU_SIZE);
1152 if (auxDataSz == 0)
1153 {
1154 auxDataSz = MAX_AUX_MTU_SIZE;
1155 }
1156 }
1157
1158 if (auxDataSz % MAX_PACKET_SIZE == 0)
1159 {
1160 // If last write of unframed write request is divisible
1161 // by 512, break off last byte and send seperatly.
1162 TRACE( "TxComplete() Special case, break off last byte\n" );
1163
1164 bRC = mpConnection->TxData( pAuxData,
1165 auxDataSz - 1 );
1166
1167 if (bRC == true)
1168 {
1169 bRC = mpConnection->TxData( pAuxData + auxDataSz -1,
1170 1 );
1171 }
1172 }
1173 else
1174 {
1175 bRC = mpConnection->TxData( pAuxData,
1176 auxDataSz );
1177 }
1178 }
1179 else if (mpActiveRequest->mRequiredAuxTxs > 1)
1180 {
1181 auxDataSz = MAX_AUX_MTU_SIZE;
1182
1183 bRC = mpConnection->TxData( pAuxData,
1184 auxDataSz );
1185 }
1186
1187 if (bRC == true)
1188 {
1189 mpActiveRequest->mEncodedSize = auxDataSz;
1190 TxComplete();
1191 }
1192 else
1193 {
1194 TxError();
1195 }
1196
1197 return;
1198 }
1199 }
1200
1201 // Another successful transmission, add the buffer to the log
1202 ULONG reqIdx = INVALID_LOG_INDEX;
1203
1204 sProtocolBuffer pb( req.GetSharedBuffer() );
1205 reqIdx = mLog.AddBuffer( pb );
1206
1207 // Notify client?
1208 if (pNotifier != 0)
1209 {
1210 pNotifier->Notify( ePROTOCOL_EVT_REQ_SENT, (DWORD)reqID, (DWORD)reqIdx );
1211 }
1212
1213 // Wait for a response?
1214 if (mpActiveRequest->mRequest.IsTXOnly() == false)
1215 {
1216 // We now await the response
1217 mpActiveRequest->mbWaitingForResponse = true;
1218 mActiveRequestTimeout = TimeIn( mpActiveRequest->mRequest.GetTimeout() );
1219 }
1220 else
1221 {
1222 // Reschedule request as needed
1223 RescheduleActiveRequest();
1224 }
1225 }
1226
1227 /*===========================================================================
1228 METHOD:
1229 TxError (Internal Method)
1230
1231 DESCRIPTION:
1232 Handle transmit data operation error be either rescheduling the
1233 request or cleaning it up
1234
1235 SEQUENCING:
1236 Calling process must have lock on mScheduleMutex
1237
1238 RETURN VALUE:
1239 None
1240 ===========================================================================*/
1241 void cProtocolServer::TxError()
1242 {
1243 // No active request?
1244 if (mpActiveRequest == 0)
1245 {
1246 return;
1247 }
1248
1249 ULONG reqID = mpActiveRequest->mID;
1250 const sProtocolRequest & req = mpActiveRequest->mRequest;
1251 const cProtocolNotification * pNotifier = req.GetNotifier();
1252
1253 // Failure to send request, notify client
1254 if (pNotifier != 0)
1255 {
1256 pNotifier->Notify( ePROTOCOL_EVT_REQ_ERR, (DWORD)reqID, (DWORD)0 );
1257 }
1258
1259 // Reschedule request as needed
1260 RescheduleActiveRequest();
1261 }
1262
1263 /*===========================================================================
1264 METHOD:
1265 Initialize (Public Method)
1266
1267 DESCRIPTION:
1268 Initialize the protocol server by starting up the schedule thread
1269
1270 SEQUENCING:
1271 This method is sequenced according to the schedule mutex, i.e. any
1272 other thread that needs to modify the schedule will block until
1273 this method completes
1274
1275 RETURN VALUE:
1276 bool
1277 ===========================================================================*/
1278 bool cProtocolServer::Initialize()
1279 {
1280 // Assume failure
1281 bool bRC = false;
1282
1283 mbExiting = false;
1284
1285 // Get mScheduleMutex
1286 if (GetScheduleMutex() == true)
1287 {
1288 if (mScheduleThreadID == 0)
1289 {
1290 // Yes, start thread
1291 int nRet = pthread_create( &mScheduleThreadID,
1292 NULL,
1293 ScheduleThread,
1294 this );
1295 if (nRet == 0)
1296 {
1297 // Success!
1298 bRC = true;
1299 }
1300 }
1301 }
1302 else
1303 {
1304 TRACE( "cProtocolServer::Initialize(), unable to aquire ScheduleMutex\n" );
1305 return false;
1306 }
1307
1308 // Unlock schedule mutex
1309 if (ReleaseScheduleMutex() == false)
1310 {
1311 // This should never happen
1312 return false;
1313 }
1314
1315 return bRC;
1316 }
1317
1318 /*===========================================================================
1319 METHOD:
1320 Exit (Public Method)
1321
1322 DESCRIPTION:
1323 Exit the protocol server by exiting the schedule thread (if necessary)
1324
1325 SEQUENCING:
1326 This method is sequenced according to the schedule mutex, i.e. any
1327 other thread that needs to modify the schedule will block until
1328 this method completes
1329
1330 RETURN VALUE:
1331 bool
1332 ===========================================================================*/
1333 bool cProtocolServer::Exit()
1334 {
1335 // Assume failure
1336 bool bRC = false;
1337
1338 if (mScheduleThreadID != 0)
1339 {
1340 if (GetScheduleMutex() == false)
1341 {
1342 // This should never happen
1343 return false;
1344 }
1345
1346 // Check that mScheduleTheadID is still not 0
1347 if (mScheduleThreadID == 0)
1348 {
1349 printf( "mScheduleThreadID was zero!!!\n" );
1350 ReleaseScheduleMutex( false );
1351 return false;
1352 }
1353
1354 // Set exit event
1355 mbExiting = true;
1356
1357 // Signal a schedule update
1358 if (mThreadScheduleEvent.Set( 1 ) != 0)
1359 {
1360 // This should never happen
1361 return false;
1362 }
1363
1364 TRACE( "Joining ScheduleThread %lu\n", mScheduleThreadID );
1365
1366 // Allow process to continue until it finishes
1367 int nRet = pthread_join( mScheduleThreadID, NULL );
1368 if (nRet == ESRCH)
1369 {
1370 TRACE( "ScheduleThread has exited already\n" );
1371 }
1372 else if (nRet != 0)
1373 {
1374 TRACE( "Unable to join ScheduleThread. Error %d: %s\n",
1375 nRet,
1376 strerror( nRet ) );
1377 return false;
1378 }
1379
1380 TRACE( "cProtocolServer::Exit(), completed thread %lu\n",
1381 (ULONG)mScheduleThreadID );
1382
1383 bRC = true;
1384
1385 // Release "handle"
1386 mScheduleThreadID = 0;
1387
1388 // Release mutex lock, don't signal ScheduleThread
1389 if (ReleaseScheduleMutex( false ) == false)
1390 {
1391 // This should never happen
1392 return false;
1393 }
1394 }
1395 else
1396 {
1397 // No ScheduleThread
1398 bRC = true;
1399 }
1400
1401 // Free any allocated requests
1402 std::map <ULONG, sProtocolReqRsp *>::iterator pReqIter;
1403 pReqIter = mRequestMap.begin();
1404
1405 while (pReqIter != mRequestMap.end())
1406 {
1407 sProtocolReqRsp * pReqRsp = pReqIter->second;
1408 if (pReqRsp != 0)
1409 {
1410 delete pReqRsp;
1411 }
1412
1413 pReqIter++;
1414 }
1415
1416 mRequestMap.clear();
1417
1418 // Free log
1419 mLog.Clear();
1420
1421 return bRC;
1422 }
1423
1424 /*===========================================================================
1425 METHOD:
1426 Connect (Public Method)
1427
1428 DESCRIPTION:
1429 Connect to the given communications port
1430
1431 PARAMETERS:
1432 pPort [ I ] - String pointer representing the device node to
1433 connect to (IE: /dev/qcqmi0)
1434
1435 SEQUENCING:
1436 None
1437
1438 RETURN VALUE:
1439 bool
1440 ===========================================================================*/
1441 bool cProtocolServer::Connect( LPCSTR pPort )
1442 {
1443 // Assume failure
1444 bool bRC = false;
1445 if (pPort == 0 || pPort[0] == 0 || mpConnection == 0)
1446 {
1447 return bRC;
1448 }
1449
1450 // Connect to device
1451
1452 // Set callback
1453 mRxCallback.SetServer( this );
1454
1455 // Override to initialize port with protocol specific options
1456 bRC = mpConnection->Connect( pPort );
1457 if (bRC == true)
1458 {
1459 bRC = InitializeComm();
1460 if (bRC == true)
1461 {
1462 // Setup the initial read
1463 mpConnection->RxData( mpRxBuffer,
1464 (ULONG)mRxBufferSize,
1465 (cIOCallback *)&mRxCallback );
1466 }
1467 }
1468
1469 return bRC;
1470 }
1471
1472 /*===========================================================================
1473 METHOD:
1474 Disconnect (Public Method)
1475
1476 DESCRIPTION:
1477 Disconnect from the current communications port
1478
1479 SEQUENCING:
1480 None
1481
1482 RETURN VALUE:
1483 bool
1484 ===========================================================================*/
1485 bool cProtocolServer::Disconnect()
1486 {
1487 // Disconnect
1488
1489 if (mpConnection != 0)
1490 {
1491 // Cancel any outstanding I/O
1492 mpConnection->CancelIO();
1493 }
1494
1495 // Empty callback
1496 mRxCallback.SetServer( 0 );
1497
1498 // Cleanup COM port
1499 CleanupComm();
1500
1501 if (mpConnection != 0)
1502 {
1503 // Now disconnect
1504 bool bDis = mpConnection->Disconnect();
1505 delete mpConnection;
1506 return bDis;
1507 }
1508 else
1509 {
1510 return true;
1511 }
1512 }
1513
1514 /*===========================================================================
1515 METHOD:
1516 IsConnected (Public Method)
1517
1518 DESCRIPTION:
1519 Are we currently connected to a port?
1520
1521 SEQUENCING:
1522 None
1523
1524 RETURN VALUE:
1525 bool
1526 ===========================================================================*/
1527 bool cProtocolServer::IsConnected()
1528 {
1529 return (mpConnection != 0 && mpConnection->IsConnected());
1530 }
1531
1532 /*===========================================================================
1533 METHOD:
1534 AddRequest (Public Method)
1535
1536 DESCRIPTION:
1537 Add an outgoing protocol request to the protocol server request queue
1538
1539 PARAMETERS:
1540 req [ I ] - Request being added
1541
1542 SEQUENCING:
1543 This method is sequenced according to the schedule mutex, i.e. any
1544 other thread that needs to modify the schedule will block until
1545 this method completes
1546
1547 RETURN VALUE:
1548 ULONG - ID of scheduled request (INVALID_REQUEST_ID upon error)
1549 ===========================================================================*/
1550 ULONG cProtocolServer::AddRequest( const sProtocolRequest & req )
1551 {
1552 // Assume failure
1553 ULONG reqID = INVALID_REQUEST_ID;
1554
1555 // Server not configured for sending requests?
1556 if (IsValid( mTxType ) == false)
1557 {
1558 return reqID;
1559 }
1560
1561 // Request type not valid for server?
1562 if (req.GetType() != mTxType)
1563 {
1564 return reqID;
1565 }
1566
1567 // Invalide request?
1568 if (ValidateRequest( req ) == false)
1569 {
1570 return reqID;
1571 }
1572
1573 // Get mScheduleMutex
1574 if (GetScheduleMutex() == true)
1575 {
1576 TRACE( "AddRequest() - Entry at %llu\n", GetTickCount() );
1577
1578 // Grab next available request ID
1579 if (++mLastRequestID == 0)
1580 {
1581 mLastRequestID++;
1582 }
1583
1584 reqID = mLastRequestID;
1585 while (mRequestMap.find( reqID ) != mRequestMap.end())
1586 {
1587 reqID++;
1588 }
1589
1590 // Wrap in our internal structure
1591 sProtocolReqRsp * pReqRsp = 0;
1592 pReqRsp = new sProtocolReqRsp( req, reqID, MAX_AUX_MTU_SIZE );
1593
1594 if (pReqRsp != 0)
1595 {
1596 // Add to request map
1597 mRequestMap[reqID] = pReqRsp;
1598
1599 // ... and schedule
1600 ScheduleRequest( reqID, req.GetSchedule() );
1601 }
1602
1603 TRACE( "AddRequest() - Exit at %llu\n", GetTickCount() );
1604
1605 // Unlock schedule mutex
1606 if (ReleaseScheduleMutex() == false)
1607 {
1608 // This should never happen
1609 return INVALID_REQUEST_ID;
1610 }
1611 }
1612 else
1613 {
1614 TRACE( "cProtocolServer::AddRequest(), unable to get schedule Mutex\n" );
1615 }
1616
1617 return reqID;
1618 }
1619
1620 /*===========================================================================
1621 METHOD:
1622 RemoveRequest (Public Method)
1623
1624 DESCRIPTION:
1625 Remove a previously added protocol request
1626
1627 SEQUENCING:
1628 This method is sequenced according to the schedule mutex, i.e. any
1629 other thread that needs to modify the schedule will block until
1630 this method completes
1631
1632 Note: If a request is being written, it cannot be inturrupted as
1633 both ProcessRequest and RemoveRequest depend on the ScheduleMutex
1634 and the write is synchronus. If the request has been written but
1635 the read has not been triggered it can be removed.
1636
1637 PARAMETERS:
1638 reqID [ I ] - ID of request being removed
1639
1640 RETURN VALUE:
1641 bool
1642 ===========================================================================*/
1643 bool cProtocolServer::RemoveRequest( ULONG reqID )
1644 {
1645 // Assume failure
1646 bool bRC = false;
1647
1648 // Get Schedule Mutex
1649 if (GetScheduleMutex() == true)
1650 {
1651 TRACE( "RemoveRequest() - Entry at %llu\n", GetTickCount() );
1652
1653 bRC = HandleRemoveRequest( reqID );
1654
1655 TRACE( "RemoveRequest() - Exit at %llu\n", GetTickCount() );
1656
1657 // Unlock schedule mutex
1658 if (ReleaseScheduleMutex() == false)
1659 {
1660 // This should never happen
1661 return false;
1662 }
1663 }
1664 else
1665 {
1666 TRACE( "cProtocolServer::RemoveRequest(), unable to get mScheduleMutex\n" );
1667 }
1668
1669 return bRC;
1670 }
1671
1672 /*===========================================================================
1673 METHOD:
1674 GetScheduleMutex (Internal Method)
1675
1676 DESCRIPTION:
1677 Get the schedule mutex. Additionally a check is applied to verify the
1678 DEADLOCK_TIME was not exceeded
1679
1680 SEQUENCING:
1681 This function will block until the mScheduleMutex is aquired
1682
1683 PARAMETERS:
1684
1685 RETURN VALUE:
1686 bool
1687 ===========================================================================*/
1688 bool cProtocolServer::GetScheduleMutex()
1689 {
1690 ULONGLONG nStart = GetTickCount();
1691
1692 //TRACE( "Locking Schedule mutex\n" );
1693 int nRet = pthread_mutex_lock( &mScheduleMutex );
1694 if (nRet != 0)
1695 {
1696 TRACE( "Unable to lock schedule mutex. Error %d: %s\n",
1697 nRet,
1698 strerror( nRet ) );
1699 return false;
1700 }
1701
1702 ULONGLONG nEnd = GetTickCount();
1703 if (nEnd - nStart > DEADLOCK_TIME)
1704 {
1705 TRACE( "Deadlock time exceeded: took %llu ms\n", nEnd - nStart );
1706 ReleaseScheduleMutex( true );
1707 return false;
1708 }
1709
1710 //TRACE( "Locked ScheduleMutex\n" );
1711 return true;
1712 }
1713
1714 /*===========================================================================
1715 METHOD:
1716 ReleaseScheduleMutex (Internal Method)
1717
1718 DESCRIPTION:
1719 Release lock on the schedule mutex
1720
1721 SEQUENCING:
1722 Calling process must have lock
1723
1724 PARAMETERS:
1725 bSignalThread [ I ] - Signal Schedule thread as well?
1726
1727 RETURN VALUE:
1728 bool
1729 ===========================================================================*/
1730 bool cProtocolServer::ReleaseScheduleMutex( bool bSignalThread )
1731 {
1732 if (bSignalThread == true)
1733 {
1734 if (mThreadScheduleEvent.Set( 1 ) != 0)
1735 {
1736 return false;
1737 }
1738 }
1739
1740 int nRet = pthread_mutex_unlock( &mScheduleMutex );
1741 if (nRet != 0)
1742 {
1743 TRACE( "Unable to unlock schedule mutex. Error %d: %s\n",
1744 nRet,
1745 strerror( nRet ) );
1746 return false;
1747 }
1748
1749 return true;
1750 }