Debian Codegraph @

gobi-api/Gobi_2011-11-28-1533/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) 2011, 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 Coop 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 : mComm(),
490 mRxCallback(),
491 mScheduleThreadID( 0 ),
492 mThreadScheduleEvent(),
493 mbExiting( false ),
494 mpServerControl( 0 ),
495 mLastRequestID( 1 ),
496 mpActiveRequest( 0 ),
497 mpRxBuffer( 0 ),
498 mRxBufferSize( bufferSzRx ),
499 mRxType( rxType ),
500 mTxType( txType ),
501 mLog( logSz )
502 {
503 mLastTime = TimeIn( 0 );
504
505 // Allocate receive buffer?
506 if (mRxBufferSize > 0 && mComm.IsValid() == true)
507 {
508 mpRxBuffer = new BYTE[mRxBufferSize];
509 }
510
511 // Before continuing verify receive buffer was allocated
512 if (mpRxBuffer != 0)
513 {
514 // Schedule mutex
515 int nRet = pthread_mutex_init( &mScheduleMutex, NULL );
516 if (nRet != 0)
517 {
518 TRACE( "Unable to init schedule mutex. Error %d: %s\n",
519 nRet,
520 strerror( nRet ) );
521 return;
522 }
523 }
524 }
525
526 /*===========================================================================
527 METHOD:
528 ~cProtocolServer (Public Method)
529
530 DESCRIPTION:
531 Destructor
532
533 SEQUENCING:
534 None (destroys sequencing objects)
535
536 RETURN VALUE:
537 None
538 ===========================================================================*/
539 cProtocolServer::~cProtocolServer()
540 {
541 // This should have already been called, but ...
542 Exit();
543
544 // Schedule mutex
545 int nRet = pthread_mutex_destroy( &mScheduleMutex );
546 if (nRet != 0)
547 {
548 TRACE( "Unable to destroy schedule mutex. Error %d: %s\n",
549 nRet,
550 strerror( nRet ) );
551 }
552
553 // Free receive buffer
554 if (mpRxBuffer != 0)
555 {
556 delete [] mpRxBuffer;
557 mpRxBuffer = 0;
558 }
559 }
560
561 /*===========================================================================
562 METHOD:
563 HandleRemoveRequest (Public Method)
564
565 DESCRIPTION:
566 Remove a previously added protocol request
567
568 Note: if a request is being processed, it cannot be inturrupted
569
570 PARAMETERS:
571 reqID [ I ] - Server assigned request ID
572
573 SEQUENCING:
574 Calling process must have lock on mScheduleMutex
575
576 RETURN VALUE:
577 bool
578 ===========================================================================*/
579 bool cProtocolServer::HandleRemoveRequest( ULONG reqID )
580 {
581 // Assume failure
582 bool bRC = false;
583
584 // Find and erase request from request map
585 std::map <ULONG, sProtocolReqRsp *>::iterator pReqIter;
586 pReqIter = mRequestMap.find( reqID );
587
588 if (pReqIter != mRequestMap.end())
589 {
590 sProtocolReqRsp * pReqRsp = pReqIter->second;
591 if (pReqRsp != 0)
592 {
593 delete pReqRsp;
594 }
595
596 mRequestMap.erase( pReqIter );
597
598 // Success!
599 bRC = true;
600
601 // Find and erase request from schedule
602 bool bFound = false;
603 int entryIndex = -1;
604
605 std::set <tSchedule>::iterator pScheduleIter;
606 pScheduleIter = mRequestSchedule.begin();
607
608 while (pScheduleIter != mRequestSchedule.end())
609 {
610 entryIndex++;
611
612 tSchedule entry = *pScheduleIter;
613 if (entry.second == reqID)
614 {
615 bFound = true;
616 mRequestSchedule.erase( pScheduleIter );
617 break;
618 }
619 else
620 {
621 pScheduleIter++;
622 }
623 }
624
625 // Note: schedule will be updated when mutex is unlocked/signaled
626 }
627 else if (mpActiveRequest != 0 && mpActiveRequest->mID == reqID)
628 {
629 const sProtocolRequest & req = mpActiveRequest->mRequest;
630 const cProtocolNotification * pNotifier = req.GetNotifier();
631
632 // Cancel the response timer (when active)
633 if (mpActiveRequest->mbWaitingForResponse == true)
634 {
635 // Schedule will be updated when mutex is unlocked
636
637 // Failure to receive response, notify client
638 if (pNotifier != 0)
639 {
640 pNotifier->Notify( ePROTOCOL_EVT_RSP_ERR,
641 (DWORD)reqID,
642 ECANCELED );
643 }
644 }
645 else
646 {
647 // This is the active request, cancel the underlying transmit
648 // Note: Because ProcessRequest and RemoveRequest are both muxed
649 // with ScheduleMutex, it is impossible to for the write
650 // to actually be in progress when this code is reached.
651 mComm.CancelTx();
652
653 // Failure to send request, notify client
654 if (pNotifier != 0)
655 {
656 pNotifier->Notify( ePROTOCOL_EVT_REQ_ERR,
657 (DWORD)reqID,
658 ECANCELED );
659 }
660 }
661
662 // Now delete the request
663 delete mpActiveRequest;
664 mpActiveRequest = 0;
665
666 // Success!
667 bRC = true;
668 }
669 else
670 {
671 TRACE( "cProtocolServer::RemoveRequest( %lu ),"
672 " invalid request ID\n",
673 reqID );
674 }
675
676 return bRC;
677 }
678
679 /*===========================================================================
680 METHOD:
681 ScheduleRequest (Internal Method)
682
683 DESCRIPTION:
684 Schedule a request for transmission
685
686 PARAMETERS:
687 reqID [ I ] - ID of the request being scheduled this ID must exist
688 in the internal request/schedule maps
689
690 schedule [ I ] - Value in milliseconds that indicates the approximate
691 time from now that the request is to be sent out, the
692 actual time that the request is sent will be greater
693 than or equal to this value dependant on requests
694 scheduled before the request in question and
695 standard server processing time
696
697 SEQUENCING:
698 Calling process must have lock on mScheduleMutex
699
700 RETURN VALUE:
701 bool
702 ===========================================================================*/
703 bool cProtocolServer::ScheduleRequest(
704 ULONG reqID,
705 ULONG schedule )
706 {
707 // Assume failure
708 bool bRC = false;
709
710 // Schedule adjust is in milliseconds
711 timespec schTimer = TimeIn( schedule );
712
713 // Create the schedule entry
714 tSchedule newEntry( schTimer, reqID );
715
716 // Fit this request into the schedule (ordered by scheduled time)
717 mRequestSchedule.insert( newEntry );
718
719 // Note: timer will be updated when mScheduleMutex is unlocked
720
721 return bRC;
722 }
723
724 /*===========================================================================
725 METHOD:
726 RescheduleActiveRequest (Internal Method)
727
728 DESCRIPTION:
729 Reschedule (or cleanup) the active request
730
731 SEQUENCING:
732 Calling process must have lock on mScheduleMutex
733
734 RETURN VALUE:
735 None
736 ===========================================================================*/
737 void cProtocolServer::RescheduleActiveRequest()
738 {
739 // Are there more attempts to be made?
740 if (mpActiveRequest->mAttempts < mpActiveRequest->mRequest.GetRequests())
741 {
742 // Yes, first reset the request
743 mpActiveRequest->Reset();
744
745 // Now add it back to the request map
746 mRequestMap[mpActiveRequest->mID] = mpActiveRequest;
747
748 TRACE( "RescheduleActiveRequest(): req %lu rescheduled\n", mpActiveRequest->mID );
749
750 // Lastly reschedule the request
751 ScheduleRequest( mpActiveRequest->mID,
752 mpActiveRequest->mRequest.GetFrequency() );
753
754 }
755 else
756 {
757 TRACE( "RescheduleActiveRequest(): req %lu removed\n", mpActiveRequest->mID );
758
759 // No, we are through with this request
760 delete mpActiveRequest;
761 }
762
763 // There is no longer an active request
764 mpActiveRequest = 0;
765
766 }
767
768 /*===========================================================================
769 METHOD:
770 ProcessRequest (Internal Method)
771
772 DESCRIPTION:
773 Process a single outgoing protocol request, this consists of removing
774 the request ID from the head of the schedule, looking up the internal
775 request object in the request map, sending out the request, and setting
776 up the response timer (if a response is required)
777
778 SEQUENCING:
779 Calling process must have lock on mScheduleMutex
780
781 RETURN VALUE:
782 ===========================================================================*/
783 void cProtocolServer::ProcessRequest()
784 {
785 // Is there already an active request?
786 if (mpActiveRequest != 0)
787 {
788 return;
789 }
790
791 // Grab request ID from the schedule
792 std::set <tSchedule>::iterator pScheduleIter;
793 pScheduleIter = mRequestSchedule.begin();
794
795 // Did we find the request?
796 if (pScheduleIter == mRequestSchedule.end())
797 {
798 // No
799 return;
800 }
801
802 // Yes, grab the request ID
803 ULONG reqID = pScheduleIter->second;
804
805 // Remove from schedule
806 mRequestSchedule.erase( pScheduleIter );
807
808 // Look up the internal request object
809 std::map <ULONG, sProtocolReqRsp *>::iterator pReqIter;
810 pReqIter = mRequestMap.find( reqID );
811
812 // Request not found around?
813 if (pReqIter == mRequestMap.end() || pReqIter->second == 0)
814 {
815 // No
816 return;
817 }
818
819 // Set this request as the active request
820 mpActiveRequest = pReqIter->second;
821
822 TRACE( "ProcessRequest(): req %lu started\n", mpActiveRequest->mID );
823
824 // Remove request from pending request map
825 mRequestMap.erase( pReqIter );
826
827 // Extract the underlying request
828 const sProtocolRequest & req = mpActiveRequest->mRequest;
829
830 // Increment attempt count?
831 if (req.GetRequests() != INFINITE_REQS)
832 {
833 // This request isn't an indefinite one, so keep track of each attempt
834 mpActiveRequest->mAttempts++;
835 }
836
837 bool bTxSuccess = false;
838
839 // Encode data for transmission?
840 bool bEncoded = false;
841 sSharedBuffer * pEncoded = 0;
842 pEncoded = EncodeTxData( req.GetSharedBuffer(), bEncoded );
843 if (bEncoded == false)
844 {
845 // Note: no longer asynchronus
846 // Send the request data
847 bTxSuccess = mComm.TxData( req.GetBuffer(),
848 req.GetSize() );
849 }
850 else if (bEncoded == true)
851 {
852 if (pEncoded != 0 && pEncoded->IsValid() == true)
853 {
854 // Note: no longer asynchronus
855 // Send the request data
856 mpActiveRequest->mEncodedSize = pEncoded->GetSize();
857 bTxSuccess = mComm.TxData( pEncoded->GetBuffer(),
858 pEncoded->GetSize() );
859 }
860 }
861
862 if (bTxSuccess == true)
863 {
864 TRACE( "ProcessRequest(): req %lu finished\n", mpActiveRequest->mID );
865 TxComplete();
866 }
867 else
868 {
869 TxError();
870 TRACE( "ProcessRequest(): req finished with a TxError\n" );
871 }
872
873 return;
874 }
875
876 /*===========================================================================
877 METHOD:
878 CheckSystemTime (Internal Method)
879
880 DESCRIPTION:
881 Check that system time hasn't moved backwards. Since we use the system
882 time for scheduling requests we need to periodically check that the
883 user (or system itself) hasn't reset system time backwards, if it has
884 then we reschedule everything to the current system time. This disrupts
885 the schedule but avoids stranding requests
886
887 Updates mLastTime
888
889 SEQUENCING:
890 Calling process must have lock on mScheduleMutex
891
892 RETURN VALUE:
893 bool: System time moved backwards?
894 ===========================================================================*/
895 bool cProtocolServer::CheckSystemTime()
896 {
897 // Assume that time is still marching forward
898 bool bAdjust = false;
899
900 timespec curTime = TimeIn( 0 );
901
902 if (curTime < mLastTime)
903 {
904 // Looks like the system clock has been adjusted to an earlier
905 // value, go through the current schedule and adjust each timer
906 // to reflect the adjustment. This isn't an exact approach but
907 // it prevents requests from being stranded which is our goal
908
909 // Note: set iterators are constant. This means we need to
910 // create a set with the new data, we can't modify this one
911
912 std::set < tSchedule, std::less <tSchedule> > tempSchedule;
913
914 std::set <tSchedule>::iterator pScheduleIter;
915 pScheduleIter = mRequestSchedule.begin();
916
917 while (pScheduleIter != mRequestSchedule.end())
918 {
919 tSchedule entry = *pScheduleIter;
920 entry.first.tv_sec = curTime.tv_sec;
921 entry.first.tv_nsec = curTime.tv_nsec;
922 tempSchedule.insert( entry );
923
924 pScheduleIter++;
925 }
926
927 mRequestSchedule = tempSchedule;
928
929 // Update mActiveRequestTimeout
930 if ( (mpActiveRequest != 0)
931 && (mpActiveRequest->mbWaitingForResponse == true) )
932 {
933 // Restart active request's timeout
934 ULONG mTimeout = mpActiveRequest->mRequest.GetTimeout();
935 mActiveRequestTimeout = TimeIn( mTimeout );
936 }
937
938 TRACE( "Time has moved backwards, schedule updated\n" );
939
940 // Indicate the change
941 bAdjust = true;
942 }
943
944 mLastTime.tv_sec = curTime.tv_sec;
945 mLastTime.tv_nsec = curTime.tv_nsec;
946
947 return bAdjust;
948 }
949
950 /*===========================================================================
951 METHOD:
952 RxComplete (Internal Method)
953
954 DESCRIPTION:
955 Handle completion of receive data operation
956
957 PARAMETERS:
958 status [ I ] - Status of operation
959 bytesReceived [ I ] - Number of bytes received
960
961 SEQUENCING:
962 This method is sequenced according to the schedule mutex
963 i.e. any other thread that needs to modify the schedule
964 will block until this method completes
965
966 RETURN VALUE:
967 None
968 ===========================================================================*/
969 void cProtocolServer::RxComplete(
970 DWORD status,
971 DWORD bytesReceived )
972 {
973 if (status != NO_ERROR)
974 {
975 TRACE( "cProtocolServer::RxComplete() = %lu\n", status );
976 }
977
978 // Error with the read
979 if (status != NO_ERROR || bytesReceived == 0)
980 {
981 // Setup the next read
982 mComm.RxData( mpRxBuffer,
983 (ULONG)mRxBufferSize,
984 (cIOCallback *)&mRxCallback );
985
986 return;
987 }
988
989 // Get Schedule Mutex
990 if (GetScheduleMutex() == false)
991 {
992 TRACE( "RxComplete(), unable to get schedule Mutex\n" );
993 return;
994 }
995
996 TRACE( "RxComplete() - Entry at %llu\n", GetTickCount() );
997
998 // Decode data
999 bool bAbortTx = false;
1000 ULONG rspIdx = INVALID_LOG_INDEX;
1001 bool bRsp = DecodeRxData( bytesReceived, rspIdx, bAbortTx );
1002
1003 // Is there an active request that needs to be aborted
1004 if (mpActiveRequest != 0 && bAbortTx == true)
1005 {
1006 // Yes, terminate the transmission and handle the error
1007 mComm.CancelTx();
1008 TxError();
1009 }
1010 // Is there an active request and a valid response?
1011 else if (mpActiveRequest != 0 && bRsp == true)
1012 {
1013 const sProtocolRequest & req = mpActiveRequest->mRequest;
1014 const cProtocolNotification * pNotifier = req.GetNotifier();
1015
1016 // Notify client that response was received
1017 if (pNotifier != 0)
1018 {
1019 pNotifier->Notify( ePROTOCOL_EVT_RSP_RECV,
1020 (DWORD)mpActiveRequest->mID,
1021 (DWORD)rspIdx );
1022 }
1023
1024 // Reschedule request as needed
1025 RescheduleActiveRequest();
1026 }
1027
1028 // Setup the next read
1029 mComm.RxData( mpRxBuffer,
1030 (ULONG)mRxBufferSize,
1031 (cIOCallback *)&mRxCallback );
1032
1033 TRACE( "RxComplete() - Exit at %llu\n", GetTickCount() );
1034
1035 // Unlock schedule mutex
1036 if (ReleaseScheduleMutex() == false)
1037 {
1038 // This should never happen
1039 return;
1040 }
1041
1042 return;
1043 }
1044
1045 /*===========================================================================
1046 METHOD:
1047 RxTimeout (Internal Method)
1048
1049 DESCRIPTION:
1050 Handle the response timer expiring
1051
1052 SEQUENCING:
1053 Calling process must have lock on mScheduleMutex
1054
1055 RETURN VALUE:
1056 None
1057 ===========================================================================*/
1058 void cProtocolServer::RxTimeout()
1059 {
1060 // No active request?
1061 if (mpActiveRequest == 0)
1062 {
1063 TRACE( "RxTimeout() with no active request\n" );
1064 ASSERT( 0 );
1065 }
1066
1067 TRACE( "RxTimeout() for req %lu\n", mpActiveRequest->mID );
1068
1069 const sProtocolRequest & req = mpActiveRequest->mRequest;
1070 const cProtocolNotification * pNotifier = req.GetNotifier();
1071
1072 // Failure to receive response, notify client
1073 if (pNotifier != 0)
1074 {
1075 pNotifier->Notify( ePROTOCOL_EVT_RSP_ERR,
1076 (DWORD)mpActiveRequest->mID,
1077 (DWORD)0 );
1078 }
1079
1080 // Reschedule request as needed
1081 RescheduleActiveRequest();
1082 }
1083
1084 /*===========================================================================
1085 METHOD:
1086 TxComplete (Internal Method)
1087
1088 DESCRIPTION:
1089 Handle completion of transmit data operation
1090
1091 PARAMETERS:
1092
1093 SEQUENCING:
1094 Calling process must have lock on mScheduleMutex
1095
1096 RETURN VALUE:
1097 None
1098 ===========================================================================*/
1099 void cProtocolServer::TxComplete()
1100 {
1101 // No active request?
1102 if (mpActiveRequest == 0)
1103 {
1104 TRACE( "TxComplete() called with no active request\n" );
1105 ASSERT( 0 );
1106 }
1107
1108 TRACE( "TxComplete() req %lu started\n", mpActiveRequest->mID );
1109
1110 ULONG reqID = mpActiveRequest->mID;
1111 const sProtocolRequest & req = mpActiveRequest->mRequest;
1112 const cProtocolNotification * pNotifier = req.GetNotifier();
1113
1114 // Notify client of auxiliary data being sent?
1115 if (mpActiveRequest->mRequiredAuxTxs && mpActiveRequest->mCurrentAuxTx)
1116 {
1117 pNotifier->Notify( ePROTOCOL_EVT_AUX_TU_SENT,
1118 (DWORD)reqID,
1119 (DWORD)mpActiveRequest->mEncodedSize );
1120 }
1121
1122 // Check for more auxiliary data to transmit
1123 if (mpActiveRequest->mCurrentAuxTx < mpActiveRequest->mRequiredAuxTxs)
1124 {
1125 ULONG auxDataSz = 0;
1126 const BYTE * pAuxData = req.GetAuxiliaryData( auxDataSz );
1127 if (auxDataSz > 0 && pAuxData != 0)
1128 {
1129 bool bRC = false;
1130
1131 // Adjust for current MTU
1132 pAuxData += (mpActiveRequest->mCurrentAuxTx * MAX_AUX_MTU_SIZE);
1133 mpActiveRequest->mCurrentAuxTx++;
1134
1135 // Last MTU?
1136 if (mpActiveRequest->mCurrentAuxTx == mpActiveRequest->mRequiredAuxTxs)
1137 {
1138 // More than one MTU?
1139 if (mpActiveRequest->mRequiredAuxTxs > 1)
1140 {
1141 auxDataSz = (auxDataSz % MAX_AUX_MTU_SIZE);
1142 if (auxDataSz == 0)
1143 {
1144 auxDataSz = MAX_AUX_MTU_SIZE;
1145 }
1146 }
1147
1148 if (auxDataSz % MAX_PACKET_SIZE == 0)
1149 {
1150 // If last write of unframed write request is divisible
1151 // by 512, break off last byte and send seperatly.
1152 TRACE( "TxComplete() Special case, break off last byte\n" );
1153
1154 bRC = mComm.TxData( pAuxData,
1155 auxDataSz - 1 );
1156
1157 if (bRC == true)
1158 {
1159 bRC = mComm.TxData( pAuxData + auxDataSz -1,
1160 1 );
1161 }
1162 }
1163 else
1164 {
1165 bRC = mComm.TxData( pAuxData,
1166 auxDataSz );
1167 }
1168 }
1169 else if (mpActiveRequest->mRequiredAuxTxs > 1)
1170 {
1171 auxDataSz = MAX_AUX_MTU_SIZE;
1172
1173 bRC = mComm.TxData( pAuxData,
1174 auxDataSz );
1175 }
1176
1177 if (bRC == true)
1178 {
1179 mpActiveRequest->mEncodedSize = auxDataSz;
1180 TxComplete();
1181 }
1182 else
1183 {
1184 TxError();
1185 }
1186
1187 return;
1188 }
1189 }
1190
1191 // Another successful transmission, add the buffer to the log
1192 ULONG reqIdx = INVALID_LOG_INDEX;
1193
1194 sProtocolBuffer pb( req.GetSharedBuffer() );
1195 reqIdx = mLog.AddBuffer( pb );
1196
1197 // Notify client?
1198 if (pNotifier != 0)
1199 {
1200 pNotifier->Notify( ePROTOCOL_EVT_REQ_SENT, (DWORD)reqID, (DWORD)reqIdx );
1201 }
1202
1203 // Wait for a response?
1204 if (mpActiveRequest->mRequest.IsTXOnly() == false)
1205 {
1206 // We now await the response
1207 mpActiveRequest->mbWaitingForResponse = true;
1208 mActiveRequestTimeout = TimeIn( mpActiveRequest->mRequest.GetTimeout() );
1209 }
1210 else
1211 {
1212 // Reschedule request as needed
1213 RescheduleActiveRequest();
1214 }
1215 }
1216
1217 /*===========================================================================
1218 METHOD:
1219 TxError (Internal Method)
1220
1221 DESCRIPTION:
1222 Handle transmit data operation error be either rescheduling the
1223 request or cleaning it up
1224
1225 SEQUENCING:
1226 Calling process must have lock on mScheduleMutex
1227
1228 RETURN VALUE:
1229 None
1230 ===========================================================================*/
1231 void cProtocolServer::TxError()
1232 {
1233 // No active request?
1234 if (mpActiveRequest == 0)
1235 {
1236 return;
1237 }
1238
1239 ULONG reqID = mpActiveRequest->mID;
1240 const sProtocolRequest & req = mpActiveRequest->mRequest;
1241 const cProtocolNotification * pNotifier = req.GetNotifier();
1242
1243 // Failure to send request, notify client
1244 if (pNotifier != 0)
1245 {
1246 pNotifier->Notify( ePROTOCOL_EVT_REQ_ERR, (DWORD)reqID, (DWORD)0 );
1247 }
1248
1249 // Reschedule request as needed
1250 RescheduleActiveRequest();
1251 }
1252
1253 /*===========================================================================
1254 METHOD:
1255 Initialize (Public Method)
1256
1257 DESCRIPTION:
1258 Initialize the protocol server by starting up the schedule thread
1259
1260 SEQUENCING:
1261 This method is sequenced according to the schedule mutex, i.e. any
1262 other thread that needs to modify the schedule will block until
1263 this method completes
1264
1265 RETURN VALUE:
1266 bool
1267 ===========================================================================*/
1268 bool cProtocolServer::Initialize()
1269 {
1270 // Assume failure
1271 bool bRC = false;
1272
1273 mbExiting = false;
1274
1275 // Get mScheduleMutex
1276 if (GetScheduleMutex() == true)
1277 {
1278 if (mScheduleThreadID == 0)
1279 {
1280 // Yes, start thread
1281 int nRet = pthread_create( &mScheduleThreadID,
1282 NULL,
1283 ScheduleThread,
1284 this );
1285 if (nRet == 0)
1286 {
1287 // Success!
1288 bRC = true;
1289 }
1290 }
1291 }
1292 else
1293 {
1294 TRACE( "cProtocolServer::Initialize(), unable to aquire ScheduleMutex\n" );
1295 return false;
1296 }
1297
1298 // Unlock schedule mutex
1299 if (ReleaseScheduleMutex() == false)
1300 {
1301 // This should never happen
1302 return false;
1303 }
1304
1305 return bRC;
1306 }
1307
1308 /*===========================================================================
1309 METHOD:
1310 Exit (Public Method)
1311
1312 DESCRIPTION:
1313 Exit the protocol server by exiting the schedule thread (if necessary)
1314
1315 SEQUENCING:
1316 This method is sequenced according to the schedule mutex, i.e. any
1317 other thread that needs to modify the schedule will block until
1318 this method completes
1319
1320 RETURN VALUE:
1321 bool
1322 ===========================================================================*/
1323 bool cProtocolServer::Exit()
1324 {
1325 // Assume failure
1326 bool bRC = false;
1327
1328 if (mScheduleThreadID != 0)
1329 {
1330 if (GetScheduleMutex() == false)
1331 {
1332 // This should never happen
1333 return false;
1334 }
1335
1336 // Check that mScheduleTheadID is still not 0
1337 if (mScheduleThreadID == 0)
1338 {
1339 printf( "mScheduleThreadID was zero!!!\n" );
1340 ReleaseScheduleMutex( false );
1341 return false;
1342 }
1343
1344 // Set exit event
1345 mbExiting = true;
1346
1347 // Signal a schedule update
1348 if (mThreadScheduleEvent.Set( 1 ) != 0)
1349 {
1350 // This should never happen
1351 return false;
1352 }
1353
1354 TRACE( "Joining ScheduleThread %lu\n", mScheduleThreadID );
1355
1356 // Allow process to continue until it finishes
1357 int nRet = pthread_join( mScheduleThreadID, NULL );
1358 if (nRet == ESRCH)
1359 {
1360 TRACE( "ScheduleThread has exited already\n" );
1361 }
1362 else if (nRet != 0)
1363 {
1364 TRACE( "Unable to join ScheduleThread. Error %d: %s\n",
1365 nRet,
1366 strerror( nRet ) );
1367 return false;
1368 }
1369
1370 TRACE( "cProtocolServer::Exit(), completed thread %lu\n",
1371 (ULONG)mScheduleThreadID );
1372
1373 bRC = true;
1374
1375 // Release "handle"
1376 mScheduleThreadID = 0;
1377
1378 // Release mutex lock, don't signal ScheduleThread
1379 if (ReleaseScheduleMutex( false ) == false)
1380 {
1381 // This should never happen
1382 return false;
1383 }
1384 }
1385 else
1386 {
1387 // No ScheduleThread
1388 bRC = true;
1389 }
1390
1391 // Free any allocated requests
1392 std::map <ULONG, sProtocolReqRsp *>::iterator pReqIter;
1393 pReqIter = mRequestMap.begin();
1394
1395 while (pReqIter != mRequestMap.end())
1396 {
1397 sProtocolReqRsp * pReqRsp = pReqIter->second;
1398 if (pReqRsp != 0)
1399 {
1400 delete pReqRsp;
1401 }
1402
1403 pReqIter++;
1404 }
1405
1406 mRequestMap.clear();
1407
1408 // Free log
1409 mLog.Clear();
1410
1411 return bRC;
1412 }
1413
1414 /*===========================================================================
1415 METHOD:
1416 Connect (Public Method)
1417
1418 DESCRIPTION:
1419 Connect to the given communications port
1420
1421 PARAMETERS:
1422 pPort [ I ] - String pointer representing the device node to
1423 connect to (IE: /dev/qcqmi0)
1424
1425 SEQUENCING:
1426 None
1427
1428 RETURN VALUE:
1429 bool
1430 ===========================================================================*/
1431 bool cProtocolServer::Connect( LPCSTR pPort )
1432 {
1433 // Assume failure
1434 bool bRC = false;
1435 if (pPort == 0 || pPort[0] == 0)
1436 {
1437 return bRC;
1438 }
1439
1440 // Connect to device
1441
1442 // Set callback
1443 mRxCallback.SetServer( this );
1444
1445 // Override to initialize port with protocol specific options
1446 bRC = mComm.Connect( pPort );
1447 if (bRC == true)
1448 {
1449 bRC = InitializeComm();
1450 if (bRC == true)
1451 {
1452 // Setup the initial read
1453 mComm.RxData( mpRxBuffer,
1454 (ULONG)mRxBufferSize,
1455 (cIOCallback *)&mRxCallback );
1456 }
1457 }
1458
1459 return bRC;
1460 }
1461
1462 /*===========================================================================
1463 METHOD:
1464 Disconnect (Public Method)
1465
1466 DESCRIPTION:
1467 Disconnect from the current communications port
1468
1469 SEQUENCING:
1470 None
1471
1472 RETURN VALUE:
1473 bool
1474 ===========================================================================*/
1475 bool cProtocolServer::Disconnect()
1476 {
1477 // Disconnect
1478
1479 // Cancel any outstanding I/O
1480 mComm.CancelIO();
1481
1482 // Empty callback
1483 mRxCallback.SetServer( 0 );
1484
1485 // Cleanup COM port
1486 CleanupComm();
1487
1488 // Now disconnect
1489 return mComm.Disconnect();
1490 }
1491
1492 /*===========================================================================
1493 METHOD:
1494 IsConnected (Public Method)
1495
1496 DESCRIPTION:
1497 Are we currently connected to a port?
1498
1499 SEQUENCING:
1500 None
1501
1502 RETURN VALUE:
1503 bool
1504 ===========================================================================*/
1505 bool cProtocolServer::IsConnected()
1506 {
1507 return mComm.IsConnected();
1508 }
1509
1510 /*===========================================================================
1511 METHOD:
1512 AddRequest (Public Method)
1513
1514 DESCRIPTION:
1515 Add an outgoing protocol request to the protocol server request queue
1516
1517 PARAMETERS:
1518 req [ I ] - Request being added
1519
1520 SEQUENCING:
1521 This method is sequenced according to the schedule mutex, i.e. any
1522 other thread that needs to modify the schedule will block until
1523 this method completes
1524
1525 RETURN VALUE:
1526 ULONG - ID of scheduled request (INVALID_REQUEST_ID upon error)
1527 ===========================================================================*/
1528 ULONG cProtocolServer::AddRequest( const sProtocolRequest & req )
1529 {
1530 // Assume failure
1531 ULONG reqID = INVALID_REQUEST_ID;
1532
1533 // Server not configured for sending requests?
1534 if (IsValid( mTxType ) == false)
1535 {
1536 return reqID;
1537 }
1538
1539 // Request type not valid for server?
1540 if (req.GetType() != mTxType)
1541 {
1542 return reqID;
1543 }
1544
1545 // Invalide request?
1546 if (ValidateRequest( req ) == false)
1547 {
1548 return reqID;
1549 }
1550
1551 // Get mScheduleMutex
1552 if (GetScheduleMutex() == true)
1553 {
1554 TRACE( "AddRequest() - Entry at %llu\n", GetTickCount() );
1555
1556 // Grab next available request ID
1557 if (++mLastRequestID == 0)
1558 {
1559 mLastRequestID++;
1560 }
1561
1562 reqID = mLastRequestID;
1563 while (mRequestMap.find( reqID ) != mRequestMap.end())
1564 {
1565 reqID++;
1566 }
1567
1568 // Wrap in our internal structure
1569 sProtocolReqRsp * pReqRsp = 0;
1570 pReqRsp = new sProtocolReqRsp( req, reqID, MAX_AUX_MTU_SIZE );
1571
1572 if (pReqRsp != 0)
1573 {
1574 // Add to request map
1575 mRequestMap[reqID] = pReqRsp;
1576
1577 // ... and schedule
1578 ScheduleRequest( reqID, req.GetSchedule() );
1579 }
1580
1581 TRACE( "AddRequest() - Exit at %llu\n", GetTickCount() );
1582
1583 // Unlock schedule mutex
1584 if (ReleaseScheduleMutex() == false)
1585 {
1586 // This should never happen
1587 return INVALID_REQUEST_ID;
1588 }
1589 }
1590 else
1591 {
1592 TRACE( "cProtocolServer::AddRequest(), unable to get schedule Mutex\n" );
1593 }
1594
1595 return reqID;
1596 }
1597
1598 /*===========================================================================
1599 METHOD:
1600 RemoveRequest (Public Method)
1601
1602 DESCRIPTION:
1603 Remove a previously added protocol request
1604
1605 SEQUENCING:
1606 This method is sequenced according to the schedule mutex, i.e. any
1607 other thread that needs to modify the schedule will block until
1608 this method completes
1609
1610 Note: If a request is being written, it cannot be inturrupted as
1611 both ProcessRequest and RemoveRequest depend on the ScheduleMutex
1612 and the write is synchronus. If the request has been written but
1613 the read has not been triggered it can be removed.
1614
1615 PARAMETERS:
1616 reqID [ I ] - ID of request being removed
1617
1618 RETURN VALUE:
1619 bool
1620 ===========================================================================*/
1621 bool cProtocolServer::RemoveRequest( ULONG reqID )
1622 {
1623 // Assume failure
1624 bool bRC = false;
1625
1626 // Get Schedule Mutex
1627 if (GetScheduleMutex() == true)
1628 {
1629 TRACE( "RemoveRequest() - Entry at %llu\n", GetTickCount() );
1630
1631 bRC = HandleRemoveRequest( reqID );
1632
1633 TRACE( "RemoveRequest() - Exit at %llu\n", GetTickCount() );
1634
1635 // Unlock schedule mutex
1636 if (ReleaseScheduleMutex() == false)
1637 {
1638 // This should never happen
1639 return false;
1640 }
1641 }
1642 else
1643 {
1644 TRACE( "cProtocolServer::RemoveRequest(), unable to get mScheduleMutex\n" );
1645 }
1646
1647 return bRC;
1648 }
1649
1650 /*===========================================================================
1651 METHOD:
1652 GetScheduleMutex (Internal Method)
1653
1654 DESCRIPTION:
1655 Get the schedule mutex. Additionally a check is applied to verify the
1656 DEADLOCK_TIME was not exceeded
1657
1658 SEQUENCING:
1659 This function will block until the mScheduleMutex is aquired
1660
1661 PARAMETERS:
1662
1663 RETURN VALUE:
1664 bool
1665 ===========================================================================*/
1666 bool cProtocolServer::GetScheduleMutex()
1667 {
1668 ULONGLONG nStart = GetTickCount();
1669
1670 //TRACE( "Locking Schedule mutex\n" );
1671 int nRet = pthread_mutex_lock( &mScheduleMutex );
1672 if (nRet != 0)
1673 {
1674 TRACE( "Unable to lock schedule mutex. Error %d: %s\n",
1675 nRet,
1676 strerror( nRet ) );
1677 return false;
1678 }
1679
1680 ULONGLONG nEnd = GetTickCount();
1681 if (nEnd - nStart > DEADLOCK_TIME)
1682 {
1683 TRACE( "Deadlock time exceeded: took %llu ms\n", nEnd - nStart );
1684 ReleaseScheduleMutex( true );
1685 return false;
1686 }
1687
1688 //TRACE( "Locked ScheduleMutex\n" );
1689 return true;
1690 }
1691
1692 /*===========================================================================
1693 METHOD:
1694 ReleaseScheduleMutex (Internal Method)
1695
1696 DESCRIPTION:
1697 Release lock on the schedule mutex
1698
1699 SEQUENCING:
1700 Calling process must have lock
1701
1702 PARAMETERS:
1703 bSignalThread [ I ] - Signal Schedule thread as well?
1704
1705 RETURN VALUE:
1706 bool
1707 ===========================================================================*/
1708 bool cProtocolServer::ReleaseScheduleMutex( bool bSignalThread )
1709 {
1710 if (bSignalThread == true)
1711 {
1712 if (mThreadScheduleEvent.Set( 1 ) != 0)
1713 {
1714 return false;
1715 }
1716 }
1717
1718 int nRet = pthread_mutex_unlock( &mScheduleMutex );
1719 if (nRet != 0)
1720 {
1721 TRACE( "Unable to unlock schedule mutex. Error %d: %s\n",
1722 nRet,
1723 strerror( nRet ) );
1724 return false;
1725 }
1726
1727 return true;
1728 }