summaryrefslogtreecommitdiff
path: root/FreeRTOS-Plus/Source/FreeRTOS-Plus-IoT-SDK/c_sdk/standard/common/taskpool/iot_taskpool.c
blob: fff69ca83aec0b9eba9d221e6b05dbb26719bc79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
/*
 * Amazon FreeRTOS Common V1.0.0
 * Copyright (C) 2018 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * http://aws.amazon.com/freertos
 * http://www.FreeRTOS.org
 */
/**
 * @file iot_taskpool.c
 * @brief Implements the task pool functions in iot_taskpool.h
 */

/* The config header is always included first. */
#include "iot_config.h"

/* Standard includes. */
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>

/* Platform layer includes. */
#include "platform/iot_threads.h"
#include "platform/iot_clock.h"

/* Task pool internal include. */
#include "private/iot_taskpool_internal.h"

/**
 * @brief Maximum semaphore value for wait operations.
 */
#define TASKPOOL_MAX_SEM_VALUE              0xFFFF

/**
 * @brief Reschedule delay in milliseconds for deferred jobs.
 */
#define TASKPOOL_JOB_RESCHEDULE_DELAY_MS    ( 10ULL )

/* ---------------------------------------------------------------------------------- */

/**
 * Doxygen should ignore this section.
 *
 * @brief The system task pool handle for all libraries to use.
 * User application can use the system task pool as well knowing that the usage will be shared with
 * the system libraries as well. The system task pool needs to be initialized before any library is used or
 * before any code that posts jobs to the task pool runs.
 */
_taskPool_t _IotSystemTaskPool = { .dispatchQueue = IOT_DEQUEUE_INITIALIZER };

/* -------------- Convenience functions to create/recycle/destroy jobs -------------- */

/**
 * @brief Initializes one instance of a Task pool cache.
 *
 * @param[in] pCache The pre-allocated instance of the cache to initialize.
 */
static void _initJobsCache( _taskPoolCache_t * const pCache );

/**
 * @brief Initialize a job.
 *
 * @param[in] pJob The job to initialize.
 * @param[in] userCallback The user callback for the job.
 * @param[in] pUserContext The context tp be passed to the callback.
 * @param[in] isStatic A flag to indicate whether the job is statically or synamically allocated.
 */
static void _initializeJob( _taskPoolJob_t * const pJob,
                            IotTaskPoolRoutine_t userCallback,
                            void * pUserContext,
                            bool isStatic );

/**
 * @brief Extracts and initializes one instance of a job from the cache or, if there is none available, it allocates and initialized a new one.
 *
 * @param[in] pCache The instance of the cache to extract the job from.
 */
static _taskPoolJob_t * _fetchOrAllocateJob( _taskPoolCache_t * const pCache );

/**
 * Recycles one instance of a job into the cache or, if the cache is full, it destroys it.
 *
 * @param[in] pCache The instance of the cache to recycle the job into.
 * @param[in] pJob The job to recycle.
 *
 */
static void _recycleJob( _taskPoolCache_t * const pCache,
                         _taskPoolJob_t * const pJob );

/**
 * Destroys one instance of a job.
 *
 * @param[in] pJob The job to destroy.
 *
 */
static void _destroyJob( _taskPoolJob_t * const pJob );

/* -------------- The worker thread procedure for a task pool thread -------------- */

/**
 * The procedure for a task pool worker thread.
 *
 * @param[in] pUserContext The user context.
 *
 */
static void _taskPoolWorker( void * pUserContext );

/* -------------- Convenience functions to handle timer events  -------------- */

/**
 * Comparer for the time list.
 *
 * param[in] pTimerEventLink1 The link to the first timer event.
 * param[in] pTimerEventLink1 The link to the first timer event.
 */
static int32_t _timerEventCompare( const IotLink_t * const pTimerEventLink1,
                                   const IotLink_t * const pTimerEventLink2 );

/**
 * Reschedules the timer for handling deferred jobs to the next timeout.
 *
 * param[in] timer The timer to reschedule.
 * param[in] pFirstTimerEvent The timer event that carries the timeout and job inforamtion.
 */
static void _rescheduleDeferredJobsTimer( TimerHandle_t const timer,
                                          _taskPoolTimerEvent_t * const pFirstTimerEvent );

/**
 * The task pool timer procedure for scheduling deferred jobs.
 *
 * param[in] timer The timer to handle.
 */
static void _timerCallback( TimerHandle_t xTimer );

/* -------------- Convenience functions to create/initialize/destroy the task pool -------------- */

/**
 * Parameter validation for a task pool initialization.
 *
 * @param[in] pInfo The initialization information for the task pool.
 *
 */
static IotTaskPoolError_t _performTaskPoolParameterValidation( const IotTaskPoolInfo_t * const pInfo );

/**
 * Initializes a pre-allocated instance of a task pool.
 *
 * @param[in] pInfo The initialization information for the task pool.
 * @param[in] pTaskPool The pre-allocated instance of the task pool to initialize.
 *
 */
static IotTaskPoolError_t _initTaskPoolControlStructures( const IotTaskPoolInfo_t * const pInfo,
                                                          _taskPool_t * const pTaskPool );

/**
 * Initializes a pre-allocated instance of a task pool.
 *
 * @param[in] pInfo The initialization information for the task pool.
 * @param[out] pTaskPool A pointer to the task pool data structure to initialize.
 *
 */
static IotTaskPoolError_t _createTaskPool( const IotTaskPoolInfo_t * const pInfo,
                                           _taskPool_t * const pTaskPool );

/**
 * Destroys one instance of a task pool.
 *
 * @param[in] pTaskPool The task pool to destroy.
 *
 */
static void _destroyTaskPool( _taskPool_t * const pTaskPool );

/**
 * Check for the exit condition.
 *
 * @param[in] pTaskPool The task pool to destroy.
 *
 */
static bool _IsShutdownStarted( const _taskPool_t * const pTaskPool );

/**
 * Set the exit condition.
 *
 * @param[in] pTaskPool The task pool to destroy.
 * @param[in] threads The number of threads active in the task pool at shutdown time.
 *
 */
static void _signalShutdown( _taskPool_t * const pTaskPool,
                             uint32_t threads );

/**
 * Places a job in the dispatch queue.
 *
 * @param[in] pTaskPool The task pool to scheduel the job with.
 * @param[in] pJob The job to schedule.
 * @param[in] flags The job flags.
 *
 */
static IotTaskPoolError_t _scheduleInternal( _taskPool_t * const pTaskPool,
                                             _taskPoolJob_t * const pJob );

/**
 * Matches a deferred job in the timer queue with its timer event wrapper.
 *
 * @param[in] pLink A pointer to the timer event link in the timer queue.
 * @param[in] pMatch A pointer to the job to match.
 *
 */
static bool _matchJobByPointer( const IotLink_t * const pLink,
                                void * pMatch );

/**
 * Tries to cancel a job.
 *
 * @param[in] pTaskPool The task pool to cancel an operation against.
 * @param[in] pJob The job to cancel.
 * @param[out] pStatus The status of the job at the time of cancellation.
 *
 */
static IotTaskPoolError_t _tryCancelInternal( _taskPool_t * const pTaskPool,
                                              _taskPoolJob_t * const pJob,
                                              IotTaskPoolJobStatus_t * const pStatus );

/* ---------------------------------------------------------------------------------------------- */

IotTaskPool_t IotTaskPool_GetSystemTaskPool( void )
{
    return &_IotSystemTaskPool;
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_CreateSystemTaskPool( const IotTaskPoolInfo_t * const pInfo )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    /* At this time the task pool cannot be created before the scheduler has
    started because the function attempts to block on synchronization
    primitives (although I'm not sure why). */
    configASSERT( xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED );

    /* Guard against multiple attempts to create the system task pool in case
    this function is called by more than one library initialization routine. */
    if( _IotSystemTaskPool.running == false )
    {
        /* Parameter checking. */
        TASKPOOL_ON_ERROR_GOTO_CLEANUP( _performTaskPoolParameterValidation( pInfo ) );

        /* Create the system task pool pool. */
        TASKPOOL_SET_AND_GOTO_CLEANUP( _createTaskPool( pInfo, &_IotSystemTaskPool ) );
    }

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_Create( const IotTaskPoolInfo_t * const pInfo,
                                       IotTaskPool_t * const pTaskPool )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    _taskPool_t * pTempTaskPool = NULL;

    /* Verify that the task pool storage is valid. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( pTaskPool );

    /* Parameter checking. */
    TASKPOOL_ON_ERROR_GOTO_CLEANUP( _performTaskPoolParameterValidation( pInfo ) );

    /* Allocate the memory for the task pool */
    pTempTaskPool = ( _taskPool_t * ) IotTaskPool_MallocTaskPool( sizeof( _taskPool_t ) );

    if( pTempTaskPool == NULL )
    {
        TASKPOOL_SET_AND_GOTO_CLEANUP( IOT_TASKPOOL_NO_MEMORY );
    }

    memset( pTempTaskPool, 0x00, sizeof( _taskPool_t ) );

    TASKPOOL_SET_AND_GOTO_CLEANUP( _createTaskPool( pInfo, pTempTaskPool ) );

    TASKPOOL_FUNCTION_CLEANUP();

    if( TASKPOOL_FAILED( status ) )
    {
        if( pTempTaskPool != NULL )
        {
            IotTaskPool_FreeTaskPool( pTempTaskPool );
        }
    }
    else
    {
        *pTaskPool = pTempTaskPool;
    }

    TASKPOOL_FUNCTION_CLEANUP_END();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_Destroy( IotTaskPool_t taskPoolHandle )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    uint32_t count;
    bool completeShutdown = true;

    _taskPool_t * pTaskPool = ( _taskPool_t * ) taskPoolHandle;

    /* Track how many threads the task pool owns. */
    uint32_t activeThreads;

    /* Parameter checking. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( pTaskPool );

    /* Destroying the task pool should be safe, and therefore we will grab the task pool lock.
     * No worker thread or application thread should access any data structure
     * in the task pool while the task pool is being destroyed. */
    taskENTER_CRITICAL();
    {
        IotLink_t * pItemLink;

        /* Record how many active threads in the task pool. */
        activeThreads = pTaskPool->activeThreads;

        /* Destroying a Task pool happens in six (6) stages: First, (1) we clear the job queue and (2) the timer queue.
         * Then (3) we clear the jobs cache. We will then (4) wait for all worker threads to signal exit,
         * before (5) setting the exit condition and wake up all active worker threads. Finally (6) destroying
         * all task pool data structures and release the associated memory.
         */

        /* (1) Clear the job queue. */
        do
        {
            pItemLink = NULL;

            pItemLink = IotDeQueue_DequeueHead( &pTaskPool->dispatchQueue );

            if( pItemLink != NULL )
            {
                _taskPoolJob_t * pJob = IotLink_Container( _taskPoolJob_t, pItemLink, link );

                _destroyJob( pJob );
            }
        } while( pItemLink );

        /* (2) Clear the timer queue. */
        {
            _taskPoolTimerEvent_t * pTimerEvent;

            /* A deferred job may have fired already. Since deferred jobs will go through the same mutex
             * the shutdown sequence is holding at this stage, there is no risk for race conditions. Yet, we
             * need to let the deferred job to destroy the task pool. */

            pItemLink = IotListDouble_PeekHead( &pTaskPool->timerEventsList );

            if( pItemLink != NULL )
            {
                TickType_t now = xTaskGetTickCount();

                pTimerEvent = IotLink_Container( _taskPoolTimerEvent_t, pItemLink, link );

                if( pTimerEvent->expirationTime <= now )
                {
                    IotLogDebug( "Shutdown will be deferred to the timer thread" );

                    /* Timer may have fired already! Let the timer thread destroy
                     * complete the taskpool destruction sequence. */
                    completeShutdown = false;
                }

                /* Remove all timers from the timeout list. */
                for( ; ; )
                {
                    pItemLink = IotListDouble_RemoveHead( &pTaskPool->timerEventsList );

                    if( pItemLink == NULL )
                    {
                        break;
                    }

                    pTimerEvent = IotLink_Container( _taskPoolTimerEvent_t, pItemLink, link );

                    _destroyJob( pTimerEvent->job );

                    IotTaskPool_FreeTimerEvent( pTimerEvent );
                }
            }
        }

        /* (3) Clear the job cache. */
        do
        {
            pItemLink = NULL;

            pItemLink = IotListDouble_RemoveHead( &pTaskPool->jobsCache.freeList );

            if( pItemLink != NULL )
            {
                _taskPoolJob_t * pJob = IotLink_Container( _taskPoolJob_t, pItemLink, link );

                _destroyJob( pJob );
            }
        } while( pItemLink );

        /* (4) Set the exit condition. */
        _signalShutdown( pTaskPool, activeThreads );
    }
    taskEXIT_CRITICAL();

    /* (5) Wait for all active threads to reach the end of their life-span. */
    for( count = 0; count < activeThreads; ++count )
    {
        xSemaphoreTake( pTaskPool->startStopSignal, portMAX_DELAY );
    }

    IotTaskPool_Assert( uxSemaphoreGetCount( pTaskPool->startStopSignal ) == 0 );
    IotTaskPool_Assert( pTaskPool->activeThreads == 0 );

    /* (6) Destroy all signaling objects. */
    if( completeShutdown == true )
    {
        _destroyTaskPool( pTaskPool );

        /* Do not free the system task pool which is statically allocated. */
        if( pTaskPool != &_IotSystemTaskPool )
        {
            IotTaskPool_FreeTaskPool( pTaskPool );
        }
    }

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_SetMaxThreads( IotTaskPool_t taskPoolHandle,
                                              uint32_t maxThreads )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    _taskPool_t * pTaskPool = ( _taskPool_t * ) taskPoolHandle;

    /* Parameter checking. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( pTaskPool );
    TASKPOOL_ON_ARG_ERROR_GOTO_CLEANUP( maxThreads < 1UL );

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_CreateJob( IotTaskPoolRoutine_t userCallback,
                                          void * pUserContext,
                                          IotTaskPoolJobStorage_t * const pJobStorage,
                                          IotTaskPoolJob_t * const ppJob )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    /* Parameter checking. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( userCallback );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( pJobStorage );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( ppJob );

    /* Build a job around the user-provided storage. */
    _initializeJob( ( _taskPoolJob_t * ) pJobStorage, userCallback, pUserContext, true );

    *ppJob = ( IotTaskPoolJob_t ) pJobStorage;

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_CreateRecyclableSystemJob( IotTaskPoolRoutine_t userCallback,
                                                          void * pUserContext,
                                                          IotTaskPoolJob_t * const pJob )
{
    return IotTaskPool_CreateRecyclableJob ( &_IotSystemTaskPool, userCallback, pUserContext, pJob );
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_CreateRecyclableJob( IotTaskPool_t taskPoolHandle,
                                                    IotTaskPoolRoutine_t userCallback,
                                                    void * pUserContext,
                                                    IotTaskPoolJob_t * const ppJob )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    _taskPool_t * pTaskPool = ( _taskPool_t * ) taskPoolHandle;
    _taskPoolJob_t * pTempJob = NULL;

    /* Parameter checking. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( taskPoolHandle );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( userCallback );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( ppJob );

    taskENTER_CRITICAL();
    {
        /* Bail out early if this task pool is shutting down. */
        pTempJob = _fetchOrAllocateJob( &pTaskPool->jobsCache );
    }
    taskEXIT_CRITICAL();

    if( pTempJob == NULL )
    {
        IotLogInfo( "Failed to allocate a job." );

        TASKPOOL_SET_AND_GOTO_CLEANUP( IOT_TASKPOOL_NO_MEMORY );
    }

    _initializeJob( pTempJob, userCallback, pUserContext, false );

    *ppJob = pTempJob;

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_DestroyRecyclableJob( IotTaskPool_t taskPoolHandle,
                                                     IotTaskPoolJob_t pJobHandle )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    ( void ) taskPoolHandle;

    _taskPoolJob_t * pJob = ( _taskPoolJob_t * ) pJobHandle;

    /* Parameter checking. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( taskPoolHandle );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( pJobHandle );

    IotTaskPool_Assert( IotLink_IsLinked( &pJob->link ) == false );

    _destroyJob( pJob );

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_RecycleJob( IotTaskPool_t taskPoolHandle,
                                           IotTaskPoolJob_t pJob )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    _taskPool_t * pTaskPool = ( _taskPool_t * ) taskPoolHandle;

    /* Parameter checking. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( taskPoolHandle );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( pJob );

    taskENTER_CRITICAL();
    {
        IotTaskPool_Assert( IotLink_IsLinked( &pJob->link ) == false );

        _recycleJob( &pTaskPool->jobsCache, pJob );
    }
    taskEXIT_CRITICAL();

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_Schedule( IotTaskPool_t taskPoolHandle,
                                         IotTaskPoolJob_t pJob,
                                         uint32_t flags )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    _taskPool_t * pTaskPool = ( _taskPool_t * ) taskPoolHandle;

    configASSERT( pTaskPool->running != false );

    /* Parameter checking. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( taskPoolHandle );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( pJob );
    TASKPOOL_ON_ARG_ERROR_GOTO_CLEANUP( ( flags != 0UL ) && ( flags != IOT_TASKPOOL_JOB_HIGH_PRIORITY ) );

    taskENTER_CRITICAL(); //_RB_ Critical section is too long - does the whole thing need to be protected?
    {
        _scheduleInternal( pTaskPool, pJob );
    }
    taskEXIT_CRITICAL();

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_ScheduleSystemJob( IotTaskPoolJob_t pJob,
                                                  uint32_t flags )
{
    return IotTaskPool_Schedule( &_IotSystemTaskPool, pJob, flags );
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_ScheduleDeferred( IotTaskPool_t taskPoolHandle,
                                                 IotTaskPoolJob_t job,
                                                 uint32_t timeMs )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    _taskPool_t * pTaskPool = ( _taskPool_t * ) taskPoolHandle;

    /* Parameter checking. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( taskPoolHandle );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( job );

    if( timeMs == 0UL )
    {
        TASKPOOL_SET_AND_GOTO_CLEANUP( IotTaskPool_Schedule( pTaskPool, job, 0 ) );
    }

    taskENTER_CRITICAL();
    {
        _taskPoolTimerEvent_t * pTimerEvent = IotTaskPool_MallocTimerEvent( sizeof( _taskPoolTimerEvent_t ) );

        if( pTimerEvent == NULL )
        {
            taskEXIT_CRITICAL();

            TASKPOOL_SET_AND_GOTO_CLEANUP( IOT_TASKPOOL_NO_MEMORY );
        }

        IotLink_t * pTimerEventLink;

        TickType_t now = xTaskGetTickCount();

        pTimerEvent->link.pNext = NULL;
        pTimerEvent->link.pPrevious = NULL;
        pTimerEvent->expirationTime = now + pdMS_TO_TICKS( timeMs );
        pTimerEvent->job = job;

        /* Append the timer event to the timer list. */
        IotListDouble_InsertSorted( &pTaskPool->timerEventsList, &pTimerEvent->link, _timerEventCompare );

        /* Update the job status to 'scheduled'. */
        job->status = IOT_TASKPOOL_STATUS_DEFERRED;

        /* Peek the first event in the timer event list. There must be at least one,
         * since we just inserted it. */
        pTimerEventLink = IotListDouble_PeekHead( &pTaskPool->timerEventsList );
        IotTaskPool_Assert( pTimerEventLink != NULL );

        /* If the event we inserted is at the front of the queue, then
         * we need to reschedule the underlying timer. */
        if( pTimerEventLink == &pTimerEvent->link )
        {
            pTimerEvent = IotLink_Container( _taskPoolTimerEvent_t, pTimerEventLink, link );

            _rescheduleDeferredJobsTimer( pTaskPool->timer, pTimerEvent );
        }
    }
    taskEXIT_CRITICAL();

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_GetStatus( IotTaskPool_t taskPoolHandle,
                                          IotTaskPoolJob_t job,
                                          IotTaskPoolJobStatus_t * const pStatus )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    /* Parameter checking. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( taskPoolHandle );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( job );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( pStatus );
    *pStatus = IOT_TASKPOOL_STATUS_UNDEFINED;

    taskENTER_CRITICAL();
    {
        *pStatus = job->status;
    }
    taskEXIT_CRITICAL();

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolError_t IotTaskPool_TryCancel( IotTaskPool_t taskPoolHandle,
                                          IotTaskPoolJob_t job,
                                          IotTaskPoolJobStatus_t * const pStatus )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    _taskPool_t * pTaskPool = ( _taskPool_t * ) taskPoolHandle;

    /* Parameter checking. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( taskPoolHandle );
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( job );

    if( pStatus != NULL )
    {
        *pStatus = IOT_TASKPOOL_STATUS_UNDEFINED;
    }

    taskENTER_CRITICAL();
    {
        status = _tryCancelInternal( pTaskPool, job, pStatus );
    }
    taskEXIT_CRITICAL();

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

IotTaskPoolJobStorage_t * IotTaskPool_GetJobStorageFromHandle( IotTaskPoolJob_t pJob )
{
    return ( IotTaskPoolJobStorage_t * ) pJob;
}

/*-----------------------------------------------------------*/

const char * IotTaskPool_strerror( IotTaskPoolError_t status )
{
    const char * pMessage = NULL;

    switch( status )
    {
        case IOT_TASKPOOL_SUCCESS:
            pMessage = "SUCCESS";
            break;

        case IOT_TASKPOOL_BAD_PARAMETER:
            pMessage = "BAD PARAMETER";
            break;

        case IOT_TASKPOOL_ILLEGAL_OPERATION:
            pMessage = "ILLEGAL OPERATION";
            break;

        case IOT_TASKPOOL_NO_MEMORY:
            pMessage = "NO MEMORY";
            break;

        case IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS:
            pMessage = "SHUTDOWN IN PROGRESS";
            break;

        case IOT_TASKPOOL_CANCEL_FAILED:
            pMessage = "CANCEL FAILED";
            break;

        default:
            pMessage = "INVALID STATUS";
            break;
    }

    return pMessage;
}

/* ---------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------- */

static IotTaskPoolError_t _performTaskPoolParameterValidation( const IotTaskPoolInfo_t * const pInfo )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    /* Check input values for consistency. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( pInfo );
    TASKPOOL_ON_ARG_ERROR_GOTO_CLEANUP( pInfo->minThreads > pInfo->maxThreads );
    TASKPOOL_ON_ARG_ERROR_GOTO_CLEANUP( pInfo->minThreads < 1UL );
    TASKPOOL_ON_ARG_ERROR_GOTO_CLEANUP( pInfo->maxThreads < 1UL );

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

static IotTaskPoolError_t _initTaskPoolControlStructures( const IotTaskPoolInfo_t * const pInfo,
                                                          _taskPool_t * const pTaskPool )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    bool semStartStopInit = false;
    bool semDispatchInit = false;

    /* Initialize a job data structures that require no de-initialization.
     * All other data structures carry a value of 'NULL' before initailization.
     */
    IotDeQueue_Create( &pTaskPool->dispatchQueue );
    IotListDouble_Create( &pTaskPool->timerEventsList );

    _initJobsCache( &pTaskPool->jobsCache );

    /* Initialize the semaphore to ensure all threads have started. */
    pTaskPool->startStopSignal = xSemaphoreCreateCountingStatic( pInfo->minThreads, 0, &pTaskPool->startStopSignalBuffer );

    if( pTaskPool->startStopSignal != NULL )
    {
        semStartStopInit = true;

        /* Initialize the semaphore for waiting for incoming work. */
        pTaskPool->dispatchSignal = xSemaphoreCreateCountingStatic( TASKPOOL_MAX_SEM_VALUE, 0, &pTaskPool->dispatchSignalBuffer );

        if( pTaskPool->dispatchSignal != NULL )
        {
            semDispatchInit = true;
        }
        else
        {
            TASKPOOL_SET_AND_GOTO_CLEANUP( IOT_TASKPOOL_NO_MEMORY );
        }
    }
    else
    {
        TASKPOOL_SET_AND_GOTO_CLEANUP( IOT_TASKPOOL_NO_MEMORY );
    }

    TASKPOOL_FUNCTION_CLEANUP();

    if( TASKPOOL_FAILED( status ) )
    {
        if( semStartStopInit )
        {
            vSemaphoreDelete( &pTaskPool->startStopSignal );
        }

        if( semDispatchInit )
        {
            vSemaphoreDelete( &pTaskPool->dispatchSignal );
        }
    }

    TASKPOOL_FUNCTION_CLEANUP_END();
}

static IotTaskPoolError_t _createTaskPool( const IotTaskPoolInfo_t * const pInfo,
                                           _taskPool_t * const pTaskPool )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    uint32_t count;
    uint32_t threadsCreated;

    /* Check input values for consistency. */
    TASKPOOL_ON_NULL_ARG_GOTO_CLEANUP( pTaskPool );

    /* Zero out all data structures. */
    memset( ( void * ) pTaskPool, 0x00, sizeof( _taskPool_t ) );

    /* Initialize all internal data structure prior to creating all threads. */
    TASKPOOL_ON_ERROR_GOTO_CLEANUP( _initTaskPoolControlStructures( pInfo, pTaskPool ) );

    /* Create the timer for a new connection. */
    pTaskPool->timer = xTimerCreate( NULL, portMAX_DELAY, pdFALSE, ( void * ) pTaskPool, _timerCallback );

    if( pTaskPool->timer == NULL )
    {
        IotLogError( "Failed to create timer for task pool." );

        TASKPOOL_SET_AND_GOTO_CLEANUP( IOT_TASKPOOL_NO_MEMORY );
    }

    /* The task pool will initialize the minimum number of threads requested by the user upon start. */
    /* When a thread is created, it will signal a semaphore to signify that it is about to wait on incoming */
    /* jobs. A thread can be woken up for exit or for new jobs only at that point in time.  */
    /* The exit condition is setting the maximum number of threads to 0. */

    /* Create the minimum number of threads specified by the user, and if one fails shutdown and return error. */
    for( threadsCreated = 0; threadsCreated < pInfo->minThreads; )
    {
        TaskHandle_t task = NULL;

        BaseType_t res = xTaskCreate( _taskPoolWorker,
                                      NULL,
                                      pInfo->stackSize,
                                      pTaskPool,
                                      pInfo->priority,
                                      &task );

        /* Create one thread. */
        if( res == pdFALSE )
        {
            IotLogError( "Could not create worker thread! Exiting..." );

            /* If creating one thread fails, set error condition and exit the loop. */
            TASKPOOL_SET_AND_GOTO_CLEANUP( IOT_TASKPOOL_NO_MEMORY );
        }

        /* Upon successful thread creation, increase the number of active threads. */
        pTaskPool->activeThreads++;
        IotTaskPool_Assert( task != NULL );

        ++threadsCreated;
    }

    TASKPOOL_FUNCTION_CLEANUP();

    /* Wait for threads to be ready to wait on the condition, so that threads are actually able to receive messages. */
    for( count = 0; count < threadsCreated; ++count )
    {
        xSemaphoreTake( pTaskPool->startStopSignal, portMAX_DELAY ); /*_RB_ Is waiting necessary, and if so, is a semaphore necessary? */
    }

    /* In case of failure, wait on the created threads to exit. */
    if( TASKPOOL_FAILED( status ) )
    {
        /* Set the exit condition for the newly created threads. */
        _signalShutdown( pTaskPool, threadsCreated );

        /* Signal all threads to exit. */
        for( count = 0; count < threadsCreated; ++count )
        {
            xSemaphoreTake( pTaskPool->startStopSignal, portMAX_DELAY );
        }

        _destroyTaskPool( pTaskPool );
    }

    pTaskPool->running = true;

    TASKPOOL_FUNCTION_CLEANUP_END();
}

/*-----------------------------------------------------------*/

static void _destroyTaskPool( _taskPool_t * const pTaskPool )
{
    if( pTaskPool->timer != NULL )
    {
        xTimerDelete( pTaskPool->timer, 0 );
    }

    if( pTaskPool->dispatchSignal != NULL )
    {
        vSemaphoreDelete( pTaskPool->dispatchSignal );
    }

    if( pTaskPool->startStopSignal != NULL )
    {
        vSemaphoreDelete( pTaskPool->startStopSignal );
    }
}

/* ---------------------------------------------------------------------------------------------- */

static void _taskPoolWorker( void * pUserContext )
{
    IotTaskPool_Assert( pUserContext != NULL );

    IotTaskPoolRoutine_t userCallback = NULL;
    bool running = true;

    /* Extract pTaskPool pointer from context. */
    _taskPool_t * pTaskPool = ( _taskPool_t * ) pUserContext;

    /* Signal that this worker completed initialization and it is ready to receive notifications. */
    ( void ) xSemaphoreGive( pTaskPool->startStopSignal );

    /* OUTER LOOP: it controls the lifetiem of the worker thread: exit condition for a worker thread
     * is setting maxThreads to zero. A worker thread is running until the maximum number of allowed
     * threads is not zero and the active threads are less than the maximum number of allowed threads.
     */
    do
    {
        IotLink_t * pFirst = NULL;
        _taskPoolJob_t * pJob = NULL;

        /* Wait on incoming notifications... */
        xSemaphoreTake( pTaskPool->dispatchSignal, portMAX_DELAY );

        /* Acquire the lock to check the exit condition, and release the lock if the exit condition is verified,
         * or before waiting for incoming notifications.
         */
        taskENTER_CRITICAL();
        {
            /* If the exit condition is verified, update the number of active threads and exit the loop. */
            if( _IsShutdownStarted( pTaskPool ) )
            {
                IotLogDebug( "Worker thread exiting because exit condition was set." );

                /* Decrease the number of active threads. */
                pTaskPool->activeThreads--;

                taskEXIT_CRITICAL();

                /* Signal that this worker is exiting. */
                xSemaphoreGive( pTaskPool->startStopSignal );

                /* On shutdown, abandon the OUTER LOOP immediately. */
                break;
            }

            /* Dequeue the first job in FIFO order. */
            pFirst = IotDeQueue_DequeueHead( &pTaskPool->dispatchQueue );

            /* If there is indeed a job, then update status under lock, and release the lock before processing the job. */
            if( pFirst != NULL )
            {
                /* Extract the job from its link. */
                pJob = IotLink_Container( _taskPoolJob_t, pFirst, link );

                /* Update status to 'executing'. */
                pJob->status = IOT_TASKPOOL_STATUS_COMPLETED;
                userCallback = pJob->userCallback;
            }
        }
        taskEXIT_CRITICAL();

        /* INNER LOOP: it controls the execution of jobs: the exit condition is the lack of a job to execute. */
        while( pJob != NULL )
        {
            /* Process the job by invoking the associated callback with the user context.
             * This task pool thread will not be available until the user callback returns.
             */
            {
                IotTaskPool_Assert( IotLink_IsLinked( &pJob->link ) == false );
                IotTaskPool_Assert( userCallback != NULL );

                userCallback( pTaskPool, pJob, pJob->pUserContext );

                /* This job is finished, clear its pointer. */
                pJob = NULL;
                userCallback = NULL;

                /* If this thread exceeded the quota, then let it terminate. */
                if( running == false )
                {
                    /* Abandon the INNER LOOP. Execution will tranfer back to the OUTER LOOP condition. */
                    break;
                }
            }

            /* Acquire the lock before updating the job status. */
            taskENTER_CRITICAL();
            {
                /* Try and dequeue the next job in the dispatch queue. */
                IotLink_t * pItem = NULL;

                /* Dequeue the next job from the dispatch queue. */
                pItem = IotDeQueue_DequeueHead( &pTaskPool->dispatchQueue );

                /* If there is no job left in the dispatch queue, update the worker status and leave. */
                if( pItem == NULL )
                {
                    taskEXIT_CRITICAL();

                    /* Abandon the INNER LOOP. Execution will tranfer back to the OUTER LOOP condition. */
                    break;
                }
                else
                {
                    pJob = IotLink_Container( _taskPoolJob_t, pItem, link );

                    userCallback = pJob->userCallback;
                }

                pJob->status = IOT_TASKPOOL_STATUS_COMPLETED;
            }
            taskEXIT_CRITICAL();
        }
    } while( running == true );

    vTaskDelete( NULL );
}

/* ---------------------------------------------------------------------------------------------- */

static void _initJobsCache( _taskPoolCache_t * const pCache )
{
    IotDeQueue_Create( &pCache->freeList );

    pCache->freeCount = 0;
}

/*-----------------------------------------------------------*/

static void _initializeJob( _taskPoolJob_t * const pJob,
                            IotTaskPoolRoutine_t userCallback,
                            void * pUserContext,
                            bool isStatic )
{
    pJob->link.pNext = NULL;
    pJob->link.pPrevious = NULL;
    pJob->userCallback = userCallback;
    pJob->pUserContext = pUserContext;

    if( isStatic )
    {
        pJob->flags = IOT_TASK_POOL_INTERNAL_STATIC;
        pJob->status = IOT_TASKPOOL_STATUS_READY;
    }
    else
    {
        pJob->status = IOT_TASKPOOL_STATUS_READY;
    }
}

static _taskPoolJob_t * _fetchOrAllocateJob( _taskPoolCache_t * const pCache )
{
    _taskPoolJob_t * pJob = NULL;
    IotLink_t * pLink = IotListDouble_RemoveHead( &( pCache->freeList ) );

    if( pLink != NULL )
    {
        pJob = IotLink_Container( _taskPoolJob_t, pLink, link );
    }

    /* If there is no available job in the cache, then allocate one. */
    if( pJob == NULL )
    {
        pJob = ( _taskPoolJob_t * ) IotTaskPool_MallocJob( sizeof( _taskPoolJob_t ) );

        if( pJob != NULL )
        {
            memset( pJob, 0x00, sizeof( _taskPoolJob_t ) );
        }
        else
        {
            /* Log alocation failure for troubleshooting purposes. */
            IotLogInfo( "Failed to allocate job." );
        }
    }
    /* If there was a job in the cache, then make sure we keep the counters up-to-date. */
    else
    {
        IotTaskPool_Assert( pCache->freeCount > 0 );

        pCache->freeCount--;
    }

    return pJob;
}

/*-----------------------------------------------------------*/

static void _recycleJob( _taskPoolCache_t * const pCache,
                         _taskPoolJob_t * const pJob )
{
    /* We should never try and recycling a job that is linked into some queue. */
    IotTaskPool_Assert( IotLink_IsLinked( &pJob->link ) == false );

    /* We will recycle the job if there is space in the cache. */
    if( pCache->freeCount < IOT_TASKPOOL_JOBS_RECYCLE_LIMIT )
    {
        /* Destroy user data, for added safety&security. */
        pJob->userCallback = NULL;
        pJob->pUserContext = NULL;

        /* Reset the status for added debuggability. */
        pJob->status = IOT_TASKPOOL_STATUS_UNDEFINED;

        IotListDouble_InsertTail( &pCache->freeList, &pJob->link );

        pCache->freeCount++;

        IotTaskPool_Assert( pCache->freeCount >= 1 );
    }
    else
    {
        _destroyJob( pJob );
    }
}

/*-----------------------------------------------------------*/

static void _destroyJob( _taskPoolJob_t * const pJob )
{
    /* Destroy user data, for added safety & security. */
    pJob->userCallback = NULL;
    pJob->pUserContext = NULL;

    /* Reset the status for added debuggability. */
    pJob->status = IOT_TASKPOOL_STATUS_UNDEFINED;

    /* Only dispose of dynamically allocated jobs. */
    if( ( pJob->flags & IOT_TASK_POOL_INTERNAL_STATIC ) == 0UL )
    {
        IotTaskPool_FreeJob( pJob );
    }
}

/* ---------------------------------------------------------------------------------------------- */

static bool _IsShutdownStarted( const _taskPool_t * const pTaskPool )
{
    return( pTaskPool->running == false );
}

/*-----------------------------------------------------------*/

static void _signalShutdown( _taskPool_t * const pTaskPool,
                             uint32_t threads )
{
    uint32_t count;

    /* Set the exit condition. */
    pTaskPool->running = false;

    /* Broadcast to all active threads to wake-up. Active threads do check the exit condition right after wakein up. */
    for( count = 0; count < threads; ++count )
    {
        ( void ) xSemaphoreGive( pTaskPool->dispatchSignal );
    }
}

/* ---------------------------------------------------------------------------------------------- */

static IotTaskPoolError_t _scheduleInternal( _taskPool_t * const pTaskPool,
                                             _taskPoolJob_t * const pJob )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    /* Update the job status to 'scheduled'. */
    pJob->status = IOT_TASKPOOL_STATUS_SCHEDULED;

    BaseType_t higherPriorityTaskWoken;

    /* Append the job to the dispatch queue. */
    IotDeQueue_EnqueueTail( &pTaskPool->dispatchQueue, &pJob->link );

    /* Signal a worker to pick up the job. */
    ( void ) xSemaphoreGiveFromISR( pTaskPool->dispatchSignal, &higherPriorityTaskWoken );

    portYIELD_FROM_ISR( higherPriorityTaskWoken );

    TASKPOOL_NO_FUNCTION_CLEANUP_NOLABEL();
}

/*-----------------------------------------------------------*/

static bool _matchJobByPointer( const IotLink_t * const pLink,
                                void * pMatch )
{
    const _taskPoolJob_t * const pJob = ( _taskPoolJob_t * ) pMatch;

    const _taskPoolTimerEvent_t * const pTimerEvent = IotLink_Container( _taskPoolTimerEvent_t, pLink, link );

    if( pJob == pTimerEvent->job )
    {
        return true;
    }

    return false;
}

/*-----------------------------------------------------------*/

static IotTaskPoolError_t _tryCancelInternal( _taskPool_t * const pTaskPool,
                                              _taskPoolJob_t * const pJob,
                                              IotTaskPoolJobStatus_t * const pStatus )
{
    TASKPOOL_FUNCTION_ENTRY( IOT_TASKPOOL_SUCCESS );

    bool cancelable = false;

    /* We can only cancel jobs that are either 'ready' (waiting to be scheduled). 'deferred', or 'scheduled'. */

    IotTaskPoolJobStatus_t currentStatus = pJob->status;

    switch( currentStatus )
    {
        case IOT_TASKPOOL_STATUS_READY:
        case IOT_TASKPOOL_STATUS_DEFERRED:
        case IOT_TASKPOOL_STATUS_SCHEDULED:
        case IOT_TASKPOOL_STATUS_CANCELED:
            cancelable = true;
            break;

        case IOT_TASKPOOL_STATUS_COMPLETED:
            /* Log mesggesong purposes. */
            IotLogWarn( "Attempt to cancel a job that is already executing, or canceled." );
            break;

        default:
            /* Log mesggesong purposes. */
            IotLogError( "Attempt to cancel a job with an undefined state." );
            break;
    }

    /* Update the returned status to the current status of the job. */
    if( pStatus != NULL )
    {
        *pStatus = currentStatus;
    }

    if( cancelable == false )
    {
        TASKPOOL_SET_AND_GOTO_CLEANUP( IOT_TASKPOOL_CANCEL_FAILED );
    }
    else
    {
        /* Update the status of the job. */
        pJob->status = IOT_TASKPOOL_STATUS_CANCELED;

        /* If the job is cancelable and its current status is 'scheduled' then unlink it from the dispatch
         * queue and signal any waiting threads. */
        if( currentStatus == IOT_TASKPOOL_STATUS_SCHEDULED )
        {
            /* A scheduled work items must be in the dispatch queue. */
            IotTaskPool_Assert( IotLink_IsLinked( &pJob->link ) );

            IotDeQueue_Remove( &pJob->link );
        }

        /* If the job current status is 'deferred' then the job has to be pending
         * in the timeouts queue. */
        else if( currentStatus == IOT_TASKPOOL_STATUS_DEFERRED )
        {
            /* Find the timer event associated with the current job. There MUST be one, hence assert if not. */
            IotLink_t * pTimerEventLink = IotListDouble_FindFirstMatch( &pTaskPool->timerEventsList, NULL, _matchJobByPointer, pJob );
            IotTaskPool_Assert( pTimerEventLink != NULL );

            if( pTimerEventLink != NULL )
            {
                bool shouldReschedule = false;

                /* If the job being cancelled was at the head of the timeouts queue, then we need to reschedule the timer
                 * with the next job timeout */
                IotLink_t * pHeadLink = IotListDouble_PeekHead( &pTaskPool->timerEventsList );

                if( pHeadLink == pTimerEventLink )
                {
                    shouldReschedule = true;
                }

                /* Remove the timer event associated with the canceled job and free the associated memory. */
                IotListDouble_Remove( pTimerEventLink );
                IotTaskPool_FreeTimerEvent( IotLink_Container( _taskPoolTimerEvent_t, pTimerEventLink, link ) );

                if( shouldReschedule )
                {
                    IotLink_t * pNextTimerEventLink = IotListDouble_PeekHead( &pTaskPool->timerEventsList );

                    if( pNextTimerEventLink != NULL )
                    {
                        _rescheduleDeferredJobsTimer( pTaskPool->timer, IotLink_Container( _taskPoolTimerEvent_t, pNextTimerEventLink, link ) );
                    }
                }
            }
        }
        else
        {
            /* A cancelable job status should be either 'scheduled' or 'deferrred'. */
            IotTaskPool_Assert( ( currentStatus == IOT_TASKPOOL_STATUS_READY ) || ( currentStatus == IOT_TASKPOOL_STATUS_CANCELED ) );
        }
    }

    TASKPOOL_NO_FUNCTION_CLEANUP();
}

/*-----------------------------------------------------------*/

static int32_t _timerEventCompare( const IotLink_t * const pTimerEventLink1,
                                   const IotLink_t * const pTimerEventLink2 )
{
    const _taskPoolTimerEvent_t * const pTimerEvent1 = IotLink_Container( _taskPoolTimerEvent_t,
                                                                          pTimerEventLink1,
                                                                          link );
    const _taskPoolTimerEvent_t * const pTimerEvent2 = IotLink_Container( _taskPoolTimerEvent_t,
                                                                          pTimerEventLink2,
                                                                          link );

    if( pTimerEvent1->expirationTime < pTimerEvent2->expirationTime )
    {
        return -1;
    }

    if( pTimerEvent1->expirationTime > pTimerEvent2->expirationTime )
    {
        return 1;
    }

    return 0;
}

/*-----------------------------------------------------------*/

static void _rescheduleDeferredJobsTimer( TimerHandle_t const timer,
                                          _taskPoolTimerEvent_t * const pFirstTimerEvent )
{
    uint64_t delta = 0;
    TickType_t now = xTaskGetTickCount();

    if( pFirstTimerEvent->expirationTime > now )
    {
        delta = pFirstTimerEvent->expirationTime - now;
    }

    if( delta < TASKPOOL_JOB_RESCHEDULE_DELAY_MS )
    {
        delta = TASKPOOL_JOB_RESCHEDULE_DELAY_MS; /* The job will be late... */
    }

    IotTaskPool_Assert( delta > 0 );

    if( xTimerChangePeriod( timer, ( uint32_t ) delta, portMAX_DELAY ) == pdFAIL )
    {
        IotLogWarn( "Failed to re-arm timer for task pool" );
    }
}

/*-----------------------------------------------------------*/

static void _timerCallback( TimerHandle_t xTimer )
{
    _taskPool_t * pTaskPool = pvTimerGetTimerID( xTimer );

    IotTaskPool_Assert( pTaskPool );

    _taskPoolTimerEvent_t * pTimerEvent = NULL;

    IotLogDebug( "Timer thread started for task pool %p.", pTaskPool );

    /* Attempt to lock the timer mutex. Return immediately if the mutex cannot be locked.
     * If this mutex cannot be locked it means that another thread is manipulating the
     * timeouts list, and will reset the timer to fire again, although it will be late.
     */
    taskENTER_CRITICAL();
    {
        /* Check again for shutdown and bail out early in case. */
        if( _IsShutdownStarted( pTaskPool ) )
        {
            taskEXIT_CRITICAL();

            /* Complete the shutdown sequence. */
            _destroyTaskPool( pTaskPool );

            return;
        }

        /* Dispatch all deferred job whose timer expired, then reset the timer for the next
         * job down the line. */
        for( ; ; )
        {
            /* Peek the first event in the timer event list. */
            IotLink_t * pLink = IotListDouble_PeekHead( &pTaskPool->timerEventsList );

            /* Check if the timer misfired for any reason.  */
            if( pLink != NULL )
            {
                /* Record the current time. */
                TickType_t now = xTaskGetTickCount();

                /* Extract the job from its envelope. */
                pTimerEvent = IotLink_Container( _taskPoolTimerEvent_t, pLink, link );

                /* Check if the first event should be processed now. */
                if( pTimerEvent->expirationTime <= now )
                {
                    /*  Remove the timer event for immediate processing. */
                    IotListDouble_Remove( &( pTimerEvent->link ) );
                }
                else
                {
                    /* The first element in the timer queue shouldn't be processed yet.
                     * Arm the timer for when it should be processed and leave altogether. */
                    _rescheduleDeferredJobsTimer( pTaskPool->timer, pTimerEvent );

                    break;
                }
            }
            /* If there are no timer events to process, terminate this thread. */
            else
            {
                IotLogDebug( "No further timer events to process. Exiting timer thread." );

                break;
            }

            IotLogDebug( "Scheduling job from timer event." );

            /* Queue the job associated with the received timer event. */
            ( void ) _scheduleInternal( pTaskPool, pTimerEvent->job );

            /* Free the timer event. */
            IotTaskPool_FreeTimerEvent( pTimerEvent );
        }
    }
    taskEXIT_CRITICAL();
}