tasks.c 182 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849
  1. /*
  2. * FreeRTOS Kernel V10.5.1
  3. * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * SPDX-License-Identifier: MIT
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. * this software and associated documentation files (the "Software"), to deal in
  9. * the Software without restriction, including without limitation the rights to
  10. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. * the Software, and to permit persons to whom the Software is furnished to do so,
  12. * subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all
  15. * copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. *
  24. * https://www.FreeRTOS.org
  25. * https://github.com/FreeRTOS
  26. *
  27. */
  28. /* Standard includes. */
  29. #include <stdlib.h>
  30. #include <string.h>
  31. /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
  32. * all the API functions to use the MPU wrappers. That should only be done when
  33. * task.h is included from an application file. */
  34. #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  35. /* FreeRTOS includes. */
  36. #include "FreeRTOS.h"
  37. #include "task.h"
  38. #include "timers.h"
  39. #include "stack_macros.h"
  40. /* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified
  41. * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined
  42. * for the header files above, but not in this file, in order to generate the
  43. * correct privileged Vs unprivileged linkage and placement. */
  44. #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */
  45. /* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting
  46. * functions but without including stdio.h here. */
  47. #if (configUSE_STATS_FORMATTING_FUNCTIONS == 1)
  48. /* At the bottom of this file are two optional functions that can be used
  49. * to generate human readable text from the raw data generated by the
  50. * uxTaskGetSystemState() function. Note the formatting functions are provided
  51. * for convenience only, and are NOT considered part of the kernel. */
  52. #include <stdio.h>
  53. #endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1) */
  54. #if (configUSE_PREEMPTION == 0)
  55. /* If the cooperative scheduler is being used then a yield should not be
  56. * performed just because a higher priority task has been woken. */
  57. #define taskYIELD_IF_USING_PREEMPTION()
  58. #else
  59. #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API()
  60. #endif
  61. /**
  62. * Values that can be assigned to the ucNotifyState member of the TCB.
  63. * 接收任务通知状态机
  64. */
  65. #define taskNOT_WAITING_NOTIFICATION ((uint8_t)0)
  66. #define taskWAITING_NOTIFICATION ((uint8_t)1)
  67. #define taskNOTIFICATION_RECEIVED ((uint8_t)2)
  68. /*
  69. * The value used to fill the stack of a task when the task is created. This
  70. * is used purely for checking the high water mark for tasks.
  71. */
  72. #define tskSTACK_FILL_BYTE (0xa5U)
  73. /* Bits used to record how a task's stack and TCB were allocated. */
  74. #define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ((uint8_t) 0)
  75. #define tskSTATICALLY_ALLOCATED_STACK_ONLY ((uint8_t) 1)
  76. #define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ((uint8_t) 2)
  77. /* If any of the following are set then task stacks are filled with a known
  78. * value so the high water mark can be determined. If none of the following are
  79. * set then don't fill the stack so there is no unnecessary dependency on memset. */
  80. #if ((configCHECK_FOR_STACK_OVERFLOW > 1) || \
  81. (configUSE_TRACE_FACILITY == 1) || \
  82. (INCLUDE_uxTaskGetStackHighWaterMark == 1) || \
  83. (INCLUDE_uxTaskGetStackHighWaterMark2 == 1))
  84. #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1
  85. #else
  86. #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0
  87. #endif
  88. /*
  89. * Macros used by vListTask to indicate which state a task is in.
  90. */
  91. #define tskRUNNING_CHAR ('X')
  92. #define tskBLOCKED_CHAR ('B')
  93. #define tskREADY_CHAR ('R')
  94. #define tskDELETED_CHAR ('D')
  95. #define tskSUSPENDED_CHAR ('S')
  96. /*
  97. * Some kernel aware debuggers require the data the debugger needs access to to
  98. * be global, rather than file scope.
  99. */
  100. #ifdef portREMOVE_STATIC_QUALIFIER
  101. #define static
  102. #endif
  103. /* The name allocated to the Idle task. This can be overridden by defining
  104. * configIDLE_TASK_NAME in FreeRTOSConfig.h. */
  105. #ifndef configIDLE_TASK_NAME
  106. #define configIDLE_TASK_NAME "IDLE"
  107. #endif
  108. #if (configUSE_PORT_OPTIMISED_TASK_SELECTION == 0)
  109. /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is
  110. * performed in a generic way that is not optimised to any particular
  111. * microcontroller architecture. */
  112. /* uxTopReadyPriority holds the priority of the highest priority ready
  113. * state task. */
  114. #define taskRECORD_READY_PRIORITY(uxPriority) \
  115. { \
  116. if ((uxPriority) > uxTopReadyPriority) \
  117. { \
  118. uxTopReadyPriority = (uxPriority); \
  119. } \
  120. } /* taskRECORD_READY_PRIORITY */
  121. #define taskSELECT_HIGHEST_PRIORITY_TASK() \
  122. { \
  123. UBaseType_t uxTopPriority = uxTopReadyPriority; \
  124. \
  125. /* Find the highest priority queue that contains ready tasks. */ \
  126. while (listLIST_IS_EMPTY(&(pxReadyTasksLists[uxTopPriority]))) \
  127. { \
  128. configASSERT(uxTopPriority); \
  129. --uxTopPriority; \
  130. } \
  131. \
  132. /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \
  133. * the same priority get an equal share of the processor time. */ \
  134. listGET_OWNER_OF_NEXT_ENTRY(pxCurrentTCB, &(pxReadyTasksLists[uxTopPriority])); \
  135. uxTopReadyPriority = uxTopPriority; \
  136. } /* taskSELECT_HIGHEST_PRIORITY_TASK */
  137. /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as
  138. * they are only required when a port optimised method of task selection is
  139. * being used. */
  140. #define taskRESET_READY_PRIORITY(uxPriority)
  141. #define portRESET_READY_PRIORITY(uxPriority, uxTopReadyPriority)
  142. #else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
  143. /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is
  144. * performed in a way that is tailored to the particular microcontroller
  145. * architecture being used. */
  146. /* A port optimised version is provided. Call the port defined macros. */
  147. #define taskRECORD_READY_PRIORITY(uxPriority) portRECORD_READY_PRIORITY((uxPriority), uxTopReadyPriority)
  148. /**
  149. * 找到优先级最高的任务
  150. * pxCurrentTCB 保存优先级最高的任务
  151. * @uxTopPriority: 保存当前系统最高优先级
  152. */
  153. #define taskSELECT_HIGHEST_PRIORITY_TASK() \
  154. { \
  155. UBaseType_t uxTopPriority; \
  156. \
  157. /* Find the highest priority list that contains ready tasks. */ \
  158. portGET_HIGHEST_PRIORITY(uxTopPriority, uxTopReadyPriority); \
  159. configASSERT(listCURRENT_LIST_LENGTH(&(pxReadyTasksLists[uxTopPriority])) > 0); \
  160. listGET_OWNER_OF_NEXT_ENTRY(pxCurrentTCB, &(pxReadyTasksLists[uxTopPriority])); \
  161. } /* taskSELECT_HIGHEST_PRIORITY_TASK() */
  162. /* A port optimised version is provided, call it only if the TCB being reset
  163. * is being referenced from a ready list. If it is referenced from a delayed
  164. * or suspended list then it won't be in a ready list. */
  165. #define taskRESET_READY_PRIORITY(uxPriority) \
  166. { \
  167. if (listCURRENT_LIST_LENGTH(&(pxReadyTasksLists[(uxPriority)])) == (UBaseType_t) 0) \
  168. { \
  169. portRESET_READY_PRIORITY((uxPriority), (uxTopReadyPriority)); \
  170. } \
  171. }
  172. #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
  173. /**
  174. * pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick
  175. * count overflows.
  176. * 当xTickCount溢出时候,交换pxDelayedTaskList和pxOverflowDelayedTaskList队列
  177. */
  178. #define taskSWITCH_DELAYED_LISTS() \
  179. { \
  180. List_t * pxTemp; \
  181. \
  182. /* The delayed tasks list should be empty when the lists are switched. */ \
  183. configASSERT((listLIST_IS_EMPTY(pxDelayedTaskList))); \
  184. \
  185. pxTemp = pxDelayedTaskList; \
  186. pxDelayedTaskList = pxOverflowDelayedTaskList; \
  187. pxOverflowDelayedTaskList = pxTemp; \
  188. xNumOfOverflows++; \
  189. prvResetNextTaskUnblockTime(); \
  190. }
  191. /*
  192. * Place the task represented by pxTCB into the appropriate ready list for
  193. * the task. It is inserted at the end of the list.
  194. * 相同优先级的,使用队列方式加入
  195. */
  196. #define prvAddTaskToReadyList(pxTCB) \
  197. traceMOVED_TASK_TO_READY_STATE(pxTCB); \
  198. taskRECORD_READY_PRIORITY((pxTCB)->uxPriority); \
  199. listINSERT_END(&(pxReadyTasksLists[(pxTCB)->uxPriority]), &((pxTCB)->xStateListItem)); \
  200. tracePOST_MOVED_TASK_TO_READY_STATE(pxTCB)
  201. /*
  202. * Several functions take a TaskHandle_t parameter that can optionally be NULL,
  203. * where NULL is used to indicate that the handle of the currently executing
  204. * task should be used in place of the parameter. This macro simply checks to
  205. * see if the parameter is NULL and returns a pointer to the appropriate TCB.
  206. */
  207. #define prvGetTCBFromHandle(pxHandle) (((pxHandle) == NULL) ? pxCurrentTCB : (pxHandle))
  208. /* The item value of the event list item is normally used to hold the priority
  209. * of the task to which it belongs (coded to allow it to be held in reverse
  210. * priority order). However, it is occasionally borrowed for other purposes. It
  211. * is important its value is not updated due to a task priority change while it is
  212. * being used for another purpose. The following bit definition is used to inform
  213. * the scheduler that the value should not be changed - in which case it is the
  214. * responsibility of whichever module is using the value to ensure it gets set back
  215. * to its original value when it is released. */
  216. #if (configUSE_16_BIT_TICKS == 1)
  217. #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U
  218. #else
  219. #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL
  220. #endif
  221. /*
  222. * Task control block. A task control block (TCB) is allocated for each task,
  223. * and stores task state information, including a pointer to the task's context
  224. * (the task's run time environment, including register values)
  225. * 任务控制块
  226. */
  227. typedef struct tskTaskControlBlock
  228. {
  229. volatile StackType_t * pxTopOfStack; /*THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */
  230. #if (portUSING_MPU_WRAPPERS == 1)
  231. xMPU_SETTINGS xMPUSettings; /*THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */
  232. #endif
  233. ListItem_t xStateListItem; /* 任务状态队列节点 (Ready, Blocked, Suspended). */
  234. ListItem_t xEventListItem; /* 任务事件队列节点 */
  235. UBaseType_t uxPriority; /* 任务优先级 */
  236. StackType_t * pxStack; /* 任务栈顶 */
  237. char pcTaskName[configMAX_TASK_NAME_LEN];
  238. /* Points to the highest valid address for the stack. */
  239. #if ((portSTACK_GROWTH > 0) || (configRECORD_STACK_HIGH_ADDRESS == 1))
  240. StackType_t * pxEndOfStack;
  241. #endif
  242. /* Holds the critical section nesting depth for ports
  243. * that do not maintain their own count in the port layer.
  244. */
  245. #if (portCRITICAL_NESTING_IN_TCB == 1)
  246. UBaseType_t uxCriticalNesting;
  247. #endif
  248. #if (configUSE_TRACE_FACILITY == 1)
  249. UBaseType_t uxTCBNumber;
  250. UBaseType_t uxTaskNumber;
  251. #endif
  252. #if (configUSE_MUTEXES == 1)
  253. UBaseType_t uxBasePriority;
  254. UBaseType_t uxMutexesHeld;
  255. #endif
  256. #if (configUSE_APPLICATION_TASK_TAG == 1)
  257. TaskHookFunction_t pxTaskTag;
  258. #endif
  259. #if (configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0)
  260. void * pvThreadLocalStoragePointers[configNUM_THREAD_LOCAL_STORAGE_POINTERS];
  261. #endif
  262. /* Stores the amount of time the task has spent in the Running state. */
  263. #if (configGENERATE_RUN_TIME_STATS == 1)
  264. configRUN_TIME_COUNTER_TYPE ulRunTimeCounter;
  265. #endif
  266. /* Memory block used as Thread Local Storage (TLS) Block for the task. */
  267. #if ((configUSE_NEWLIB_REENTRANT == 1) || (configUSE_C_RUNTIME_TLS_SUPPORT == 1))
  268. configTLS_BLOCK_TYPE xTLSBlock;
  269. #endif
  270. #if (configUSE_TASK_NOTIFICATIONS == 1)
  271. volatile uint32_t ulNotifiedValue[configTASK_NOTIFICATION_ARRAY_ENTRIES];
  272. volatile uint8_t ucNotifyState[configTASK_NOTIFICATION_ARRAY_ENTRIES];
  273. #endif
  274. /* See the comments in FreeRTOS.h with the definition of
  275. * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */
  276. #if (tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0)
  277. uint8_t ucStaticallyAllocated;
  278. #endif
  279. #if (INCLUDE_xTaskAbortDelay == 1)
  280. uint8_t ucDelayAborted;
  281. #endif
  282. #if (configUSE_POSIX_ERRNO == 1)
  283. int iTaskErrno;
  284. #endif
  285. } tskTCB;
  286. /* The old tskTCB name is maintained above then typedefed to the new TCB_t name
  287. * below to enable the use of older kernel aware debuggers.
  288. */
  289. typedef tskTCB TCB_t;
  290. /*lint -save -e956 A manual analysis and inspection has been used to determine
  291. * which static variables must be declared volatile. */
  292. portDONT_DISCARD PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL;
  293. /**
  294. * Lists for ready and blocked tasks. --------------------
  295. * xDelayedTaskList1 and xDelayedTaskList2 could be moved to function scope but
  296. * doing so breaks some kernel aware debuggers and debuggers that rely on removing
  297. * the static qualifier.
  298. * @pxReadyTasksLists: 就绪任务管理数组,每一个优先级拥有自己的管理队列
  299. */
  300. PRIVILEGED_DATA static List_t pxReadyTasksLists[configMAX_PRIORITIES]; /*< Prioritised ready tasks. */
  301. PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */
  302. PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */
  303. PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */
  304. PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */
  305. PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */
  306. #if (INCLUDE_vTaskDelete == 1)
  307. PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */
  308. PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = (UBaseType_t) 0U;
  309. #endif
  310. #if (INCLUDE_vTaskSuspend == 1)
  311. PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */
  312. #endif
  313. /* Global POSIX errno. Its value is changed upon context switching to match
  314. * the errno of the currently running task. */
  315. #if (configUSE_POSIX_ERRNO == 1)
  316. int FreeRTOS_errno = 0;
  317. #endif
  318. /* Other file private variables. --------------------------------*/
  319. PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = (UBaseType_t) 0U;
  320. /**
  321. * @xTickCount: 当前系统tick计数器
  322. */
  323. PRIVILEGED_DATA static volatile TickType_t xTickCount = (TickType_t) configINITIAL_TICK_COUNT;
  324. PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY;
  325. PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE;
  326. PRIVILEGED_DATA static volatile TickType_t xPendedTicks = (TickType_t) 0U;
  327. PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE;
  328. /**
  329. * @xNumOfOverflows: 记录xTickCount溢出的次数
  330. */
  331. PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = (BaseType_t) 0;
  332. PRIVILEGED_DATA static UBaseType_t uxTaskNumber = (UBaseType_t) 0U;
  333. PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = (TickType_t) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */
  334. /**
  335. * 空闲任务描述符
  336. */
  337. PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL;
  338. /* Improve support for OpenOCD. The kernel tracks Ready tasks via priority lists.
  339. * For tracking the state of remote threads, OpenOCD uses uxTopUsedPriority
  340. * to determine the number of priority lists to read back from the remote target. */
  341. const volatile UBaseType_t uxTopUsedPriority = configMAX_PRIORITIES - 1U;
  342. /* Context switches are held pending while the scheduler is suspended. Also,
  343. * interrupts must not manipulate the xStateListItem of a TCB, or any of the
  344. * lists the xStateListItem can be referenced from, if the scheduler is suspended.
  345. * If an interrupt needs to unblock a task while the scheduler is suspended then it
  346. * moves the task's event list item into the xPendingReadyList, ready for the
  347. * kernel to move the task from the pending ready list into the real ready list
  348. * when the scheduler is unsuspended. The pending ready list itself can only be
  349. * accessed from a critical section. */
  350. PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = (UBaseType_t) pdFALSE;
  351. #if (configGENERATE_RUN_TIME_STATS == 1)
  352. /* Do not move these variables to function scope as doing so prevents the
  353. * code working with debuggers that need to remove the static qualifier. */
  354. PRIVILEGED_DATA static configRUN_TIME_COUNTER_TYPE ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */
  355. PRIVILEGED_DATA static volatile configRUN_TIME_COUNTER_TYPE ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */
  356. #endif
  357. /**
  358. * Utility task that simply returns pdTRUE if the task referenced by xTask is
  359. * currently in the Suspended state, or pdFALSE if the task referenced by xTask
  360. * is in any other state.
  361. */
  362. #if (INCLUDE_vTaskSuspend == 1)
  363. static BaseType_t prvTaskIsTaskSuspended(const TaskHandle_t xTask) PRIVILEGED_FUNCTION;
  364. #endif /* INCLUDE_vTaskSuspend */
  365. /*
  366. * Utility to ready all the lists used by the scheduler. This is called
  367. * automatically upon the creation of the first task.
  368. */
  369. static void prvInitialiseTaskLists(void) PRIVILEGED_FUNCTION;
  370. /*
  371. * The idle task, which as all tasks is implemented as a never ending loop.
  372. * The idle task is automatically created and added to the ready lists upon
  373. * creation of the first user task.
  374. *
  375. * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific
  376. * language extensions. The equivalent prototype for this function is:
  377. *
  378. * void prvIdleTask(void *pvParameters);
  379. *
  380. */
  381. static portTASK_FUNCTION_PROTO(prvIdleTask, pvParameters) PRIVILEGED_FUNCTION;
  382. /*
  383. * Utility to free all memory allocated by the scheduler to hold a TCB,
  384. * including the stack pointed to by the TCB.
  385. *
  386. * This does not free memory allocated by the task itself (i.e. memory
  387. * allocated by calls to pvPortMalloc from within the tasks application code).
  388. */
  389. #if (INCLUDE_vTaskDelete == 1)
  390. static void prvDeleteTCB(TCB_t * pxTCB) PRIVILEGED_FUNCTION;
  391. #endif
  392. /*
  393. * Used only by the idle task. This checks to see if anything has been placed
  394. * in the list of tasks waiting to be deleted. If so the task is cleaned up
  395. * and its TCB deleted.
  396. */
  397. static void prvCheckTasksWaitingTermination(void) PRIVILEGED_FUNCTION;
  398. /*
  399. * The currently executing task is entering the Blocked state. Add the task to
  400. * either the current or the overflow delayed task list.
  401. */
  402. static void prvAddCurrentTaskToDelayedList(TickType_t xTicksToWait,
  403. const BaseType_t xCanBlockIndefinitely) PRIVILEGED_FUNCTION;
  404. /*
  405. * Fills an TaskStatus_t structure with information on each task that is
  406. * referenced from the pxList list (which may be a ready list, a delayed list,
  407. * a suspended list, etc.).
  408. *
  409. * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM
  410. * NORMAL APPLICATION CODE.
  411. */
  412. #if (configUSE_TRACE_FACILITY == 1)
  413. static UBaseType_t prvListTasksWithinSingleList(TaskStatus_t * pxTaskStatusArray,
  414. List_t * pxList,
  415. eTaskState eState) PRIVILEGED_FUNCTION;
  416. #endif
  417. /*
  418. * Searches pxList for a task with name pcNameToQuery - returning a handle to
  419. * the task if it is found, or NULL if the task is not found.
  420. */
  421. #if (INCLUDE_xTaskGetHandle == 1)
  422. static TCB_t * prvSearchForNameWithinSingleList(List_t * pxList,
  423. const char pcNameToQuery[]) PRIVILEGED_FUNCTION;
  424. #endif
  425. /*
  426. * When a task is created, the stack of the task is filled with a known value.
  427. * This function determines the 'high water mark' of the task stack by
  428. * determining how much of the stack remains at the original preset value.
  429. */
  430. #if ((configUSE_TRACE_FACILITY == 1) || (INCLUDE_uxTaskGetStackHighWaterMark == 1) || (INCLUDE_uxTaskGetStackHighWaterMark2 == 1))
  431. static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace(const uint8_t * pucStackByte) PRIVILEGED_FUNCTION;
  432. #endif
  433. /*
  434. * Return the amount of time, in ticks, that will pass before the kernel will
  435. * next move a task from the Blocked state to the Running state.
  436. *
  437. * This conditional compilation should use inequality to 0, not equality to 1.
  438. * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user
  439. * defined low power mode implementations require configUSE_TICKLESS_IDLE to be
  440. * set to a value other than 1.
  441. */
  442. #if (configUSE_TICKLESS_IDLE != 0)
  443. static TickType_t prvGetExpectedIdleTime(void) PRIVILEGED_FUNCTION;
  444. #endif
  445. /*
  446. * Set xNextTaskUnblockTime to the time at which the next Blocked state task
  447. * will exit the Blocked state.
  448. */
  449. static void prvResetNextTaskUnblockTime(void) PRIVILEGED_FUNCTION;
  450. #if (configUSE_STATS_FORMATTING_FUNCTIONS > 0)
  451. /*
  452. * Helper function used to pad task names with spaces when printing out
  453. * human readable tables of task information.
  454. */
  455. static char * prvWriteNameToBuffer(char * pcBuffer,
  456. const char * pcTaskName) PRIVILEGED_FUNCTION;
  457. #endif
  458. /*
  459. * Called after a Task_t structure has been allocated either statically or
  460. * dynamically to fill in the structure's members.
  461. */
  462. static void prvInitialiseNewTask(TaskFunction_t pxTaskCode,
  463. const char * const pcName,
  464. const uint32_t ulStackDepth,
  465. void * const pvParameters,
  466. UBaseType_t uxPriority,
  467. TaskHandle_t * const pxCreatedTask,
  468. TCB_t * pxNewTCB,
  469. const MemoryRegion_t * const xRegions) PRIVILEGED_FUNCTION;
  470. /*
  471. * Called after a new task has been created and initialised to place the task
  472. * under the control of the scheduler.
  473. */
  474. static void prvAddNewTaskToReadyList(TCB_t * pxNewTCB) PRIVILEGED_FUNCTION;
  475. /*
  476. * freertos_tasks_c_additions_init() should only be called if the user definable
  477. * macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro
  478. * called by the function.
  479. */
  480. #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
  481. static void freertos_tasks_c_additions_init(void) PRIVILEGED_FUNCTION;
  482. #endif
  483. #if (portUSING_MPU_WRAPPERS == 1)
  484. BaseType_t xTaskCreateRestricted(const TaskParameters_t * const pxTaskDefinition,
  485. TaskHandle_t * pxCreatedTask)
  486. {
  487. TCB_t * pxNewTCB;
  488. BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
  489. configASSERT(pxTaskDefinition->puxStackBuffer);
  490. if (pxTaskDefinition->puxStackBuffer != NULL)
  491. {
  492. /* Allocate space for the TCB. Where the memory comes from depends
  493. * on the implementation of the port malloc function and whether or
  494. * not static allocation is being used. */
  495. pxNewTCB = (TCB_t *) pvPortMalloc(sizeof(TCB_t));
  496. if (pxNewTCB != NULL)
  497. {
  498. memset((void *) pxNewTCB, 0x00, sizeof(TCB_t));
  499. /* Store the stack location in the TCB. */
  500. pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer;
  501. #if (tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0)
  502. {
  503. /* Tasks can be created statically or dynamically, so note
  504. * this task had a statically allocated stack in case it is
  505. * later deleted. The TCB was allocated dynamically. */
  506. pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY;
  507. }
  508. #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
  509. prvInitialiseNewTask(pxTaskDefinition->pvTaskCode,
  510. pxTaskDefinition->pcName,
  511. (uint32_t) pxTaskDefinition->usStackDepth,
  512. pxTaskDefinition->pvParameters,
  513. pxTaskDefinition->uxPriority,
  514. pxCreatedTask, pxNewTCB,
  515. pxTaskDefinition->xRegions);
  516. prvAddNewTaskToReadyList(pxNewTCB);
  517. xReturn = pdPASS;
  518. }
  519. }
  520. return xReturn;
  521. }
  522. #endif /* portUSING_MPU_WRAPPERS */
  523. /**
  524. * 创建任务
  525. * @pxTaskCode: 任务函数入口
  526. * @pcName: 任务名称
  527. * @usStackDepth: 任务堆栈大小
  528. * @pvParameters: 传递给任务的参数
  529. * @uxPriority: 任务优先级, 数字越大,优先级越大
  530. * @pxCreatedTask: 任务句柄
  531. */
  532. BaseType_t xTaskCreate(TaskFunction_t pxTaskCode,
  533. const char * const pcName,
  534. const configSTACK_DEPTH_TYPE usStackDepth,
  535. void * const pvParameters,
  536. UBaseType_t uxPriority,
  537. TaskHandle_t * const pxCreatedTask)
  538. {
  539. TCB_t * pxNewTCB;
  540. BaseType_t xReturn;
  541. /* If the stack grows down then allocate the stack then the TCB so the stack
  542. * does not grow into the TCB. Likewise if the stack grows up then allocate
  543. * the TCB then the stack.
  544. * 堆栈向下生长
  545. */
  546. #if (portSTACK_GROWTH > 0)
  547. {
  548. /* Allocate space for the TCB. Where the memory comes from depends on
  549. * the implementation of the port malloc function and whether or not static
  550. * allocation is being used. */
  551. pxNewTCB = (TCB_t *) pvPortMalloc(sizeof(TCB_t));
  552. if (pxNewTCB != NULL)
  553. {
  554. memset((void *) pxNewTCB, 0x00, sizeof(TCB_t));
  555. /* Allocate space for the stack used by the task being created.
  556. * The base of the stack memory stored in the TCB so the task can
  557. * be deleted later if required. */
  558. pxNewTCB->pxStack = (StackType_t *) pvPortMallocStack((((size_t) usStackDepth) * sizeof(StackType_t)));
  559. if (pxNewTCB->pxStack == NULL)
  560. {
  561. /* Could not allocate the stack. Delete the allocated TCB. */
  562. vPortFree(pxNewTCB);
  563. pxNewTCB = NULL;
  564. }
  565. }
  566. }
  567. #else /* portSTACK_GROWTH */
  568. {
  569. StackType_t * pxStack;
  570. /**
  571. * Allocate space for the stack used by the task being created.
  572. * 申请任务堆栈空间
  573. */
  574. pxStack = pvPortMallocStack((((size_t)usStackDepth) * sizeof(StackType_t)));
  575. if (pxStack != NULL) {
  576. /**
  577. * Allocate space for the TCB.
  578. * 任务控制块申请内存
  579. */
  580. pxNewTCB = (TCB_t *)pvPortMalloc(sizeof(TCB_t));
  581. if (pxNewTCB != NULL) {
  582. memset((void *)pxNewTCB, 0x00, sizeof(TCB_t));
  583. /**
  584. * Store the stack location in the TCB.
  585. * 设置新任务的堆栈
  586. */
  587. pxNewTCB->pxStack = pxStack;
  588. }
  589. else
  590. {
  591. /* The stack cannot be used as the TCB was not created. Free
  592. * it again. */
  593. vPortFreeStack(pxStack);
  594. }
  595. }
  596. else
  597. {
  598. pxNewTCB = NULL;
  599. }
  600. }
  601. #endif /* portSTACK_GROWTH */
  602. if (pxNewTCB != NULL) {
  603. #if (tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0)
  604. {
  605. /* Tasks can be created statically or dynamically, so note this
  606. * task was created dynamically in case it is later deleted. */
  607. pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB;
  608. }
  609. #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
  610. prvInitialiseNewTask(pxTaskCode,
  611. pcName,
  612. (uint32_t)usStackDepth,
  613. pvParameters,
  614. uxPriority,
  615. pxCreatedTask,
  616. pxNewTCB,
  617. NULL);
  618. /* 新创建的任务,加入任务就绪队列 */
  619. prvAddNewTaskToReadyList(pxNewTCB);
  620. xReturn = pdPASS;
  621. }
  622. else
  623. {
  624. xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
  625. }
  626. return xReturn;
  627. }
  628. static void prvInitialiseNewTask(TaskFunction_t pxTaskCode,
  629. const char * const pcName,
  630. const uint32_t ulStackDepth,
  631. void * const pvParameters,
  632. UBaseType_t uxPriority,
  633. TaskHandle_t * const pxCreatedTask,
  634. TCB_t * pxNewTCB,
  635. const MemoryRegion_t * const xRegions)
  636. {
  637. StackType_t * pxTopOfStack;
  638. UBaseType_t x;
  639. #if (portUSING_MPU_WRAPPERS == 1)
  640. /* Should the task be created in privileged mode? */
  641. BaseType_t xRunPrivileged;
  642. if ((uxPriority & portPRIVILEGE_BIT) != 0U)
  643. {
  644. xRunPrivileged = pdTRUE;
  645. }
  646. else
  647. {
  648. xRunPrivileged = pdFALSE;
  649. }
  650. uxPriority &= ~portPRIVILEGE_BIT;
  651. #endif /* portUSING_MPU_WRAPPERS == 1 */
  652. /* Avoid dependency on memset() if it is not required. */
  653. #if (tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1)
  654. {
  655. /* Fill the stack with a known value to assist debugging. */
  656. (void)memset(pxNewTCB->pxStack, (int)tskSTACK_FILL_BYTE, (size_t) ulStackDepth * sizeof(StackType_t));
  657. }
  658. #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */
  659. /* Calculate the top of stack address. This depends on whether the stack
  660. * grows from high memory to low (as per the 80x86) or vice versa.
  661. * portSTACK_GROWTH is used to make the result positive or negative as required
  662. * by the port.
  663. * portSTACK_GROWTH小于0,栈向下生长(高地址往低地址)
  664. */
  665. #if (portSTACK_GROWTH < 0)
  666. {
  667. /* 设置栈顶的位置(高地址) */
  668. pxTopOfStack = &(pxNewTCB->pxStack[ulStackDepth - (uint32_t)1]);
  669. /* 栈地址对齐到portBYTE_ALIGNMENT_MASK */
  670. pxTopOfStack = (StackType_t *)(((portPOINTER_SIZE_TYPE) pxTopOfStack) & (~((portPOINTER_SIZE_TYPE) portBYTE_ALIGNMENT_MASK)));
  671. /**
  672. * Check the alignment of the calculated top of stack is correct.
  673. * 如果栈地址不对齐,发出assert
  674. */
  675. configASSERT((((portPOINTER_SIZE_TYPE)pxTopOfStack & (portPOINTER_SIZE_TYPE)portBYTE_ALIGNMENT_MASK) == 0UL));
  676. #if (configRECORD_STACK_HIGH_ADDRESS == 1)
  677. {
  678. /* Also record the stack's high address, which may assist
  679. * debugging. */
  680. pxNewTCB->pxEndOfStack = pxTopOfStack;
  681. }
  682. #endif /* configRECORD_STACK_HIGH_ADDRESS */
  683. }
  684. #else
  685. {
  686. /* 栈向上生长, 栈顶地址就是栈的起始地址 */
  687. pxTopOfStack = pxNewTCB->pxStack;
  688. /* Check the alignment of the stack buffer is correct. */
  689. configASSERT((((portPOINTER_SIZE_TYPE) pxNewTCB->pxStack & (portPOINTER_SIZE_TYPE) portBYTE_ALIGNMENT_MASK) == 0UL));
  690. /**
  691. * The other extreme of the stack space is required if stack checking is
  692. * performed.
  693. * 计算出栈底的地址
  694. */
  695. pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + (ulStackDepth - (uint32_t)1);
  696. }
  697. #endif /* portSTACK_GROWTH */
  698. /* Store the task name in the TCB. */
  699. if (pcName != NULL) {
  700. for (x = (UBaseType_t) 0; x < (UBaseType_t) configMAX_TASK_NAME_LEN; x++) {
  701. /* 保存任务名称 */
  702. pxNewTCB->pcTaskName[x] = pcName[x];
  703. /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than
  704. * configMAX_TASK_NAME_LEN characters just in case the memory after the
  705. * string is not accessible (extremely unlikely). */
  706. if (pcName[x] == (char) 0x00) {
  707. break;
  708. }
  709. }
  710. /* Ensure the name string is terminated in the case that the string length
  711. * was greater or equal to configMAX_TASK_NAME_LEN. */
  712. pxNewTCB->pcTaskName[configMAX_TASK_NAME_LEN - 1] = '\0';
  713. }
  714. /* This is used as an array index so must ensure it's not too large. */
  715. configASSERT(uxPriority < configMAX_PRIORITIES);
  716. if (uxPriority >= (UBaseType_t) configMAX_PRIORITIES) {
  717. uxPriority = (UBaseType_t) configMAX_PRIORITIES - (UBaseType_t)1U;
  718. }
  719. pxNewTCB->uxPriority = uxPriority;
  720. #if (configUSE_MUTEXES == 1)
  721. {
  722. pxNewTCB->uxBasePriority = uxPriority;
  723. }
  724. #endif /* configUSE_MUTEXES */
  725. vListInitialiseItem(&(pxNewTCB->xStateListItem));
  726. vListInitialiseItem(&(pxNewTCB->xEventListItem));
  727. /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get
  728. * back to the containing TCB from a generic item in a list. */
  729. listSET_LIST_ITEM_OWNER(&(pxNewTCB->xStateListItem), pxNewTCB);
  730. /* Event lists are always in priority order. */
  731. listSET_LIST_ITEM_VALUE(&(pxNewTCB->xEventListItem), (TickType_t)configMAX_PRIORITIES - (TickType_t)uxPriority);
  732. listSET_LIST_ITEM_OWNER(&(pxNewTCB->xEventListItem), pxNewTCB);
  733. #if (portUSING_MPU_WRAPPERS == 1)
  734. {
  735. vPortStoreTaskMPUSettings(&(pxNewTCB->xMPUSettings), xRegions, pxNewTCB->pxStack, ulStackDepth);
  736. }
  737. #else
  738. {
  739. /* Avoid compiler warning about unreferenced parameter. */
  740. (void) xRegions;
  741. }
  742. #endif
  743. #if ((configUSE_NEWLIB_REENTRANT == 1) || (configUSE_C_RUNTIME_TLS_SUPPORT == 1))
  744. {
  745. /* Allocate and initialize memory for the task's TLS Block. */
  746. configINIT_TLS_BLOCK(pxNewTCB->xTLSBlock);
  747. }
  748. #endif
  749. /* Initialize the TCB stack to look as if the task was already running,
  750. * but had been interrupted by the scheduler. The return address is set
  751. * to the start of the task function. Once the stack has been initialised
  752. * the top of stack variable is updated. */
  753. #if (portUSING_MPU_WRAPPERS == 1)
  754. {
  755. /* If the port has capability to detect stack overflow,
  756. * pass the stack end address to the stack initialization
  757. * function as well. */
  758. #if (portHAS_STACK_OVERFLOW_CHECKING == 1)
  759. {
  760. #if (portSTACK_GROWTH < 0)
  761. {
  762. pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged);
  763. }
  764. #else /* portSTACK_GROWTH */
  765. {
  766. pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged);
  767. }
  768. #endif /* portSTACK_GROWTH */
  769. }
  770. #else /* portHAS_STACK_OVERFLOW_CHECKING */
  771. {
  772. pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged);
  773. }
  774. #endif /* portHAS_STACK_OVERFLOW_CHECKING */
  775. }
  776. #else /* portUSING_MPU_WRAPPERS */
  777. {
  778. /* If the port has capability to detect stack overflow,
  779. * pass the stack end address to the stack initialization
  780. * function as well. */
  781. #if (portHAS_STACK_OVERFLOW_CHECKING == 1)
  782. {
  783. #if (portSTACK_GROWTH < 0)
  784. {
  785. pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters);
  786. }
  787. #else /* portSTACK_GROWTH */
  788. {
  789. pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters);
  790. }
  791. #endif /* portSTACK_GROWTH */
  792. }
  793. #else /* portHAS_STACK_OVERFLOW_CHECKING */
  794. {
  795. /* 指向 任务栈中的R11的位置 */
  796. pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxTaskCode, pvParameters);
  797. }
  798. #endif /* portHAS_STACK_OVERFLOW_CHECKING */
  799. }
  800. #endif /* portUSING_MPU_WRAPPERS */
  801. if (pxCreatedTask != NULL)
  802. {
  803. /* Pass the handle out in an anonymous way. The handle can be used to
  804. * change the created task's priority, delete the created task, etc.*/
  805. *pxCreatedTask = (TaskHandle_t) pxNewTCB;
  806. }
  807. }
  808. static void prvAddNewTaskToReadyList(TCB_t * pxNewTCB)
  809. {
  810. /* Ensure interrupts don't access the task lists while the lists are being
  811. * updated. */
  812. taskENTER_CRITICAL();
  813. {
  814. /* 累加系统任务数 */
  815. uxCurrentNumberOfTasks++;
  816. /* 系统当前没有任务运行 */
  817. if (pxCurrentTCB == NULL) {
  818. /**
  819. * There are no other tasks, or all the other tasks are in
  820. * the suspended state - make this the current task.
  821. * 系统没任务或者所有任务都被挂起了
  822. */
  823. pxCurrentTCB = pxNewTCB;
  824. /* 系统第一次创建任务 */
  825. if (uxCurrentNumberOfTasks == (UBaseType_t)1) {
  826. /* This is the first task to be created so do the preliminary
  827. * initialisation required. We will not recover if this call
  828. * fails, but we will report the failure. */
  829. prvInitialiseTaskLists();
  830. }
  831. }
  832. else
  833. {
  834. /* If the scheduler is not already running, make this task the
  835. * current task if it is the highest priority task to be created
  836. * so far.
  837. * 任务调度器还没有运行
  838. */
  839. if (xSchedulerRunning == pdFALSE) {
  840. /* 如果新建任务的优先级,大于当前任务的优先级,将新创建的任务设置为当前任务 */
  841. if (pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority)
  842. {
  843. pxCurrentTCB = pxNewTCB;
  844. }
  845. }
  846. }
  847. uxTaskNumber++;
  848. #if (configUSE_TRACE_FACILITY == 1)
  849. {
  850. /* Add a counter into the TCB for tracing only. */
  851. pxNewTCB->uxTCBNumber = uxTaskNumber;
  852. }
  853. #endif /* configUSE_TRACE_FACILITY */
  854. traceTASK_CREATE(pxNewTCB);
  855. /* 新创建的任务,加入就绪队列 */
  856. prvAddTaskToReadyList(pxNewTCB);
  857. portSETUP_TCB(pxNewTCB);
  858. }
  859. taskEXIT_CRITICAL();
  860. /* 调度器已经开始运行, 检查新创建的任务,是否可以抢占,当前正在运行的任务 */
  861. if (xSchedulerRunning == pdTRUE) {
  862. /**
  863. * 新创建的任务优先级高于当前正在运行任务的优先级,触发抢占
  864. */
  865. if (pxCurrentTCB->uxPriority < pxNewTCB->uxPriority)
  866. {
  867. /**
  868. * 对于cortex-m系列的arm来说,就是触发PendSVHandler异常
  869. */
  870. taskYIELD_IF_USING_PREEMPTION();
  871. }
  872. }
  873. }
  874. #if (INCLUDE_vTaskDelete == 1)
  875. /**
  876. * 删除任务
  877. * @ xTaskToDelete: 待删除的任务
  878. */
  879. void vTaskDelete(TaskHandle_t xTaskToDelete)
  880. {
  881. TCB_t * pxTCB;
  882. taskENTER_CRITICAL();
  883. {
  884. /**
  885. * If null is passed in here then it is the calling task that is
  886. * being deleted.
  887. */
  888. pxTCB = prvGetTCBFromHandle(xTaskToDelete);
  889. /**
  890. * Remove task from the ready/delayed list.
  891. * 任务从就绪队列删除
  892. */
  893. if (uxListRemove(&(pxTCB->xStateListItem)) == (UBaseType_t)0)
  894. {
  895. taskRESET_READY_PRIORITY(pxTCB->uxPriority);
  896. }
  897. /**
  898. * Is the task waiting on an event also?
  899. * 如果待删除任务正在等待事件
  900. */
  901. if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) != NULL)
  902. {
  903. /* 直接从事件链表中删除 */
  904. (void)uxListRemove(&(pxTCB->xEventListItem));
  905. }
  906. /* Increment the uxTaskNumber also so kernel aware debuggers can
  907. * detect that the task lists need re-generating. This is done before
  908. * portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will
  909. * not return. */
  910. uxTaskNumber++;
  911. /* 待删除任务是当前正在运行的任务 */
  912. if (pxTCB == pxCurrentTCB) {
  913. /* A task is deleting itself. This cannot complete within the
  914. * task itself, as a context switch to another task is required.
  915. * Place the task in the termination list. The idle task will
  916. * check the termination list and free up any memory allocated by
  917. * the scheduler for the TCB and stack of the deleted task.
  918. * 加入到待删除任务管理队列
  919. */
  920. vListInsertEnd(&xTasksWaitingTermination, &(pxTCB->xStateListItem));
  921. /* Increment the ucTasksDeleted variable so the idle task knows
  922. * there is a task that has been deleted and that it should therefore
  923. * check the xTasksWaitingTermination list. */
  924. ++uxDeletedTasksWaitingCleanUp;
  925. /* Call the delete hook before portPRE_TASK_DELETE_HOOK() as
  926. * portPRE_TASK_DELETE_HOOK() does not return in the Win32 port. */
  927. traceTASK_DELETE(pxTCB);
  928. /* The pre-delete hook is primarily for the Windows simulator,
  929. * in which Windows specific clean up operations are performed,
  930. * after which it is not possible to yield away from this task -
  931. * hence xYieldPending is used to latch that a context switch is
  932. * required. */
  933. portPRE_TASK_DELETE_HOOK(pxTCB, &xYieldPending);
  934. }
  935. else
  936. {
  937. --uxCurrentNumberOfTasks;
  938. traceTASK_DELETE(pxTCB);
  939. /* Reset the next expected unblock time in case it referred to
  940. * the task that has just been deleted. */
  941. prvResetNextTaskUnblockTime();
  942. }
  943. }
  944. taskEXIT_CRITICAL();
  945. /* If the task is not deleting itself, call prvDeleteTCB from outside of
  946. * critical section. If a task deletes itself, prvDeleteTCB is called
  947. * from prvCheckTasksWaitingTermination which is called from Idle task. */
  948. if (pxTCB != pxCurrentTCB)
  949. {
  950. prvDeleteTCB(pxTCB);
  951. }
  952. /* Force a reschedule if it is the currently running task that has just
  953. * been deleted. */
  954. if (xSchedulerRunning == pdTRUE)
  955. {
  956. /* 待删除任务是自己 */
  957. if (pxTCB == pxCurrentTCB)
  958. {
  959. configASSERT(uxSchedulerSuspended == 0);
  960. /* 多触发一次任务调度 */
  961. portYIELD_WITHIN_API();
  962. }
  963. }
  964. }
  965. #endif
  966. #if (INCLUDE_xTaskDelayUntil == 1)
  967. BaseType_t xTaskDelayUntil(TickType_t * const pxPreviousWakeTime,
  968. const TickType_t xTimeIncrement)
  969. {
  970. TickType_t xTimeToWake;
  971. BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE;
  972. configASSERT(pxPreviousWakeTime);
  973. configASSERT((xTimeIncrement > 0U));
  974. configASSERT(uxSchedulerSuspended == 0);
  975. vTaskSuspendAll();
  976. {
  977. /* Minor optimisation. The tick count cannot change in this
  978. * block. */
  979. const TickType_t xConstTickCount = xTickCount;
  980. /* Generate the tick time at which the task wants to wake. */
  981. xTimeToWake = *pxPreviousWakeTime + xTimeIncrement;
  982. if (xConstTickCount < *pxPreviousWakeTime)
  983. {
  984. /* The tick count has overflowed since this function was
  985. * lasted called. In this case the only time we should ever
  986. * actually delay is if the wake time has also overflowed,
  987. * and the wake time is greater than the tick time. When this
  988. * is the case it is as if neither time had overflowed. */
  989. if ((xTimeToWake < *pxPreviousWakeTime) && (xTimeToWake > xConstTickCount))
  990. {
  991. xShouldDelay = pdTRUE;
  992. }
  993. }
  994. else
  995. {
  996. /* The tick time has not overflowed. In this case we will
  997. * delay if either the wake time has overflowed, and/or the
  998. * tick time is less than the wake time. */
  999. if ((xTimeToWake < *pxPreviousWakeTime) || (xTimeToWake > xConstTickCount))
  1000. {
  1001. xShouldDelay = pdTRUE;
  1002. }
  1003. }
  1004. /* Update the wake time ready for the next call. */
  1005. *pxPreviousWakeTime = xTimeToWake;
  1006. if (xShouldDelay != pdFALSE)
  1007. {
  1008. traceTASK_DELAY_UNTIL(xTimeToWake);
  1009. /* prvAddCurrentTaskToDelayedList() needs the block time, not
  1010. * the time to wake, so subtract the current tick count. */
  1011. prvAddCurrentTaskToDelayedList(xTimeToWake - xConstTickCount, pdFALSE);
  1012. }
  1013. }
  1014. xAlreadyYielded = xTaskResumeAll();
  1015. /* Force a reschedule if xTaskResumeAll has not already done so, we may
  1016. * have put ourselves to sleep. */
  1017. if (xAlreadyYielded == pdFALSE)
  1018. {
  1019. portYIELD_WITHIN_API();
  1020. }
  1021. return xShouldDelay;
  1022. }
  1023. #endif /* INCLUDE_xTaskDelayUntil */
  1024. #if (INCLUDE_vTaskDelay == 1)
  1025. /**
  1026. * 相对延迟
  1027. * @xTicksToDelay: 系统相对节拍数
  1028. */
  1029. void vTaskDelay(const TickType_t xTicksToDelay)
  1030. {
  1031. BaseType_t xAlreadyYielded = pdFALSE;
  1032. /* A delay time of zero just forces a reschedule. */
  1033. if (xTicksToDelay > (TickType_t)0U)
  1034. {
  1035. configASSERT(uxSchedulerSuspended == 0);
  1036. /* 临时挂起任务调度 */
  1037. vTaskSuspendAll();
  1038. {
  1039. traceTASK_DELAY();
  1040. /* A task that is removed from the event list while the
  1041. * scheduler is suspended will not get placed in the ready
  1042. * list or removed from the blocked list until the scheduler
  1043. * is resumed.
  1044. *
  1045. * This task cannot be in an event list as it is the currently
  1046. * executing task. */
  1047. prvAddCurrentTaskToDelayedList(xTicksToDelay, pdFALSE);
  1048. }
  1049. /* 恢复任务调度 */
  1050. xAlreadyYielded = xTaskResumeAll();
  1051. }
  1052. /**
  1053. * Force a reschedule if xTaskResumeAll has not already done so, we may
  1054. * have put ourselves to sleep.
  1055. * 如果有任务需要被调度,触发任务调度,执行延迟的任务被挂起
  1056. */
  1057. if (xAlreadyYielded == pdFALSE)
  1058. {
  1059. portYIELD_WITHIN_API();
  1060. }
  1061. }
  1062. #endif
  1063. #if ((INCLUDE_eTaskGetState == 1) || (configUSE_TRACE_FACILITY == 1) || (INCLUDE_xTaskAbortDelay == 1))
  1064. eTaskState eTaskGetState(TaskHandle_t xTask)
  1065. {
  1066. eTaskState eReturn;
  1067. List_t const * pxStateList;
  1068. List_t const * pxDelayedList;
  1069. List_t const * pxOverflowedDelayedList;
  1070. const TCB_t * const pxTCB = xTask;
  1071. configASSERT(pxTCB);
  1072. if (pxTCB == pxCurrentTCB)
  1073. {
  1074. /* The task calling this function is querying its own state. */
  1075. eReturn = eRunning;
  1076. }
  1077. else
  1078. {
  1079. taskENTER_CRITICAL();
  1080. {
  1081. pxStateList = listLIST_ITEM_CONTAINER(&(pxTCB->xStateListItem));
  1082. pxDelayedList = pxDelayedTaskList;
  1083. pxOverflowedDelayedList = pxOverflowDelayedTaskList;
  1084. }
  1085. taskEXIT_CRITICAL();
  1086. if ((pxStateList == pxDelayedList) || (pxStateList == pxOverflowedDelayedList))
  1087. {
  1088. /* The task being queried is referenced from one of the Blocked
  1089. * lists. */
  1090. eReturn = eBlocked;
  1091. }
  1092. #if (INCLUDE_vTaskSuspend == 1)
  1093. else if (pxStateList == &xSuspendedTaskList)
  1094. {
  1095. /* The task being queried is referenced from the suspended
  1096. * list. Is it genuinely suspended or is it blocked
  1097. * indefinitely? */
  1098. if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) == NULL)
  1099. {
  1100. #if (configUSE_TASK_NOTIFICATIONS == 1)
  1101. {
  1102. BaseType_t x;
  1103. /* The task does not appear on the event list item of
  1104. * and of the RTOS objects, but could still be in the
  1105. * blocked state if it is waiting on its notification
  1106. * rather than waiting on an object. If not, is
  1107. * suspended. */
  1108. eReturn = eSuspended;
  1109. for (x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++)
  1110. {
  1111. if (pxTCB->ucNotifyState[x] == taskWAITING_NOTIFICATION)
  1112. {
  1113. eReturn = eBlocked;
  1114. break;
  1115. }
  1116. }
  1117. }
  1118. #else /* if (configUSE_TASK_NOTIFICATIONS == 1) */
  1119. {
  1120. eReturn = eSuspended;
  1121. }
  1122. #endif /* if (configUSE_TASK_NOTIFICATIONS == 1) */
  1123. }
  1124. else
  1125. {
  1126. eReturn = eBlocked;
  1127. }
  1128. }
  1129. #endif /* if (INCLUDE_vTaskSuspend == 1) */
  1130. #if (INCLUDE_vTaskDelete == 1)
  1131. else if ((pxStateList == &xTasksWaitingTermination) || (pxStateList == NULL))
  1132. {
  1133. /* The task being queried is referenced from the deleted
  1134. * tasks list, or it is not referenced from any lists at
  1135. * all. */
  1136. eReturn = eDeleted;
  1137. }
  1138. #endif
  1139. else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */
  1140. {
  1141. /* If the task is not in any other state, it must be in the
  1142. * Ready (including pending ready) state. */
  1143. eReturn = eReady;
  1144. }
  1145. }
  1146. return eReturn;
  1147. } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
  1148. #endif /* INCLUDE_eTaskGetState */
  1149. #if (INCLUDE_uxTaskPriorityGet == 1)
  1150. UBaseType_t uxTaskPriorityGet(const TaskHandle_t xTask)
  1151. {
  1152. TCB_t const * pxTCB;
  1153. UBaseType_t uxReturn;
  1154. taskENTER_CRITICAL();
  1155. {
  1156. /* If null is passed in here then it is the priority of the task
  1157. * that called uxTaskPriorityGet() that is being queried. */
  1158. pxTCB = prvGetTCBFromHandle(xTask);
  1159. uxReturn = pxTCB->uxPriority;
  1160. }
  1161. taskEXIT_CRITICAL();
  1162. return uxReturn;
  1163. }
  1164. #endif
  1165. #if (INCLUDE_uxTaskPriorityGet == 1)
  1166. UBaseType_t uxTaskPriorityGetFromISR(const TaskHandle_t xTask)
  1167. {
  1168. TCB_t const * pxTCB;
  1169. UBaseType_t uxReturn, uxSavedInterruptState;
  1170. /* RTOS ports that support interrupt nesting have the concept of a
  1171. * maximum system call (or maximum API call) interrupt priority.
  1172. * Interrupts that are above the maximum system call priority are keep
  1173. * permanently enabled, even when the RTOS kernel is in a critical section,
  1174. * but cannot make any calls to FreeRTOS API functions. If configASSERT()
  1175. * is defined in FreeRTOSConfig.h then
  1176. * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
  1177. * failure if a FreeRTOS API function is called from an interrupt that has
  1178. * been assigned a priority above the configured maximum system call
  1179. * priority. Only FreeRTOS functions that end in FromISR can be called
  1180. * from interrupts that have been assigned a priority at or (logically)
  1181. * below the maximum system call interrupt priority. FreeRTOS maintains a
  1182. * separate interrupt safe API to ensure interrupt entry is as fast and as
  1183. * simple as possible. More information (albeit Cortex-M specific) is
  1184. * provided on the following link:
  1185. * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
  1186. portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
  1187. uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR();
  1188. {
  1189. /* If null is passed in here then it is the priority of the calling
  1190. * task that is being queried. */
  1191. pxTCB = prvGetTCBFromHandle(xTask);
  1192. uxReturn = pxTCB->uxPriority;
  1193. }
  1194. portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptState);
  1195. return uxReturn;
  1196. }
  1197. #endif /* INCLUDE_uxTaskPriorityGet */
  1198. #if (INCLUDE_vTaskPrioritySet == 1)
  1199. void vTaskPrioritySet(TaskHandle_t xTask, UBaseType_t uxNewPriority)
  1200. {
  1201. TCB_t * pxTCB;
  1202. UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry;
  1203. BaseType_t xYieldRequired = pdFALSE;
  1204. configASSERT(uxNewPriority < configMAX_PRIORITIES);
  1205. /* Ensure the new priority is valid. */
  1206. if (uxNewPriority >= (UBaseType_t)configMAX_PRIORITIES)
  1207. {
  1208. uxNewPriority = (UBaseType_t)configMAX_PRIORITIES - (UBaseType_t)1U;
  1209. }
  1210. taskENTER_CRITICAL();
  1211. {
  1212. /* If null is passed in here then it is the priority of the calling
  1213. * task that is being changed. */
  1214. pxTCB = prvGetTCBFromHandle(xTask);
  1215. traceTASK_PRIORITY_SET(pxTCB, uxNewPriority);
  1216. #if (configUSE_MUTEXES == 1)
  1217. {
  1218. uxCurrentBasePriority = pxTCB->uxBasePriority;
  1219. }
  1220. #else
  1221. {
  1222. uxCurrentBasePriority = pxTCB->uxPriority;
  1223. }
  1224. #endif
  1225. if (uxCurrentBasePriority != uxNewPriority)
  1226. {
  1227. /* The priority change may have readied a task of higher
  1228. * priority than the calling task. */
  1229. if (uxNewPriority > uxCurrentBasePriority)
  1230. {
  1231. if (pxTCB != pxCurrentTCB)
  1232. {
  1233. /* The priority of a task other than the currently
  1234. * running task is being raised. Is the priority being
  1235. * raised above that of the running task? */
  1236. if (uxNewPriority >= pxCurrentTCB->uxPriority)
  1237. {
  1238. xYieldRequired = pdTRUE;
  1239. }
  1240. }
  1241. else
  1242. {
  1243. /* The priority of the running task is being raised,
  1244. * but the running task must already be the highest
  1245. * priority task able to run so no yield is required. */
  1246. }
  1247. }
  1248. else if (pxTCB == pxCurrentTCB)
  1249. {
  1250. /* Setting the priority of the running task down means
  1251. * there may now be another task of higher priority that
  1252. * is ready to execute. */
  1253. xYieldRequired = pdTRUE;
  1254. }
  1255. else
  1256. {
  1257. /* Setting the priority of any other task down does not
  1258. * require a yield as the running task must be above the
  1259. * new priority of the task being modified. */
  1260. }
  1261. /* Remember the ready list the task might be referenced from
  1262. * before its uxPriority member is changed so the
  1263. * taskRESET_READY_PRIORITY() macro can function correctly. */
  1264. uxPriorityUsedOnEntry = pxTCB->uxPriority;
  1265. #if (configUSE_MUTEXES == 1)
  1266. {
  1267. /* Only change the priority being used if the task is not
  1268. * currently using an inherited priority. */
  1269. if (pxTCB->uxBasePriority == pxTCB->uxPriority)
  1270. {
  1271. pxTCB->uxPriority = uxNewPriority;
  1272. }
  1273. /* The base priority gets set whatever. */
  1274. pxTCB->uxBasePriority = uxNewPriority;
  1275. }
  1276. #else /* if (configUSE_MUTEXES == 1) */
  1277. {
  1278. pxTCB->uxPriority = uxNewPriority;
  1279. }
  1280. #endif /* if (configUSE_MUTEXES == 1) */
  1281. /* Only reset the event list item value if the value is not
  1282. * being used for anything else. */
  1283. if ((listGET_LIST_ITEM_VALUE(&(pxTCB->xEventListItem)) & taskEVENT_LIST_ITEM_VALUE_IN_USE) == 0UL)
  1284. {
  1285. listSET_LIST_ITEM_VALUE(&(pxTCB->xEventListItem), ((TickType_t)configMAX_PRIORITIES - (TickType_t)uxNewPriority));
  1286. }
  1287. /* If the task is in the blocked or suspended list we need do
  1288. * nothing more than change its priority variable. However, if
  1289. * the task is in a ready list it needs to be removed and placed
  1290. * in the list appropriate to its new priority. */
  1291. if (listIS_CONTAINED_WITHIN(&(pxReadyTasksLists[uxPriorityUsedOnEntry]), &(pxTCB->xStateListItem)) != pdFALSE)
  1292. {
  1293. /* The task is currently in its ready list - remove before
  1294. * adding it to its new ready list. As we are in a critical
  1295. * section we can do this even if the scheduler is suspended. */
  1296. if (uxListRemove(&(pxTCB->xStateListItem)) == (UBaseType_t)0)
  1297. {
  1298. /* It is known that the task is in its ready list so
  1299. * there is no need to check again and the port level
  1300. * reset macro can be called directly. */
  1301. portRESET_READY_PRIORITY(uxPriorityUsedOnEntry, uxTopReadyPriority);
  1302. }
  1303. prvAddTaskToReadyList(pxTCB);
  1304. }
  1305. if (xYieldRequired != pdFALSE)
  1306. {
  1307. taskYIELD_IF_USING_PREEMPTION();
  1308. }
  1309. /* Remove compiler warning about unused variables when the port
  1310. * optimised task selection is not being used. */
  1311. (void) uxPriorityUsedOnEntry;
  1312. }
  1313. }
  1314. taskEXIT_CRITICAL();
  1315. }
  1316. #endif /* INCLUDE_vTaskPrioritySet */
  1317. #if (INCLUDE_vTaskSuspend == 1)
  1318. void vTaskSuspend(TaskHandle_t xTaskToSuspend)
  1319. {
  1320. TCB_t * pxTCB;
  1321. taskENTER_CRITICAL();
  1322. {
  1323. /* If null is passed in here then it is the running task that is
  1324. * being suspended. */
  1325. pxTCB = prvGetTCBFromHandle(xTaskToSuspend);
  1326. traceTASK_SUSPEND(pxTCB);
  1327. /* Remove task from the ready/delayed list and place in the
  1328. * suspended list. */
  1329. if (uxListRemove(&(pxTCB->xStateListItem)) == (UBaseType_t)0)
  1330. {
  1331. taskRESET_READY_PRIORITY(pxTCB->uxPriority);
  1332. }
  1333. /* Is the task waiting on an event also? */
  1334. if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) != NULL)
  1335. {
  1336. (void) uxListRemove(&(pxTCB->xEventListItem));
  1337. }
  1338. vListInsertEnd(&xSuspendedTaskList, &(pxTCB->xStateListItem));
  1339. #if (configUSE_TASK_NOTIFICATIONS == 1)
  1340. {
  1341. BaseType_t x;
  1342. for (x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++)
  1343. {
  1344. if (pxTCB->ucNotifyState[x] == taskWAITING_NOTIFICATION)
  1345. {
  1346. /* The task was blocked to wait for a notification, but is
  1347. * now suspended, so no notification was received. */
  1348. pxTCB->ucNotifyState[x] = taskNOT_WAITING_NOTIFICATION;
  1349. }
  1350. }
  1351. }
  1352. #endif /* if (configUSE_TASK_NOTIFICATIONS == 1) */
  1353. }
  1354. taskEXIT_CRITICAL();
  1355. if (xSchedulerRunning != pdFALSE)
  1356. {
  1357. /* Reset the next expected unblock time in case it referred to the
  1358. * task that is now in the Suspended state. */
  1359. taskENTER_CRITICAL();
  1360. {
  1361. prvResetNextTaskUnblockTime();
  1362. }
  1363. taskEXIT_CRITICAL();
  1364. }
  1365. if (pxTCB == pxCurrentTCB)
  1366. {
  1367. if (xSchedulerRunning != pdFALSE)
  1368. {
  1369. /* The current task has just been suspended. */
  1370. configASSERT(uxSchedulerSuspended == 0);
  1371. portYIELD_WITHIN_API();
  1372. }
  1373. else
  1374. {
  1375. /* The scheduler is not running, but the task that was pointed
  1376. * to by pxCurrentTCB has just been suspended and pxCurrentTCB
  1377. * must be adjusted to point to a different task. */
  1378. if (listCURRENT_LIST_LENGTH(&xSuspendedTaskList) == uxCurrentNumberOfTasks)
  1379. {
  1380. /* No other tasks are ready, so set pxCurrentTCB back to
  1381. * NULL so when the next task is created pxCurrentTCB will
  1382. * be set to point to it no matter what its relative priority
  1383. * is. */
  1384. pxCurrentTCB = NULL;
  1385. }
  1386. else
  1387. {
  1388. vTaskSwitchContext();
  1389. }
  1390. }
  1391. }
  1392. }
  1393. static BaseType_t prvTaskIsTaskSuspended(const TaskHandle_t xTask)
  1394. {
  1395. BaseType_t xReturn = pdFALSE;
  1396. const TCB_t * const pxTCB = xTask;
  1397. /* Accesses xPendingReadyList so must be called from a critical
  1398. * section. */
  1399. /* It does not make sense to check if the calling task is suspended. */
  1400. configASSERT(xTask);
  1401. /* Is the task being resumed actually in the suspended list? */
  1402. if (listIS_CONTAINED_WITHIN(&xSuspendedTaskList, &(pxTCB->xStateListItem)) != pdFALSE)
  1403. {
  1404. /* Has the task already been resumed from within an ISR? */
  1405. if (listIS_CONTAINED_WITHIN(&xPendingReadyList, &(pxTCB->xEventListItem)) == pdFALSE)
  1406. {
  1407. /* Is it in the suspended list because it is in the Suspended
  1408. * state, or because is is blocked with no timeout? */
  1409. if (listIS_CONTAINED_WITHIN(NULL, &(pxTCB->xEventListItem)) != pdFALSE)
  1410. {
  1411. xReturn = pdTRUE;
  1412. }
  1413. }
  1414. }
  1415. return xReturn;
  1416. }
  1417. void vTaskResume(TaskHandle_t xTaskToResume)
  1418. {
  1419. TCB_t * const pxTCB = xTaskToResume;
  1420. /* It does not make sense to resume the calling task. */
  1421. configASSERT(xTaskToResume);
  1422. /* The parameter cannot be NULL as it is impossible to resume the
  1423. * currently executing task. */
  1424. if ((pxTCB != pxCurrentTCB) && (pxTCB != NULL))
  1425. {
  1426. taskENTER_CRITICAL();
  1427. {
  1428. if (prvTaskIsTaskSuspended(pxTCB) != pdFALSE)
  1429. {
  1430. traceTASK_RESUME(pxTCB);
  1431. /* The ready list can be accessed even if the scheduler is
  1432. * suspended because this is inside a critical section. */
  1433. (void) uxListRemove(&(pxTCB->xStateListItem));
  1434. prvAddTaskToReadyList(pxTCB);
  1435. /* A higher priority task may have just been resumed. */
  1436. if (pxTCB->uxPriority >= pxCurrentTCB->uxPriority)
  1437. {
  1438. /* This yield may not cause the task just resumed to run,
  1439. * but will leave the lists in the correct state for the
  1440. * next yield. */
  1441. taskYIELD_IF_USING_PREEMPTION();
  1442. }
  1443. }
  1444. }
  1445. taskEXIT_CRITICAL();
  1446. }
  1447. }
  1448. #endif /* INCLUDE_vTaskSuspend */
  1449. #if ((INCLUDE_xTaskResumeFromISR == 1) && (INCLUDE_vTaskSuspend == 1))
  1450. BaseType_t xTaskResumeFromISR(TaskHandle_t xTaskToResume)
  1451. {
  1452. BaseType_t xYieldRequired = pdFALSE;
  1453. TCB_t * const pxTCB = xTaskToResume;
  1454. UBaseType_t uxSavedInterruptStatus;
  1455. configASSERT(xTaskToResume);
  1456. /* RTOS ports that support interrupt nesting have the concept of a
  1457. * maximum system call (or maximum API call) interrupt priority.
  1458. * Interrupts that are above the maximum system call priority are keep
  1459. * permanently enabled, even when the RTOS kernel is in a critical section,
  1460. * but cannot make any calls to FreeRTOS API functions. If configASSERT()
  1461. * is defined in FreeRTOSConfig.h then
  1462. * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
  1463. * failure if a FreeRTOS API function is called from an interrupt that has
  1464. * been assigned a priority above the configured maximum system call
  1465. * priority. Only FreeRTOS functions that end in FromISR can be called
  1466. * from interrupts that have been assigned a priority at or (logically)
  1467. * below the maximum system call interrupt priority. FreeRTOS maintains a
  1468. * separate interrupt safe API to ensure interrupt entry is as fast and as
  1469. * simple as possible. More information (albeit Cortex-M specific) is
  1470. * provided on the following link:
  1471. * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
  1472. portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
  1473. uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
  1474. {
  1475. if (prvTaskIsTaskSuspended(pxTCB) != pdFALSE)
  1476. {
  1477. traceTASK_RESUME_FROM_ISR(pxTCB);
  1478. /* Check the ready lists can be accessed. */
  1479. if (uxSchedulerSuspended == (UBaseType_t)pdFALSE)
  1480. {
  1481. /* Ready lists can be accessed so move the task from the
  1482. * suspended list to the ready list directly. */
  1483. if (pxTCB->uxPriority >= pxCurrentTCB->uxPriority)
  1484. {
  1485. xYieldRequired = pdTRUE;
  1486. /* Mark that a yield is pending in case the user is not
  1487. * using the return value to initiate a context switch
  1488. * from the ISR using portYIELD_FROM_ISR. */
  1489. xYieldPending = pdTRUE;
  1490. }
  1491. (void)uxListRemove(&(pxTCB->xStateListItem));
  1492. prvAddTaskToReadyList(pxTCB);
  1493. }
  1494. else
  1495. {
  1496. /* The delayed or ready lists cannot be accessed so the task
  1497. * is held in the pending ready list until the scheduler is
  1498. * unsuspended. */
  1499. vListInsertEnd(&(xPendingReadyList), &(pxTCB->xEventListItem));
  1500. }
  1501. }
  1502. }
  1503. portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
  1504. return xYieldRequired;
  1505. }
  1506. #endif /* ((INCLUDE_xTaskResumeFromISR == 1) && (INCLUDE_vTaskSuspend == 1)) */
  1507. void vTaskStartScheduler(void)
  1508. {
  1509. BaseType_t xReturn;
  1510. /**
  1511. * 创建系统空闲任务.
  1512. */
  1513. xReturn = xTaskCreate(prvIdleTask,
  1514. configIDLE_TASK_NAME,
  1515. configMINIMAL_STACK_SIZE,
  1516. (void *) NULL,
  1517. portPRIVILEGE_BIT, /* 任务优先级最低 */
  1518. &xIdleTaskHandle);
  1519. #if (configUSE_TIMERS == 1)
  1520. {
  1521. if (xReturn == pdPASS)
  1522. {
  1523. /* 创建软件定时器处理任务 */
  1524. xReturn = xTimerCreateTimerTask();
  1525. }
  1526. }
  1527. #endif
  1528. if (xReturn == pdPASS)
  1529. {
  1530. /* Interrupts are turned off here, to ensure a tick does not occur
  1531. * before or during the call to xPortStartScheduler(). The stacks of
  1532. * the created tasks contain a status word with interrupts switched on
  1533. * so interrupts will automatically get re-enabled when the first task
  1534. * starts to run. */
  1535. portDISABLE_INTERRUPTS();
  1536. #if ((configUSE_NEWLIB_REENTRANT == 1) || (configUSE_C_RUNTIME_TLS_SUPPORT == 1))
  1537. {
  1538. /* Switch C-Runtime's TLS Block to point to the TLS
  1539. * block specific to the task that will run first. */
  1540. configSET_TLS_BLOCK(pxCurrentTCB->xTLSBlock);
  1541. }
  1542. #endif
  1543. xNextTaskUnblockTime = portMAX_DELAY;
  1544. /* 调度器开始运行 */
  1545. xSchedulerRunning = pdTRUE;
  1546. /* 初始化系统tick值 */
  1547. xTickCount = (TickType_t) configINITIAL_TICK_COUNT;
  1548. /* If configGENERATE_RUN_TIME_STATS is defined then the following
  1549. * macro must be defined to configure the timer/counter used to generate
  1550. * the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS
  1551. * is set to 0 and the following line fails to build then ensure you do not
  1552. * have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your
  1553. * FreeRTOSConfig.h file. */
  1554. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS();
  1555. traceTASK_SWITCHED_IN();
  1556. /**
  1557. * Setting up the timer tick is hardware specific and thus in the
  1558. * portable interface.
  1559. * 初始化system tick定时器
  1560. */
  1561. xPortStartScheduler();
  1562. /* In most cases, xPortStartScheduler() will not return. If it
  1563. * returns pdTRUE then there was not enough heap memory available
  1564. * to create either the Idle or the Timer task. If it returned
  1565. * pdFALSE, then the application called xTaskEndScheduler().
  1566. * Most ports don't implement xTaskEndScheduler() as there is
  1567. * nothing to return to. */
  1568. }
  1569. else
  1570. {
  1571. /* This line will only be reached if the kernel could not be started,
  1572. * because there was not enough FreeRTOS heap to create the idle task
  1573. * or the timer task. */
  1574. configASSERT(xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY);
  1575. }
  1576. /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0,
  1577. * meaning xIdleTaskHandle is not used anywhere else. */
  1578. (void) xIdleTaskHandle;
  1579. /* OpenOCD makes use of uxTopUsedPriority for thread debugging. Prevent uxTopUsedPriority
  1580. * from getting optimized out as it is no longer used by the kernel. */
  1581. (void) uxTopUsedPriority;
  1582. }
  1583. void vTaskEndScheduler(void)
  1584. {
  1585. /* Stop the scheduler interrupts and call the portable scheduler end
  1586. * routine so the original ISRs can be restored if necessary. The port
  1587. * layer must ensure interrupts enable bit is left in the correct state. */
  1588. portDISABLE_INTERRUPTS();
  1589. xSchedulerRunning = pdFALSE;
  1590. vPortEndScheduler();
  1591. }
  1592. /**
  1593. * 挂起调度器
  1594. */
  1595. void vTaskSuspendAll(void)
  1596. {
  1597. /* A critical section is not required as the variable is of type
  1598. * BaseType_t. Please read Richard Barry's reply in the following link to a
  1599. * post in the FreeRTOS support forum before reporting this as a bug! -
  1600. * https://goo.gl/wu4acr */
  1601. /* portSOFTWARE_BARRIER() is only implemented for emulated/simulated ports that
  1602. * do not otherwise exhibit real time behaviour. */
  1603. portSOFTWARE_BARRIER();
  1604. /* The scheduler is suspended if uxSchedulerSuspended is non-zero. An increment
  1605. * is used to allow calls to vTaskSuspendAll() to nest. */
  1606. ++uxSchedulerSuspended;
  1607. /* Enforces ordering for ports and optimised compilers that may otherwise place
  1608. * the above increment elsewhere. */
  1609. portMEMORY_BARRIER();
  1610. }
  1611. #if (configUSE_TICKLESS_IDLE != 0)
  1612. /* 计算系统进入低功耗模式的时长 */
  1613. static TickType_t prvGetExpectedIdleTime(void)
  1614. {
  1615. TickType_t xReturn;
  1616. UBaseType_t uxHigherPriorityReadyTasks = pdFALSE;
  1617. /* uxHigherPriorityReadyTasks takes care of the case where
  1618. * configUSE_PREEMPTION is 0, so there may be tasks above the idle priority
  1619. * task that are in the Ready state, even though the idle task is
  1620. * running. */
  1621. #if (configUSE_PORT_OPTIMISED_TASK_SELECTION == 0)
  1622. {
  1623. if (uxTopReadyPriority > tskIDLE_PRIORITY)
  1624. {
  1625. uxHigherPriorityReadyTasks = pdTRUE;
  1626. }
  1627. }
  1628. #else
  1629. {
  1630. const UBaseType_t uxLeastSignificantBit = (UBaseType_t) 0x01;
  1631. /* When port optimised task selection is used the uxTopReadyPriority
  1632. * variable is used as a bit map. If bits other than the least
  1633. * significant bit are set then there are tasks that have a priority
  1634. * above the idle priority that are in the Ready state. This takes
  1635. * care of the case where the co-operative scheduler is in use. */
  1636. if (uxTopReadyPriority > uxLeastSignificantBit)
  1637. {
  1638. uxHigherPriorityReadyTasks = pdTRUE;
  1639. }
  1640. }
  1641. #endif
  1642. /* 有其他任务在运行,则不能进入低功耗 */
  1643. if (pxCurrentTCB->uxPriority > tskIDLE_PRIORITY)
  1644. {
  1645. xReturn = 0;
  1646. }
  1647. else if (listCURRENT_LIST_LENGTH(&(pxReadyTasksLists[tskIDLE_PRIORITY])) > 1)
  1648. {
  1649. /* There are other idle priority tasks in the ready state. If
  1650. * time slicing is used then the very next tick interrupt must be
  1651. * processed. */
  1652. xReturn = 0;
  1653. }
  1654. else if (uxHigherPriorityReadyTasks != pdFALSE)
  1655. {
  1656. /* There are tasks in the Ready state that have a priority above the
  1657. * idle priority. This path can only be reached if
  1658. * configUSE_PREEMPTION is 0. */
  1659. xReturn = 0;
  1660. }
  1661. else
  1662. {
  1663. /* 当系统只有空闲任务时,计算出系统可以进入低功耗模式的时长 */
  1664. xReturn = xNextTaskUnblockTime - xTickCount;
  1665. }
  1666. return xReturn;
  1667. }
  1668. #endif
  1669. /**
  1670. * 恢复调度器的运行
  1671. */
  1672. BaseType_t xTaskResumeAll(void)
  1673. {
  1674. TCB_t * pxTCB = NULL;
  1675. BaseType_t xAlreadyYielded = pdFALSE;
  1676. /* If uxSchedulerSuspended is zero then this function does not match a
  1677. * previous call to vTaskSuspendAll(). */
  1678. configASSERT(uxSchedulerSuspended);
  1679. /* It is possible that an ISR caused a task to be removed from an event
  1680. * list while the scheduler was suspended. If this was the case then the
  1681. * removed task will have been added to the xPendingReadyList. Once the
  1682. * scheduler has been resumed it is safe to move all the pending ready
  1683. * tasks from this list into their appropriate ready list. */
  1684. taskENTER_CRITICAL();
  1685. {
  1686. --uxSchedulerSuspended;
  1687. /* 恢复调度器的执行 */
  1688. if (uxSchedulerSuspended == (UBaseType_t)pdFALSE)
  1689. {
  1690. if (uxCurrentNumberOfTasks > (UBaseType_t)0U)
  1691. {
  1692. /**
  1693. * Move any readied tasks from the pending list into the
  1694. * appropriate ready list.
  1695. * 等待调度任务队列不为空
  1696. */
  1697. while (listLIST_IS_EMPTY(&xPendingReadyList) == pdFALSE)
  1698. {
  1699. /* 选择优先级最高的任务 */
  1700. pxTCB = listGET_OWNER_OF_HEAD_ENTRY((&xPendingReadyList));
  1701. listREMOVE_ITEM(&(pxTCB->xEventListItem));
  1702. portMEMORY_BARRIER();
  1703. listREMOVE_ITEM(&(pxTCB->xStateListItem));
  1704. /* 加入到就绪队列 */
  1705. prvAddTaskToReadyList(pxTCB);
  1706. /**
  1707. * If the moved task has a priority higher than or equal to
  1708. * the current task then a yield must be performed.
  1709. * pxTCB的优先级大于当前正在运行任务的优先级,当前运行任务可以
  1710. * 被抢占
  1711. */
  1712. if (pxTCB->uxPriority >= pxCurrentTCB->uxPriority)
  1713. {
  1714. xYieldPending = pdTRUE;
  1715. }
  1716. }
  1717. if (pxTCB != NULL)
  1718. {
  1719. /* A task was unblocked while the scheduler was suspended,
  1720. * which may have prevented the next unblock time from being
  1721. * re-calculated, in which case re-calculate it now. Mainly
  1722. * important for low power tickless implementations, where
  1723. * this can prevent an unnecessary exit from low power
  1724. * state. */
  1725. prvResetNextTaskUnblockTime();
  1726. }
  1727. /**
  1728. * If any ticks occurred while the scheduler was suspended then
  1729. * they should be processed now. This ensures the tick count does
  1730. * not slip, and that any delayed tasks are resumed at the correct
  1731. * time.
  1732. * 系统调度器被挂起后,产生时钟中断,会累计xPendedTicks的值,其实就是累计
  1733. * 错过调度的次数
  1734. */
  1735. {
  1736. TickType_t xPendedCounts = xPendedTicks;
  1737. /* 处理由于调度器被挂起后,错过的调度次数 */
  1738. if (xPendedCounts > (TickType_t)0U)
  1739. {
  1740. do
  1741. {
  1742. if (xTaskIncrementTick() == pdTRUE)
  1743. {
  1744. xYieldPending = pdTRUE;
  1745. }
  1746. --xPendedCounts;
  1747. } while (xPendedCounts > (TickType_t)0U);
  1748. xPendedTicks = 0;
  1749. }
  1750. }
  1751. /* 任务需要调度 */
  1752. if (xYieldPending == pdTRUE)
  1753. {
  1754. /* 开启抢占的情况下,当前任务可以被抢占 */
  1755. #if (configUSE_PREEMPTION != 0)
  1756. {
  1757. xAlreadyYielded = pdTRUE;
  1758. }
  1759. #endif
  1760. taskYIELD_IF_USING_PREEMPTION();
  1761. }
  1762. }
  1763. }
  1764. }
  1765. taskEXIT_CRITICAL();
  1766. return xAlreadyYielded;
  1767. }
  1768. TickType_t xTaskGetTickCount(void)
  1769. {
  1770. TickType_t xTicks;
  1771. /* Critical section required if running on a 16 bit processor. */
  1772. portTICK_TYPE_ENTER_CRITICAL();
  1773. {
  1774. xTicks = xTickCount;
  1775. }
  1776. portTICK_TYPE_EXIT_CRITICAL();
  1777. return xTicks;
  1778. }
  1779. TickType_t xTaskGetTickCountFromISR(void)
  1780. {
  1781. TickType_t xReturn;
  1782. UBaseType_t uxSavedInterruptStatus;
  1783. /* RTOS ports that support interrupt nesting have the concept of a maximum
  1784. * system call (or maximum API call) interrupt priority. Interrupts that are
  1785. * above the maximum system call priority are kept permanently enabled, even
  1786. * when the RTOS kernel is in a critical section, but cannot make any calls to
  1787. * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
  1788. * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
  1789. * failure if a FreeRTOS API function is called from an interrupt that has been
  1790. * assigned a priority above the configured maximum system call priority.
  1791. * Only FreeRTOS functions that end in FromISR can be called from interrupts
  1792. * that have been assigned a priority at or (logically) below the maximum
  1793. * system call interrupt priority. FreeRTOS maintains a separate interrupt
  1794. * safe API to ensure interrupt entry is as fast and as simple as possible.
  1795. * More information (albeit Cortex-M specific) is provided on the following
  1796. * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
  1797. portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
  1798. uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR();
  1799. {
  1800. xReturn = xTickCount;
  1801. }
  1802. portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
  1803. return xReturn;
  1804. }
  1805. UBaseType_t uxTaskGetNumberOfTasks(void)
  1806. {
  1807. /* A critical section is not required because the variables are of type
  1808. * BaseType_t. */
  1809. return uxCurrentNumberOfTasks;
  1810. }
  1811. char *pcTaskGetName(TaskHandle_t xTaskToQuery)
  1812. {
  1813. TCB_t * pxTCB;
  1814. /* If null is passed in here then the name of the calling task is being
  1815. * queried. */
  1816. pxTCB = prvGetTCBFromHandle(xTaskToQuery);
  1817. configASSERT(pxTCB);
  1818. return &(pxTCB->pcTaskName[0]);
  1819. }
  1820. #if (INCLUDE_xTaskGetHandle == 1)
  1821. static TCB_t *prvSearchForNameWithinSingleList(List_t * pxList, const char pcNameToQuery[])
  1822. {
  1823. TCB_t * pxNextTCB;
  1824. TCB_t * pxFirstTCB;
  1825. TCB_t * pxReturn = NULL;
  1826. UBaseType_t x;
  1827. char cNextChar;
  1828. BaseType_t xBreakLoop;
  1829. /* This function is called with the scheduler suspended. */
  1830. if (listCURRENT_LIST_LENGTH(pxList) > (UBaseType_t)0)
  1831. {
  1832. listGET_OWNER_OF_NEXT_ENTRY(pxFirstTCB, pxList);
  1833. do
  1834. {
  1835. listGET_OWNER_OF_NEXT_ENTRY(pxNextTCB, pxList);
  1836. /* Check each character in the name looking for a match or
  1837. * mismatch. */
  1838. xBreakLoop = pdFALSE;
  1839. for (x = (UBaseType_t) 0; x < (UBaseType_t) configMAX_TASK_NAME_LEN; x++)
  1840. {
  1841. cNextChar = pxNextTCB->pcTaskName[x];
  1842. if (cNextChar != pcNameToQuery[x])
  1843. {
  1844. /* Characters didn't match. */
  1845. xBreakLoop = pdTRUE;
  1846. }
  1847. else if (cNextChar == (char)0x00)
  1848. {
  1849. /* Both strings terminated, a match must have been
  1850. * found. */
  1851. pxReturn = pxNextTCB;
  1852. xBreakLoop = pdTRUE;
  1853. }
  1854. if (xBreakLoop != pdFALSE)
  1855. {
  1856. break;
  1857. }
  1858. }
  1859. if (pxReturn != NULL)
  1860. {
  1861. /* The handle has been found. */
  1862. break;
  1863. }
  1864. } while (pxNextTCB != pxFirstTCB);
  1865. }
  1866. return pxReturn;
  1867. }
  1868. #endif /* INCLUDE_xTaskGetHandle */
  1869. #if (INCLUDE_xTaskGetHandle == 1)
  1870. TaskHandle_t xTaskGetHandle(const char * pcNameToQuery)
  1871. {
  1872. UBaseType_t uxQueue = configMAX_PRIORITIES;
  1873. TCB_t * pxTCB;
  1874. /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */
  1875. configASSERT(strlen(pcNameToQuery) < configMAX_TASK_NAME_LEN);
  1876. vTaskSuspendAll();
  1877. {
  1878. /* Search the ready lists. */
  1879. do
  1880. {
  1881. uxQueue--;
  1882. pxTCB = prvSearchForNameWithinSingleList((List_t *) &(pxReadyTasksLists[uxQueue]), pcNameToQuery);
  1883. if (pxTCB != NULL)
  1884. {
  1885. /* Found the handle. */
  1886. break;
  1887. }
  1888. } while (uxQueue > (UBaseType_t)tskIDLE_PRIORITY);
  1889. /* Search the delayed lists. */
  1890. if (pxTCB == NULL)
  1891. {
  1892. pxTCB = prvSearchForNameWithinSingleList((List_t *) pxDelayedTaskList, pcNameToQuery);
  1893. }
  1894. if (pxTCB == NULL)
  1895. {
  1896. pxTCB = prvSearchForNameWithinSingleList((List_t *) pxOverflowDelayedTaskList, pcNameToQuery);
  1897. }
  1898. #if (INCLUDE_vTaskSuspend == 1)
  1899. {
  1900. if (pxTCB == NULL)
  1901. {
  1902. /* Search the suspended list. */
  1903. pxTCB = prvSearchForNameWithinSingleList(&xSuspendedTaskList, pcNameToQuery);
  1904. }
  1905. }
  1906. #endif
  1907. #if (INCLUDE_vTaskDelete == 1)
  1908. {
  1909. if (pxTCB == NULL)
  1910. {
  1911. /* Search the deleted list. */
  1912. pxTCB = prvSearchForNameWithinSingleList(&xTasksWaitingTermination, pcNameToQuery);
  1913. }
  1914. }
  1915. #endif
  1916. }
  1917. (void) xTaskResumeAll();
  1918. return pxTCB;
  1919. }
  1920. #endif /* INCLUDE_xTaskGetHandle */
  1921. #if (configUSE_TRACE_FACILITY == 1)
  1922. UBaseType_t uxTaskGetSystemState(TaskStatus_t * const pxTaskStatusArray,
  1923. const UBaseType_t uxArraySize,
  1924. configRUN_TIME_COUNTER_TYPE * const pulTotalRunTime)
  1925. {
  1926. UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES;
  1927. vTaskSuspendAll();
  1928. {
  1929. /* Is there a space in the array for each task in the system? */
  1930. if (uxArraySize >= uxCurrentNumberOfTasks)
  1931. {
  1932. /* Fill in an TaskStatus_t structure with information on each
  1933. * task in the Ready state. */
  1934. do
  1935. {
  1936. uxQueue--;
  1937. uxTask += prvListTasksWithinSingleList(&(pxTaskStatusArray[uxTask]), &(pxReadyTasksLists[uxQueue]), eReady);
  1938. } while (uxQueue > (UBaseType_t) tskIDLE_PRIORITY); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
  1939. /* Fill in an TaskStatus_t structure with information on each
  1940. * task in the Blocked state. */
  1941. uxTask += prvListTasksWithinSingleList(&(pxTaskStatusArray[uxTask]), (List_t *) pxDelayedTaskList, eBlocked);
  1942. uxTask += prvListTasksWithinSingleList(&(pxTaskStatusArray[uxTask]), (List_t *) pxOverflowDelayedTaskList, eBlocked);
  1943. #if (INCLUDE_vTaskDelete == 1)
  1944. {
  1945. /* Fill in an TaskStatus_t structure with information on
  1946. * each task that has been deleted but not yet cleaned up. */
  1947. uxTask += prvListTasksWithinSingleList(&(pxTaskStatusArray[uxTask]), &xTasksWaitingTermination, eDeleted);
  1948. }
  1949. #endif
  1950. #if (INCLUDE_vTaskSuspend == 1)
  1951. {
  1952. /* Fill in an TaskStatus_t structure with information on
  1953. * each task in the Suspended state. */
  1954. uxTask += prvListTasksWithinSingleList(&(pxTaskStatusArray[uxTask]), &xSuspendedTaskList, eSuspended);
  1955. }
  1956. #endif
  1957. #if (configGENERATE_RUN_TIME_STATS == 1)
  1958. {
  1959. if (pulTotalRunTime != NULL)
  1960. {
  1961. #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
  1962. portALT_GET_RUN_TIME_COUNTER_VALUE((*pulTotalRunTime));
  1963. #else
  1964. *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
  1965. #endif
  1966. }
  1967. }
  1968. #else /* if (configGENERATE_RUN_TIME_STATS == 1) */
  1969. {
  1970. if (pulTotalRunTime != NULL)
  1971. {
  1972. *pulTotalRunTime = 0;
  1973. }
  1974. }
  1975. #endif /* if (configGENERATE_RUN_TIME_STATS == 1) */
  1976. }
  1977. }
  1978. (void) xTaskResumeAll();
  1979. return uxTask;
  1980. }
  1981. #endif /* configUSE_TRACE_FACILITY */
  1982. #if (INCLUDE_xTaskGetIdleTaskHandle == 1)
  1983. TaskHandle_t xTaskGetIdleTaskHandle(void)
  1984. {
  1985. /* If xTaskGetIdleTaskHandle() is called before the scheduler has been
  1986. * started, then xIdleTaskHandle will be NULL. */
  1987. configASSERT((xIdleTaskHandle != NULL));
  1988. return xIdleTaskHandle;
  1989. }
  1990. #endif
  1991. #if (configUSE_TICKLESS_IDLE != 0)
  1992. void vTaskStepTick(TickType_t xTicksToJump)
  1993. {
  1994. /* Correct the tick count value after a period during which the tick
  1995. * was suppressed. Note this does *not* call the tick hook function for
  1996. * each stepped tick. */
  1997. configASSERT((xTickCount + xTicksToJump) <= xNextTaskUnblockTime);
  1998. if ((xTickCount + xTicksToJump) == xNextTaskUnblockTime)
  1999. {
  2000. /* Arrange for xTickCount to reach xNextTaskUnblockTime in
  2001. * xTaskIncrementTick() when the scheduler resumes. This ensures
  2002. * that any delayed tasks are resumed at the correct time. */
  2003. configASSERT(uxSchedulerSuspended);
  2004. configASSERT(xTicksToJump != (TickType_t)0);
  2005. /* Prevent the tick interrupt modifying xPendedTicks simultaneously. */
  2006. taskENTER_CRITICAL();
  2007. {
  2008. xPendedTicks++;
  2009. }
  2010. taskEXIT_CRITICAL();
  2011. xTicksToJump--;
  2012. }
  2013. xTickCount += xTicksToJump;
  2014. traceINCREASE_TICK_COUNT(xTicksToJump);
  2015. }
  2016. #endif
  2017. BaseType_t xTaskCatchUpTicks(TickType_t xTicksToCatchUp)
  2018. {
  2019. BaseType_t xYieldOccurred;
  2020. /* Must not be called with the scheduler suspended as the implementation
  2021. * relies on xPendedTicks being wound down to 0 in xTaskResumeAll(). */
  2022. configASSERT(uxSchedulerSuspended == 0);
  2023. /* Use xPendedTicks to mimic xTicksToCatchUp number of ticks occurring when
  2024. * the scheduler is suspended so the ticks are executed in xTaskResumeAll(). */
  2025. vTaskSuspendAll();
  2026. /* Prevent the tick interrupt modifying xPendedTicks simultaneously. */
  2027. taskENTER_CRITICAL();
  2028. {
  2029. xPendedTicks += xTicksToCatchUp;
  2030. }
  2031. taskEXIT_CRITICAL();
  2032. xYieldOccurred = xTaskResumeAll();
  2033. return xYieldOccurred;
  2034. }
  2035. #if (INCLUDE_xTaskAbortDelay == 1)
  2036. BaseType_t xTaskAbortDelay(TaskHandle_t xTask)
  2037. {
  2038. TCB_t * pxTCB = xTask;
  2039. BaseType_t xReturn;
  2040. configASSERT(pxTCB);
  2041. vTaskSuspendAll();
  2042. {
  2043. /* A task can only be prematurely removed from the Blocked state if
  2044. * it is actually in the Blocked state. */
  2045. if (eTaskGetState(xTask) == eBlocked)
  2046. {
  2047. xReturn = pdPASS;
  2048. /* Remove the reference to the task from the blocked list. An
  2049. * interrupt won't touch the xStateListItem because the
  2050. * scheduler is suspended. */
  2051. (void) uxListRemove(&(pxTCB->xStateListItem));
  2052. /* Is the task waiting on an event also? If so remove it from
  2053. * the event list too. Interrupts can touch the event list item,
  2054. * even though the scheduler is suspended, so a critical section
  2055. * is used. */
  2056. taskENTER_CRITICAL();
  2057. {
  2058. if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) != NULL)
  2059. {
  2060. (void) uxListRemove(&(pxTCB->xEventListItem));
  2061. /* This lets the task know it was forcibly removed from the
  2062. * blocked state so it should not re-evaluate its block time and
  2063. * then block again. */
  2064. pxTCB->ucDelayAborted = pdTRUE;
  2065. }
  2066. }
  2067. taskEXIT_CRITICAL();
  2068. /* Place the unblocked task into the appropriate ready list. */
  2069. prvAddTaskToReadyList(pxTCB);
  2070. /* A task being unblocked cannot cause an immediate context
  2071. * switch if preemption is turned off. */
  2072. #if (configUSE_PREEMPTION == 1)
  2073. {
  2074. /* Preemption is on, but a context switch should only be
  2075. * performed if the unblocked task has a priority that is
  2076. * higher than the currently executing task. */
  2077. if (pxTCB->uxPriority > pxCurrentTCB->uxPriority)
  2078. {
  2079. /* Pend the yield to be performed when the scheduler
  2080. * is unsuspended. */
  2081. xYieldPending = pdTRUE;
  2082. }
  2083. }
  2084. #endif /* configUSE_PREEMPTION */
  2085. }
  2086. else
  2087. {
  2088. xReturn = pdFAIL;
  2089. }
  2090. }
  2091. (void) xTaskResumeAll();
  2092. return xReturn;
  2093. }
  2094. #endif /* INCLUDE_xTaskAbortDelay */
  2095. BaseType_t xTaskIncrementTick(void)
  2096. {
  2097. TCB_t * pxTCB;
  2098. TickType_t xItemValue;
  2099. BaseType_t xSwitchRequired = pdFALSE;
  2100. /**
  2101. * Called by the portable layer each time a tick interrupt occurs.
  2102. * Increments the tick then checks to see if the new tick value will cause any
  2103. * tasks to be unblocked.
  2104. */
  2105. traceTASK_INCREMENT_TICK(xTickCount);
  2106. /* 调度器如果没有被挂起 */
  2107. if (uxSchedulerSuspended != (UBaseType_t)pdTRUE) {
  2108. /*
  2109. * Minor optimisation. The tick count cannot change in this
  2110. * block.
  2111. * 累加系统时钟数
  2112. */
  2113. const TickType_t xConstTickCount = xTickCount + (TickType_t)1;
  2114. /* Increment the RTOS tick, switching the delayed and overflowed
  2115. * delayed lists if it wraps to 0. */
  2116. xTickCount = xConstTickCount;
  2117. /* 系统时钟计数器发生溢出 */
  2118. if (xConstTickCount == (TickType_t)0U)
  2119. {
  2120. taskSWITCH_DELAYED_LISTS();
  2121. }
  2122. /* See if this tick has made a timeout expire. Tasks are stored in
  2123. * the queue in the order of their wake time - meaning once one task
  2124. * has been found whose block time has not expired there is no need to
  2125. * look any further down the list.
  2126. * 遇见下一个任务超时的时间点
  2127. */
  2128. if (xConstTickCount >= xNextTaskUnblockTime) {
  2129. for (; ;)
  2130. {
  2131. /* 延迟队列为空 */
  2132. if (listLIST_IS_EMPTY(pxDelayedTaskList) != pdFALSE)
  2133. {
  2134. /* The delayed list is empty. Set xNextTaskUnblockTime
  2135. * to the maximum possible value so it is extremely
  2136. * unlikely that the
  2137. * if (xTickCount >= xNextTaskUnblockTime) test will pass
  2138. * next time through.
  2139. * 设置下一个任务超时的时间为无限大
  2140. */
  2141. xNextTaskUnblockTime = portMAX_DELAY;
  2142. break;
  2143. }
  2144. else
  2145. {
  2146. /* The delayed list is not empty, get the value of the
  2147. * item at the head of the delayed list. This is the time
  2148. * at which the task at the head of the delayed list must
  2149. * be removed from the Blocked state.
  2150. * 链表头部的任务,超时时间值是最小的
  2151. */
  2152. pxTCB = listGET_OWNER_OF_HEAD_ENTRY(pxDelayedTaskList);
  2153. /* 获取任务的超时时间值 */
  2154. xItemValue = listGET_LIST_ITEM_VALUE(&(pxTCB->xStateListItem));
  2155. /* 没有超时 */
  2156. if (xConstTickCount < xItemValue)
  2157. {
  2158. /* It is not time to unblock this item yet, but the
  2159. * item value is the time at which the task at the head
  2160. * of the blocked list must be removed from the Blocked
  2161. * state - so record the item value in
  2162. * xNextTaskUnblockTime. */
  2163. xNextTaskUnblockTime = xItemValue;
  2164. break;
  2165. }
  2166. /**
  2167. * It is time to remove the item from the Blocked state.
  2168. * 任务从延迟队列中删除
  2169. */
  2170. listREMOVE_ITEM(&(pxTCB->xStateListItem));
  2171. /* Is the task waiting on an event also? If so remove
  2172. * it from the event list. */
  2173. if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) != NULL)
  2174. {
  2175. listREMOVE_ITEM(&(pxTCB->xEventListItem));
  2176. }
  2177. /**
  2178. * Place the unblocked task into the appropriate ready
  2179. * list.
  2180. * 任务加入到就绪队列
  2181. */
  2182. prvAddTaskToReadyList(pxTCB);
  2183. /* A task being unblocked cannot cause an immediate
  2184. * context switch if preemption is turned off. */
  2185. #if (configUSE_PREEMPTION == 1)
  2186. {
  2187. /* Preemption is on, but a context switch should
  2188. * only be performed if the unblocked task's
  2189. * priority is higher than the currently executing
  2190. * task.
  2191. * The case of equal priority tasks sharing
  2192. * processing time (which happens when both
  2193. * preemption and time slicing are on) is
  2194. * handled below.
  2195. * 当前任务可以被抢占
  2196. */
  2197. if (pxTCB->uxPriority > pxCurrentTCB->uxPriority)
  2198. {
  2199. xSwitchRequired = pdTRUE;
  2200. }
  2201. }
  2202. #endif
  2203. }
  2204. }
  2205. }
  2206. /**
  2207. * Tasks of equal priority to the currently running task will share
  2208. * processing time (time slice) if preemption is on, and the application
  2209. * writer has not explicitly turned time slicing off.
  2210. * 开启抢占情况下,相同优先级的任务,分时间片轮转
  2211. */
  2212. #if ((configUSE_PREEMPTION == 1) && (configUSE_TIME_SLICING == 1))
  2213. {
  2214. /* 存在与pxCurrentTCB相同优先级的待运行任务 */
  2215. if (listCURRENT_LIST_LENGTH(&(pxReadyTasksLists[pxCurrentTCB->uxPriority])) > (UBaseType_t)1)
  2216. {
  2217. xSwitchRequired = pdTRUE;
  2218. }
  2219. }
  2220. #endif
  2221. #if (configUSE_TICK_HOOK == 1)
  2222. {
  2223. /* Guard against the tick hook being called when the pended tick
  2224. * count is being unwound (when the scheduler is being unlocked). */
  2225. if (xPendedTicks == (TickType_t)0)
  2226. {
  2227. vApplicationTickHook();
  2228. }
  2229. }
  2230. #endif
  2231. /* 开启抢占情况下 */
  2232. #if (configUSE_PREEMPTION == 1)
  2233. {
  2234. /* 存在高优先级的任务,触发抢占 */
  2235. if (xYieldPending != pdFALSE)
  2236. {
  2237. xSwitchRequired = pdTRUE;
  2238. }
  2239. }
  2240. #endif /* configUSE_PREEMPTION */
  2241. } else { /* 调度器处于挂起状态 */
  2242. ++xPendedTicks;
  2243. /* The tick hook gets called at regular intervals, even if the
  2244. * scheduler is locked. */
  2245. #if (configUSE_TICK_HOOK == 1)
  2246. {
  2247. vApplicationTickHook();
  2248. }
  2249. #endif
  2250. }
  2251. return xSwitchRequired;
  2252. }
  2253. #if (configUSE_APPLICATION_TASK_TAG == 1)
  2254. void vTaskSetApplicationTaskTag(TaskHandle_t xTask,
  2255. TaskHookFunction_t pxHookFunction)
  2256. {
  2257. TCB_t * xTCB;
  2258. /* If xTask is NULL then it is the task hook of the calling task that is
  2259. * getting set. */
  2260. if (xTask == NULL)
  2261. {
  2262. xTCB = (TCB_t *) pxCurrentTCB;
  2263. }
  2264. else
  2265. {
  2266. xTCB = xTask;
  2267. }
  2268. /* Save the hook function in the TCB. A critical section is required as
  2269. * the value can be accessed from an interrupt. */
  2270. taskENTER_CRITICAL();
  2271. {
  2272. xTCB->pxTaskTag = pxHookFunction;
  2273. }
  2274. taskEXIT_CRITICAL();
  2275. }
  2276. TaskHookFunction_t xTaskGetApplicationTaskTag(TaskHandle_t xTask)
  2277. {
  2278. TCB_t * pxTCB;
  2279. TaskHookFunction_t xReturn;
  2280. /* If xTask is NULL then set the calling task's hook. */
  2281. pxTCB = prvGetTCBFromHandle(xTask);
  2282. /* Save the hook function in the TCB. A critical section is required as
  2283. * the value can be accessed from an interrupt. */
  2284. taskENTER_CRITICAL();
  2285. {
  2286. xReturn = pxTCB->pxTaskTag;
  2287. }
  2288. taskEXIT_CRITICAL();
  2289. return xReturn;
  2290. }
  2291. TaskHookFunction_t xTaskGetApplicationTaskTagFromISR(TaskHandle_t xTask)
  2292. {
  2293. TCB_t * pxTCB;
  2294. TaskHookFunction_t xReturn;
  2295. UBaseType_t uxSavedInterruptStatus;
  2296. /* If xTask is NULL then set the calling task's hook. */
  2297. pxTCB = prvGetTCBFromHandle(xTask);
  2298. /* Save the hook function in the TCB. A critical section is required as
  2299. * the value can be accessed from an interrupt. */
  2300. uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
  2301. {
  2302. xReturn = pxTCB->pxTaskTag;
  2303. }
  2304. portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
  2305. return xReturn;
  2306. }
  2307. BaseType_t xTaskCallApplicationTaskHook(TaskHandle_t xTask,
  2308. void * pvParameter)
  2309. {
  2310. TCB_t * xTCB;
  2311. BaseType_t xReturn;
  2312. /* If xTask is NULL then we are calling our own task hook. */
  2313. if (xTask == NULL)
  2314. {
  2315. xTCB = pxCurrentTCB;
  2316. }
  2317. else
  2318. {
  2319. xTCB = xTask;
  2320. }
  2321. if (xTCB->pxTaskTag != NULL)
  2322. {
  2323. xReturn = xTCB->pxTaskTag(pvParameter);
  2324. }
  2325. else
  2326. {
  2327. xReturn = pdFAIL;
  2328. }
  2329. return xReturn;
  2330. }
  2331. #endif /* configUSE_APPLICATION_TASK_TAG */
  2332. void vTaskSwitchContext(void)
  2333. {
  2334. /* 调度器处于挂起状态 */
  2335. if (uxSchedulerSuspended != (UBaseType_t)pdFALSE) {
  2336. /**
  2337. * The scheduler is currently suspended - do not allow a context
  2338. * switch.
  2339. */
  2340. xYieldPending = pdTRUE;
  2341. } else {
  2342. xYieldPending = pdFALSE;
  2343. traceTASK_SWITCHED_OUT();
  2344. #if (configGENERATE_RUN_TIME_STATS == 1)
  2345. {
  2346. #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
  2347. portALT_GET_RUN_TIME_COUNTER_VALUE(ulTotalRunTime);
  2348. #else
  2349. ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
  2350. #endif
  2351. /* Add the amount of time the task has been running to the
  2352. * accumulated time so far. The time the task started running was
  2353. * stored in ulTaskSwitchedInTime. Note that there is no overflow
  2354. * protection here so count values are only valid until the timer
  2355. * overflows. The guard against negative values is to protect
  2356. * against suspect run time stat counter implementations - which
  2357. * are provided by the application, not the kernel. */
  2358. if (ulTotalRunTime > ulTaskSwitchedInTime)
  2359. {
  2360. pxCurrentTCB->ulRunTimeCounter += (ulTotalRunTime - ulTaskSwitchedInTime);
  2361. }
  2362. ulTaskSwitchedInTime = ulTotalRunTime;
  2363. }
  2364. #endif /* configGENERATE_RUN_TIME_STATS */
  2365. /* Check for stack overflow, if configured. */
  2366. taskCHECK_FOR_STACK_OVERFLOW();
  2367. /* Before the currently running task is switched out, save its errno. */
  2368. #if (configUSE_POSIX_ERRNO == 1)
  2369. {
  2370. pxCurrentTCB->iTaskErrno = FreeRTOS_errno;
  2371. }
  2372. #endif
  2373. /**
  2374. * Select a new task to run using either the generic C or port
  2375. * optimised asm code.
  2376. * 选择优先级最高的任务
  2377. */
  2378. taskSELECT_HIGHEST_PRIORITY_TASK();
  2379. traceTASK_SWITCHED_IN();
  2380. /* After the new task is switched in, update the global errno. */
  2381. #if (configUSE_POSIX_ERRNO == 1)
  2382. {
  2383. FreeRTOS_errno = pxCurrentTCB->iTaskErrno;
  2384. }
  2385. #endif
  2386. #if ((configUSE_NEWLIB_REENTRANT == 1) || (configUSE_C_RUNTIME_TLS_SUPPORT == 1))
  2387. {
  2388. /* Switch C-Runtime's TLS Block to point to the TLS
  2389. * Block specific to this task. */
  2390. configSET_TLS_BLOCK(pxCurrentTCB->xTLSBlock);
  2391. }
  2392. #endif
  2393. }
  2394. }
  2395. void vTaskPlaceOnEventList(List_t * const pxEventList,
  2396. const TickType_t xTicksToWait)
  2397. {
  2398. configASSERT(pxEventList);
  2399. /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE
  2400. * SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */
  2401. /* Place the event list item of the TCB in the appropriate event list.
  2402. * This is placed in the list in priority order so the highest priority task
  2403. * is the first to be woken by the event.
  2404. *
  2405. * Note: Lists are sorted in ascending order by ListItem_t.xItemValue.
  2406. * Normally, the xItemValue of a TCB's ListItem_t members is:
  2407. * xItemValue = (configMAX_PRIORITIES - uxPriority)
  2408. * Therefore, the event list is sorted in descending priority order.
  2409. *
  2410. * The queue that contains the event list is locked, preventing
  2411. * simultaneous access from interrupts. */
  2412. vListInsert(pxEventList, &(pxCurrentTCB->xEventListItem));
  2413. prvAddCurrentTaskToDelayedList(xTicksToWait, pdTRUE);
  2414. }
  2415. void vTaskPlaceOnUnorderedEventList(List_t * pxEventList,
  2416. const TickType_t xItemValue,
  2417. const TickType_t xTicksToWait)
  2418. {
  2419. configASSERT(pxEventList);
  2420. /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by
  2421. * the event groups implementation. */
  2422. configASSERT(uxSchedulerSuspended != 0);
  2423. /* Store the item value in the event list item. It is safe to access the
  2424. * event list item here as interrupts won't access the event list item of a
  2425. * task that is not in the Blocked state. */
  2426. listSET_LIST_ITEM_VALUE(&(pxCurrentTCB->xEventListItem), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE);
  2427. /* Place the event list item of the TCB at the end of the appropriate event
  2428. * list. It is safe to access the event list here because it is part of an
  2429. * event group implementation - and interrupts don't access event groups
  2430. * directly (instead they access them indirectly by pending function calls to
  2431. * the task level).
  2432. * 任务加入事件队列
  2433. */
  2434. listINSERT_END(pxEventList, &(pxCurrentTCB->xEventListItem));
  2435. /* 任务加入延迟队列 */
  2436. prvAddCurrentTaskToDelayedList(xTicksToWait, pdTRUE);
  2437. }
  2438. #if (configUSE_TIMERS == 1)
  2439. void vTaskPlaceOnEventListRestricted(List_t * const pxEventList,
  2440. TickType_t xTicksToWait,
  2441. const BaseType_t xWaitIndefinitely)
  2442. {
  2443. configASSERT(pxEventList);
  2444. /* This function should not be called by application code hence the
  2445. * 'Restricted' in its name. It is not part of the public API. It is
  2446. * designed for use by kernel code, and has special calling requirements -
  2447. * it should be called with the scheduler suspended. */
  2448. /* Place the event list item of the TCB in the appropriate event list.
  2449. * In this case it is assume that this is the only task that is going to
  2450. * be waiting on this event list, so the faster vListInsertEnd() function
  2451. * can be used in place of vListInsert. */
  2452. listINSERT_END(pxEventList, &(pxCurrentTCB->xEventListItem));
  2453. /* If the task should block indefinitely then set the block time to a
  2454. * value that will be recognised as an indefinite delay inside the
  2455. * prvAddCurrentTaskToDelayedList() function. */
  2456. if (xWaitIndefinitely != pdFALSE)
  2457. {
  2458. xTicksToWait = portMAX_DELAY;
  2459. }
  2460. traceTASK_DELAY_UNTIL((xTickCount + xTicksToWait));
  2461. prvAddCurrentTaskToDelayedList(xTicksToWait, xWaitIndefinitely);
  2462. }
  2463. #endif /* configUSE_TIMERS */
  2464. BaseType_t xTaskRemoveFromEventList(const List_t * const pxEventList)
  2465. {
  2466. TCB_t * pxUnblockedTCB;
  2467. BaseType_t xReturn;
  2468. /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be
  2469. * called from a critical section within an ISR. */
  2470. /* The event list is sorted in priority order, so the first in the list can
  2471. * be removed as it is known to be the highest priority. Remove the TCB from
  2472. * the delayed list, and add it to the ready list.
  2473. *
  2474. * If an event is for a queue that is locked then this function will never
  2475. * get called - the lock count on the queue will get modified instead. This
  2476. * means exclusive access to the event list is guaranteed here.
  2477. *
  2478. * This function assumes that a check has already been made to ensure that
  2479. * pxEventList is not empty. */
  2480. pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY(pxEventList);
  2481. configASSERT(pxUnblockedTCB);
  2482. listREMOVE_ITEM(&(pxUnblockedTCB->xEventListItem));
  2483. /* 如果调度器正在运行中 */
  2484. if (uxSchedulerSuspended == (UBaseType_t)pdFALSE)
  2485. {
  2486. listREMOVE_ITEM(&(pxUnblockedTCB->xStateListItem));
  2487. /* 任务重新加入就绪队列 */
  2488. prvAddTaskToReadyList(pxUnblockedTCB);
  2489. #if (configUSE_TICKLESS_IDLE != 0)
  2490. {
  2491. /* If a task is blocked on a kernel object then xNextTaskUnblockTime
  2492. * might be set to the blocked task's time out time. If the task is
  2493. * unblocked for a reason other than a timeout xNextTaskUnblockTime is
  2494. * normally left unchanged, because it is automatically reset to a new
  2495. * value when the tick count equals xNextTaskUnblockTime. However if
  2496. * tickless idling is used it might be more important to enter sleep mode
  2497. * at the earliest possible time - so reset xNextTaskUnblockTime here to
  2498. * ensure it is updated at the earliest possible time. */
  2499. prvResetNextTaskUnblockTime();
  2500. }
  2501. #endif
  2502. }
  2503. else
  2504. {
  2505. /* The delayed and ready lists cannot be accessed, so hold this task
  2506. * pending until the scheduler is resumed.
  2507. * 调度器被挂起状态,将任务加入到等待加入就绪队列链表
  2508. */
  2509. listINSERT_END(&(xPendingReadyList), &(pxUnblockedTCB->xEventListItem));
  2510. }
  2511. /**
  2512. * pxUnblockedTCB任务优先级比当前正在运行任务的优先级要高,当前任务被抢占
  2513. */
  2514. if (pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority)
  2515. {
  2516. /* Return true if the task removed from the event list has a higher
  2517. * priority than the calling task. This allows the calling task to know if
  2518. * it should force a context switch now. */
  2519. xReturn = pdTRUE;
  2520. /**
  2521. * Mark that a yield is pending in case the user is not using the
  2522. * "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function.
  2523. * 设置可抢占标记
  2524. */
  2525. xYieldPending = pdTRUE;
  2526. }
  2527. else
  2528. {
  2529. xReturn = pdFALSE;
  2530. }
  2531. return xReturn;
  2532. }
  2533. void vTaskRemoveFromUnorderedEventList(ListItem_t * pxEventListItem,
  2534. const TickType_t xItemValue)
  2535. {
  2536. TCB_t * pxUnblockedTCB;
  2537. /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by
  2538. * the event flags implementation. */
  2539. configASSERT(uxSchedulerSuspended != pdFALSE);
  2540. /* Store the new item value in the event list. */
  2541. listSET_LIST_ITEM_VALUE(pxEventListItem, xItemValue|taskEVENT_LIST_ITEM_VALUE_IN_USE);
  2542. /* Remove the event list form the event flag. Interrupts do not access
  2543. * event flags. */
  2544. pxUnblockedTCB = listGET_LIST_ITEM_OWNER(pxEventListItem);
  2545. configASSERT(pxUnblockedTCB);
  2546. listREMOVE_ITEM(pxEventListItem);
  2547. #if (configUSE_TICKLESS_IDLE != 0)
  2548. {
  2549. /* If a task is blocked on a kernel object then xNextTaskUnblockTime
  2550. * might be set to the blocked task's time out time. If the task is
  2551. * unblocked for a reason other than a timeout xNextTaskUnblockTime is
  2552. * normally left unchanged, because it is automatically reset to a new
  2553. * value when the tick count equals xNextTaskUnblockTime. However if
  2554. * tickless idling is used it might be more important to enter sleep mode
  2555. * at the earliest possible time - so reset xNextTaskUnblockTime here to
  2556. * ensure it is updated at the earliest possible time. */
  2557. prvResetNextTaskUnblockTime();
  2558. }
  2559. #endif
  2560. /* Remove the task from the delayed list and add it to the ready list. The
  2561. * scheduler is suspended so interrupts will not be accessing the ready
  2562. * lists. */
  2563. listREMOVE_ITEM(&(pxUnblockedTCB->xStateListItem));
  2564. /* 加入任务就绪队列 */
  2565. prvAddTaskToReadyList(pxUnblockedTCB);
  2566. if (pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority)
  2567. {
  2568. /* The unblocked task has a priority above that of the calling task, so
  2569. * a context switch is required. This function is called with the
  2570. * scheduler suspended so xYieldPending is set so the context switch
  2571. * occurs immediately that the scheduler is resumed (unsuspended). */
  2572. xYieldPending = pdTRUE;
  2573. }
  2574. }
  2575. void vTaskSetTimeOutState(TimeOut_t * const pxTimeOut)
  2576. {
  2577. configASSERT(pxTimeOut);
  2578. taskENTER_CRITICAL();
  2579. {
  2580. pxTimeOut->xOverflowCount = xNumOfOverflows;
  2581. pxTimeOut->xTimeOnEntering = xTickCount;
  2582. }
  2583. taskEXIT_CRITICAL();
  2584. }
  2585. void vTaskInternalSetTimeOutState(TimeOut_t * const pxTimeOut)
  2586. {
  2587. /* For internal use only as it does not use a critical section. */
  2588. pxTimeOut->xOverflowCount = xNumOfOverflows;
  2589. pxTimeOut->xTimeOnEntering = xTickCount;
  2590. }
  2591. /**
  2592. * 检查是否已经超过pxTicksToWait
  2593. */
  2594. BaseType_t xTaskCheckForTimeOut(TimeOut_t * const pxTimeOut,
  2595. TickType_t * const pxTicksToWait)
  2596. {
  2597. BaseType_t xReturn;
  2598. configASSERT(pxTimeOut);
  2599. configASSERT(pxTicksToWait);
  2600. taskENTER_CRITICAL();
  2601. {
  2602. /* Minor optimisation. The tick count cannot change in this block. */
  2603. const TickType_t xConstTickCount = xTickCount;
  2604. /* 计算出pxTimeOut初始设置到现在,已经经过的tick */
  2605. const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering;
  2606. #if (INCLUDE_xTaskAbortDelay == 1)
  2607. if (pxCurrentTCB->ucDelayAborted != (uint8_t)pdFALSE)
  2608. {
  2609. /* The delay was aborted, which is not the same as a time out,
  2610. * but has the same result. */
  2611. pxCurrentTCB->ucDelayAborted = pdFALSE;
  2612. xReturn = pdTRUE;
  2613. }
  2614. else
  2615. #endif
  2616. #if (INCLUDE_vTaskSuspend == 1)
  2617. if (*pxTicksToWait == portMAX_DELAY)
  2618. {
  2619. /* If INCLUDE_vTaskSuspend is set to 1 and the block time
  2620. * specified is the maximum block time then the task should block
  2621. * indefinitely, and therefore never time out. */
  2622. xReturn = pdFALSE;
  2623. }
  2624. else
  2625. #endif
  2626. if ((xNumOfOverflows != pxTimeOut->xOverflowCount) && (xConstTickCount >= pxTimeOut->xTimeOnEntering))
  2627. {
  2628. /* The tick count is greater than the time at which
  2629. * vTaskSetTimeout() was called, but has also overflowed since
  2630. * vTaskSetTimeOut() was called. It must have wrapped all the way
  2631. * around and gone past again. This passed since vTaskSetTimeout()
  2632. * was called.
  2633. * 已经超时
  2634. */
  2635. xReturn = pdTRUE;
  2636. *pxTicksToWait = (TickType_t)0;
  2637. }
  2638. else if (xElapsedTime < *pxTicksToWait)
  2639. {
  2640. /* Not a genuine timeout. Adjust parameters for time remaining. */
  2641. *pxTicksToWait -= xElapsedTime;
  2642. vTaskInternalSetTimeOutState(pxTimeOut);
  2643. xReturn = pdFALSE;
  2644. }
  2645. else
  2646. {
  2647. *pxTicksToWait = (TickType_t)0;
  2648. xReturn = pdTRUE;
  2649. }
  2650. }
  2651. taskEXIT_CRITICAL();
  2652. return xReturn;
  2653. }
  2654. void vTaskMissedYield(void)
  2655. {
  2656. xYieldPending = pdTRUE;
  2657. }
  2658. #if (configUSE_TRACE_FACILITY == 1)
  2659. UBaseType_t uxTaskGetTaskNumber(TaskHandle_t xTask)
  2660. {
  2661. UBaseType_t uxReturn;
  2662. TCB_t const * pxTCB;
  2663. if (xTask != NULL)
  2664. {
  2665. pxTCB = xTask;
  2666. uxReturn = pxTCB->uxTaskNumber;
  2667. }
  2668. else
  2669. {
  2670. uxReturn = 0U;
  2671. }
  2672. return uxReturn;
  2673. }
  2674. void vTaskSetTaskNumber(TaskHandle_t xTask,
  2675. const UBaseType_t uxHandle)
  2676. {
  2677. TCB_t * pxTCB;
  2678. if (xTask != NULL)
  2679. {
  2680. pxTCB = xTask;
  2681. pxTCB->uxTaskNumber = uxHandle;
  2682. }
  2683. }
  2684. #endif /* configUSE_TRACE_FACILITY */
  2685. /*
  2686. * -----------------------------------------------------------
  2687. * The Idle task.
  2688. * ----------------------------------------------------------
  2689. *
  2690. * The portTASK_FUNCTION() macro is used to allow port/compiler specific
  2691. * language extensions. The equivalent prototype for this function is:
  2692. *
  2693. * void prvIdleTask(void *pvParameters);
  2694. * 系统idle任务
  2695. */
  2696. static portTASK_FUNCTION(prvIdleTask, pvParameters)
  2697. {
  2698. /* Stop warnings. */
  2699. (void)pvParameters;
  2700. /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE
  2701. * SCHEDULER IS STARTED. **/
  2702. /* In case a task that has a secure context deletes itself, in which case
  2703. * the idle task is responsible for deleting the task's secure context, if
  2704. * any. */
  2705. portALLOCATE_SECURE_CONTEXT(configMINIMAL_SECURE_STACK_SIZE);
  2706. for (; ;)
  2707. {
  2708. /**
  2709. * See if any tasks have deleted themselves - if so then the idle task
  2710. * is responsible for freeing the deleted task's TCB and stack.
  2711. * 释放已经删除任务的任务控制块占用的内存
  2712. */
  2713. prvCheckTasksWaitingTermination();
  2714. #if (configUSE_PREEMPTION == 0)
  2715. {
  2716. /* If we are not using preemption we keep forcing a task switch to
  2717. * see if any other task has become available. If we are using
  2718. * preemption we don't need to do this as any task becoming available
  2719. * will automatically get the processor anyway.
  2720. * 不开启内核抢占的话,主动触发任务调度,看看,是否有其他任务可以运行
  2721. */
  2722. taskYIELD();
  2723. }
  2724. #endif
  2725. /*
  2726. * 开启抢占的情况下,用户空间创建了与idle相同优先级的任务,则用户空间的任务是可以
  2727. * 使用空闲任务的时间片
  2728. */
  2729. #if ((configUSE_PREEMPTION == 1) && (configIDLE_SHOULD_YIELD == 1))
  2730. {
  2731. /* When using preemption tasks of equal priority will be
  2732. * timesliced. If a task that is sharing the idle priority is ready
  2733. * to run then the idle task should yield before the end of the
  2734. * timeslice.
  2735. *
  2736. * A critical region is not required here as we are just reading from
  2737. * the list, and an occasional incorrect value will not matter. If
  2738. * the ready list at the idle priority contains more than one task
  2739. * then a task other than the idle task is ready to execute.
  2740. * 有和空闲任务相同优先级的用户任务,则空闲任务让出cpu
  2741. */
  2742. if (listCURRENT_LIST_LENGTH(&(pxReadyTasksLists[tskIDLE_PRIORITY])) > (UBaseType_t)1)
  2743. {
  2744. taskYIELD();
  2745. }
  2746. }
  2747. #endif
  2748. #if (configUSE_IDLE_HOOK == 1)
  2749. {
  2750. extern void vApplicationIdleHook(void);
  2751. /* Call the user defined function from within the idle task. This
  2752. * allows the application designer to add background functionality
  2753. * without the overhead of a separate task.
  2754. * NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES,
  2755. * CALL A FUNCTION THAT MIGHT BLOCK. */
  2756. vApplicationIdleHook();
  2757. }
  2758. #endif /* configUSE_IDLE_HOOK */
  2759. /* This conditional compilation should use inequality to 0, not equality
  2760. * to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when
  2761. * user defined low power mode implementations require
  2762. * configUSE_TICKLESS_IDLE to be set to a value other than 1.
  2763. * 进入低功耗模式
  2764. */
  2765. #if (configUSE_TICKLESS_IDLE != 0)
  2766. {
  2767. TickType_t xExpectedIdleTime;
  2768. /* It is not desirable to suspend then resume the scheduler on
  2769. * each iteration of the idle task. Therefore, a preliminary
  2770. * test of the expected idle time is performed without the
  2771. * scheduler suspended. The result here is not necessarily
  2772. * valid.
  2773. * 计算出系统期望运行在低功耗模式的节拍数
  2774. */
  2775. xExpectedIdleTime = prvGetExpectedIdleTime();
  2776. /* 满足系统配置的进入低功耗模式的阈值 */
  2777. if (xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP)
  2778. {
  2779. vTaskSuspendAll();
  2780. {
  2781. /* Now the scheduler is suspended, the expected idle
  2782. * time can be sampled again, and this time its value can
  2783. * be used. */
  2784. configASSERT(xNextTaskUnblockTime >= xTickCount);
  2785. /* 再次计算出系统期望运行在低功耗模式的节拍数 */
  2786. xExpectedIdleTime = prvGetExpectedIdleTime();
  2787. /* Define the following macro to set xExpectedIdleTime to 0
  2788. * if the application does not want
  2789. * portSUPPRESS_TICKS_AND_SLEEP() to be called. */
  2790. configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING(xExpectedIdleTime);
  2791. /* 满足系统配置的进入低功耗模式的阈值 */
  2792. if (xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP)
  2793. {
  2794. traceLOW_POWER_IDLE_BEGIN();
  2795. /* 处理器进入低功耗模式 */
  2796. portSUPPRESS_TICKS_AND_SLEEP(xExpectedIdleTime);
  2797. traceLOW_POWER_IDLE_END();
  2798. }
  2799. }
  2800. /* 此处,应该是只退出低功耗模式后,才能指向到这里 */
  2801. (void) xTaskResumeAll();
  2802. }
  2803. }
  2804. #endif
  2805. }
  2806. }
  2807. #if (configUSE_TICKLESS_IDLE != 0)
  2808. eSleepModeStatus eTaskConfirmSleepModeStatus(void)
  2809. {
  2810. #if (INCLUDE_vTaskSuspend == 1)
  2811. /* The idle task exists in addition to the application tasks. */
  2812. const UBaseType_t uxNonApplicationTasks = 1;
  2813. #endif /* INCLUDE_vTaskSuspend */
  2814. eSleepModeStatus eReturn = eStandardSleep;
  2815. /* This function must be called from a critical section. */
  2816. if (listCURRENT_LIST_LENGTH(&xPendingReadyList) != 0)
  2817. {
  2818. /**
  2819. * A task was made ready while the scheduler was suspended.
  2820. * 有任务就绪,放弃休眠
  2821. */
  2822. eReturn = eAbortSleep;
  2823. }
  2824. else if (xYieldPending == pdTRUE)
  2825. {
  2826. /* A yield was pended while the scheduler was suspended. */
  2827. eReturn = eAbortSleep;
  2828. }
  2829. else if (xPendedTicks != 0)
  2830. {
  2831. /* A tick interrupt has already occurred but was held pending
  2832. * because the scheduler is suspended. */
  2833. eReturn = eAbortSleep;
  2834. }
  2835. #if (INCLUDE_vTaskSuspend == 1)
  2836. else if (listCURRENT_LIST_LENGTH(&xSuspendedTaskList) == (uxCurrentNumberOfTasks - uxNonApplicationTasks))
  2837. {
  2838. /* If all the tasks are in the suspended list (which might mean they
  2839. * have an infinite block time rather than actually being suspended)
  2840. * then it is safe to turn all clocks off and just wait for external
  2841. * interrupts. */
  2842. eReturn = eNoTasksWaitingTimeout;
  2843. }
  2844. #endif /* INCLUDE_vTaskSuspend */
  2845. return eReturn;
  2846. }
  2847. #endif
  2848. #if (configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0)
  2849. void vTaskSetThreadLocalStoragePointer(TaskHandle_t xTaskToSet,
  2850. BaseType_t xIndex,
  2851. void * pvValue)
  2852. {
  2853. TCB_t * pxTCB;
  2854. if ((xIndex >= 0) &&
  2855. (xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS))
  2856. {
  2857. pxTCB = prvGetTCBFromHandle(xTaskToSet);
  2858. configASSERT(pxTCB != NULL);
  2859. pxTCB->pvThreadLocalStoragePointers[xIndex] = pvValue;
  2860. }
  2861. }
  2862. #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */
  2863. #if (configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0)
  2864. void * pvTaskGetThreadLocalStoragePointer(TaskHandle_t xTaskToQuery,
  2865. BaseType_t xIndex)
  2866. {
  2867. void * pvReturn = NULL;
  2868. TCB_t * pxTCB;
  2869. if ((xIndex >= 0) &&
  2870. (xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS))
  2871. {
  2872. pxTCB = prvGetTCBFromHandle(xTaskToQuery);
  2873. pvReturn = pxTCB->pvThreadLocalStoragePointers[xIndex];
  2874. }
  2875. else
  2876. {
  2877. pvReturn = NULL;
  2878. }
  2879. return pvReturn;
  2880. }
  2881. #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */
  2882. #if (portUSING_MPU_WRAPPERS == 1)
  2883. void vTaskAllocateMPURegions(TaskHandle_t xTaskToModify,
  2884. const MemoryRegion_t * const xRegions)
  2885. {
  2886. TCB_t * pxTCB;
  2887. /* If null is passed in here then we are modifying the MPU settings of
  2888. * the calling task. */
  2889. pxTCB = prvGetTCBFromHandle(xTaskToModify);
  2890. vPortStoreTaskMPUSettings(&(pxTCB->xMPUSettings), xRegions, NULL, 0);
  2891. }
  2892. #endif /* portUSING_MPU_WRAPPERS */
  2893. static void prvInitialiseTaskLists(void)
  2894. {
  2895. UBaseType_t uxPriority;
  2896. for (uxPriority = (UBaseType_t)0U; uxPriority < (UBaseType_t)configMAX_PRIORITIES; uxPriority++)
  2897. vListInitialise(&(pxReadyTasksLists[uxPriority]));
  2898. vListInitialise(&xDelayedTaskList1);
  2899. vListInitialise(&xDelayedTaskList2);
  2900. vListInitialise(&xPendingReadyList);
  2901. #if (INCLUDE_vTaskDelete == 1)
  2902. {
  2903. vListInitialise(&xTasksWaitingTermination);
  2904. }
  2905. #endif /* INCLUDE_vTaskDelete */
  2906. #if (INCLUDE_vTaskSuspend == 1)
  2907. {
  2908. vListInitialise(&xSuspendedTaskList);
  2909. }
  2910. #endif /* INCLUDE_vTaskSuspend */
  2911. /**
  2912. * Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList
  2913. * using list2.
  2914. */
  2915. pxDelayedTaskList = &xDelayedTaskList1;
  2916. pxOverflowDelayedTaskList = &xDelayedTaskList2;
  2917. }
  2918. /**
  2919. * 检查释放已删除任务占用的内存
  2920. */
  2921. static void prvCheckTasksWaitingTermination(void)
  2922. {
  2923. /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/
  2924. #if (INCLUDE_vTaskDelete == 1)
  2925. {
  2926. TCB_t * pxTCB;
  2927. /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL()
  2928. * being called too often in the idle task. */
  2929. while (uxDeletedTasksWaitingCleanUp > (UBaseType_t)0U)
  2930. {
  2931. taskENTER_CRITICAL();
  2932. {
  2933. /* 从终止队列中删除 */
  2934. pxTCB = listGET_OWNER_OF_HEAD_ENTRY((&xTasksWaitingTermination));
  2935. (void) uxListRemove(&(pxTCB->xStateListItem));
  2936. --uxCurrentNumberOfTasks;
  2937. --uxDeletedTasksWaitingCleanUp;
  2938. }
  2939. taskEXIT_CRITICAL();
  2940. /* 释放任务控制块占用的内存 */
  2941. prvDeleteTCB(pxTCB);
  2942. }
  2943. }
  2944. #endif /* INCLUDE_vTaskDelete */
  2945. }
  2946. #if (configUSE_TRACE_FACILITY == 1)
  2947. void vTaskGetInfo(TaskHandle_t xTask,
  2948. TaskStatus_t * pxTaskStatus,
  2949. BaseType_t xGetFreeStackSpace,
  2950. eTaskState eState)
  2951. {
  2952. TCB_t * pxTCB;
  2953. /* xTask is NULL then get the state of the calling task. */
  2954. pxTCB = prvGetTCBFromHandle(xTask);
  2955. pxTaskStatus->xHandle = (TaskHandle_t) pxTCB;
  2956. pxTaskStatus->pcTaskName = (const char *) &(pxTCB->pcTaskName[0]);
  2957. pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority;
  2958. pxTaskStatus->pxStackBase = pxTCB->pxStack;
  2959. #if ((portSTACK_GROWTH > 0) && (configRECORD_STACK_HIGH_ADDRESS == 1))
  2960. pxTaskStatus->pxTopOfStack = pxTCB->pxTopOfStack;
  2961. pxTaskStatus->pxEndOfStack = pxTCB->pxEndOfStack;
  2962. #endif
  2963. pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber;
  2964. #if (configUSE_MUTEXES == 1)
  2965. {
  2966. pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority;
  2967. }
  2968. #else
  2969. {
  2970. pxTaskStatus->uxBasePriority = 0;
  2971. }
  2972. #endif
  2973. #if (configGENERATE_RUN_TIME_STATS == 1)
  2974. {
  2975. pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter;
  2976. }
  2977. #else
  2978. {
  2979. pxTaskStatus->ulRunTimeCounter = (configRUN_TIME_COUNTER_TYPE) 0;
  2980. }
  2981. #endif
  2982. /* Obtaining the task state is a little fiddly, so is only done if the
  2983. * value of eState passed into this function is eInvalid - otherwise the
  2984. * state is just set to whatever is passed in. */
  2985. if (eState != eInvalid)
  2986. {
  2987. if (pxTCB == pxCurrentTCB)
  2988. {
  2989. pxTaskStatus->eCurrentState = eRunning;
  2990. }
  2991. else
  2992. {
  2993. pxTaskStatus->eCurrentState = eState;
  2994. #if (INCLUDE_vTaskSuspend == 1)
  2995. {
  2996. /* If the task is in the suspended list then there is a
  2997. * chance it is actually just blocked indefinitely - so really
  2998. * it should be reported as being in the Blocked state. */
  2999. if (eState == eSuspended)
  3000. {
  3001. vTaskSuspendAll();
  3002. {
  3003. if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) != NULL)
  3004. {
  3005. pxTaskStatus->eCurrentState = eBlocked;
  3006. }
  3007. }
  3008. (void) xTaskResumeAll();
  3009. }
  3010. }
  3011. #endif /* INCLUDE_vTaskSuspend */
  3012. }
  3013. }
  3014. else
  3015. {
  3016. pxTaskStatus->eCurrentState = eTaskGetState(pxTCB);
  3017. }
  3018. /* Obtaining the stack space takes some time, so the xGetFreeStackSpace
  3019. * parameter is provided to allow it to be skipped. */
  3020. if (xGetFreeStackSpace != pdFALSE)
  3021. {
  3022. #if (portSTACK_GROWTH > 0)
  3023. {
  3024. pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace((uint8_t *) pxTCB->pxEndOfStack);
  3025. }
  3026. #else
  3027. {
  3028. pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace((uint8_t *) pxTCB->pxStack);
  3029. }
  3030. #endif
  3031. }
  3032. else
  3033. {
  3034. pxTaskStatus->usStackHighWaterMark = 0;
  3035. }
  3036. }
  3037. #endif /* configUSE_TRACE_FACILITY */
  3038. #if (configUSE_TRACE_FACILITY == 1)
  3039. static UBaseType_t prvListTasksWithinSingleList(TaskStatus_t * pxTaskStatusArray,
  3040. List_t * pxList,
  3041. eTaskState eState)
  3042. {
  3043. configLIST_VOLATILE TCB_t * pxNextTCB;
  3044. configLIST_VOLATILE TCB_t * pxFirstTCB;
  3045. UBaseType_t uxTask = 0;
  3046. if (listCURRENT_LIST_LENGTH(pxList) > (UBaseType_t) 0)
  3047. {
  3048. listGET_OWNER_OF_NEXT_ENTRY(pxFirstTCB, pxList);
  3049. /* Populate an TaskStatus_t structure within the
  3050. * pxTaskStatusArray array for each task that is referenced from
  3051. * pxList. See the definition of TaskStatus_t in task.h for the
  3052. * meaning of each TaskStatus_t structure member. */
  3053. do
  3054. {
  3055. listGET_OWNER_OF_NEXT_ENTRY(pxNextTCB, pxList);
  3056. vTaskGetInfo((TaskHandle_t) pxNextTCB, &(pxTaskStatusArray[uxTask]), pdTRUE, eState);
  3057. uxTask++;
  3058. } while (pxNextTCB != pxFirstTCB);
  3059. }
  3060. return uxTask;
  3061. }
  3062. #endif /* configUSE_TRACE_FACILITY */
  3063. #if ((configUSE_TRACE_FACILITY == 1) || (INCLUDE_uxTaskGetStackHighWaterMark == 1) || (INCLUDE_uxTaskGetStackHighWaterMark2 == 1))
  3064. static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace(const uint8_t * pucStackByte)
  3065. {
  3066. uint32_t ulCount = 0U;
  3067. while (*pucStackByte == (uint8_t) tskSTACK_FILL_BYTE)
  3068. {
  3069. pucStackByte -= portSTACK_GROWTH;
  3070. ulCount++;
  3071. }
  3072. ulCount /= (uint32_t) sizeof(StackType_t); /*lint !e961 Casting is not redundant on smaller architectures. */
  3073. return (configSTACK_DEPTH_TYPE) ulCount;
  3074. }
  3075. #endif
  3076. #if (INCLUDE_uxTaskGetStackHighWaterMark2 == 1)
  3077. /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the
  3078. * same except for their return type. Using configSTACK_DEPTH_TYPE allows the
  3079. * user to determine the return type. It gets around the problem of the value
  3080. * overflowing on 8-bit types without breaking backward compatibility for
  3081. * applications that expect an 8-bit return type. */
  3082. configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2(TaskHandle_t xTask)
  3083. {
  3084. TCB_t * pxTCB;
  3085. uint8_t * pucEndOfStack;
  3086. configSTACK_DEPTH_TYPE uxReturn;
  3087. /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are
  3088. * the same except for their return type. Using configSTACK_DEPTH_TYPE
  3089. * allows the user to determine the return type. It gets around the
  3090. * problem of the value overflowing on 8-bit types without breaking
  3091. * backward compatibility for applications that expect an 8-bit return
  3092. * type. */
  3093. pxTCB = prvGetTCBFromHandle(xTask);
  3094. #if portSTACK_GROWTH < 0
  3095. {
  3096. pucEndOfStack = (uint8_t *) pxTCB->pxStack;
  3097. }
  3098. #else
  3099. {
  3100. pucEndOfStack = (uint8_t *) pxTCB->pxEndOfStack;
  3101. }
  3102. #endif
  3103. uxReturn = prvTaskCheckFreeStackSpace(pucEndOfStack);
  3104. return uxReturn;
  3105. }
  3106. #endif /* INCLUDE_uxTaskGetStackHighWaterMark2 */
  3107. #if (INCLUDE_uxTaskGetStackHighWaterMark == 1)
  3108. UBaseType_t uxTaskGetStackHighWaterMark(TaskHandle_t xTask)
  3109. {
  3110. TCB_t * pxTCB;
  3111. uint8_t * pucEndOfStack;
  3112. UBaseType_t uxReturn;
  3113. pxTCB = prvGetTCBFromHandle(xTask);
  3114. #if portSTACK_GROWTH < 0
  3115. {
  3116. pucEndOfStack = (uint8_t *) pxTCB->pxStack;
  3117. }
  3118. #else
  3119. {
  3120. pucEndOfStack = (uint8_t *) pxTCB->pxEndOfStack;
  3121. }
  3122. #endif
  3123. uxReturn = (UBaseType_t) prvTaskCheckFreeStackSpace(pucEndOfStack);
  3124. return uxReturn;
  3125. }
  3126. #endif /* INCLUDE_uxTaskGetStackHighWaterMark */
  3127. #if (INCLUDE_vTaskDelete == 1)
  3128. static void prvDeleteTCB(TCB_t *pxTCB)
  3129. {
  3130. /* This call is required specifically for the TriCore port. It must be
  3131. * above the vPortFree() calls. The call is also used by ports/demos that
  3132. * want to allocate and clean RAM statically. */
  3133. portCLEAN_UP_TCB(pxTCB);
  3134. #if ((configUSE_NEWLIB_REENTRANT == 1) || (configUSE_C_RUNTIME_TLS_SUPPORT == 1))
  3135. {
  3136. /* Free up the memory allocated for the task's TLS Block. */
  3137. configDEINIT_TLS_BLOCK(pxCurrentTCB->xTLSBlock);
  3138. }
  3139. #endif
  3140. #if (portUSING_MPU_WRAPPERS == 0)
  3141. {
  3142. /**
  3143. * The task can only have been allocated dynamically - free both
  3144. * the stack and TCB.
  3145. * 释放任务的堆栈内存和任务控制块内存
  3146. */
  3147. vPortFreeStack(pxTCB->pxStack);
  3148. vPortFree(pxTCB);
  3149. }
  3150. #elif (tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0)
  3151. {
  3152. /* The task could have been allocated statically or dynamically, so
  3153. * check what was statically allocated before trying to free the
  3154. * memory. */
  3155. if (pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB)
  3156. {
  3157. /* Both the stack and TCB were allocated dynamically, so both
  3158. * must be freed. */
  3159. vPortFreeStack(pxTCB->pxStack);
  3160. vPortFree(pxTCB);
  3161. }
  3162. else if (pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY)
  3163. {
  3164. /* Only the stack was statically allocated, so the TCB is the
  3165. * only memory that must be freed. */
  3166. vPortFree(pxTCB);
  3167. }
  3168. else
  3169. {
  3170. /* Neither the stack nor the TCB were allocated dynamically, so
  3171. * nothing needs to be freed. */
  3172. configASSERT(pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB);
  3173. }
  3174. }
  3175. #endif
  3176. }
  3177. #endif /* INCLUDE_vTaskDelete */
  3178. static void prvResetNextTaskUnblockTime(void)
  3179. {
  3180. /* 延迟队列为空 */
  3181. if (listLIST_IS_EMPTY(pxDelayedTaskList) != pdFALSE)
  3182. {
  3183. /**
  3184. * The new current delayed list is empty. Set xNextTaskUnblockTime to
  3185. * the maximum possible value so it is extremely unlikely that the
  3186. * if (xTickCount >= xNextTaskUnblockTime) test will pass until
  3187. * there is an item in the delayed list.
  3188. */
  3189. xNextTaskUnblockTime = portMAX_DELAY;
  3190. }
  3191. else
  3192. {
  3193. /**
  3194. * The new current delayed list is not empty, get the value of
  3195. * the item at the head of the delayed list. This is the time at
  3196. * which the task at the head of the delayed list should be removed
  3197. * from the Blocked state.
  3198. * 下一个等待超时的时间
  3199. */
  3200. xNextTaskUnblockTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY(pxDelayedTaskList);
  3201. }
  3202. }
  3203. #if ((INCLUDE_xTaskGetCurrentTaskHandle == 1) || (configUSE_MUTEXES == 1))
  3204. TaskHandle_t xTaskGetCurrentTaskHandle(void)
  3205. {
  3206. TaskHandle_t xReturn;
  3207. /* A critical section is not required as this is not called from
  3208. * an interrupt and the current TCB will always be the same for any
  3209. * individual execution thread. */
  3210. xReturn = pxCurrentTCB;
  3211. return xReturn;
  3212. }
  3213. #endif /* ((INCLUDE_xTaskGetCurrentTaskHandle == 1) || (configUSE_MUTEXES == 1)) */
  3214. #if ((INCLUDE_xTaskGetSchedulerState == 1) || (configUSE_TIMERS == 1))
  3215. /**
  3216. * 检查调度器状态
  3217. */
  3218. BaseType_t xTaskGetSchedulerState(void)
  3219. {
  3220. BaseType_t xReturn;
  3221. if (xSchedulerRunning == pdFALSE)
  3222. {
  3223. xReturn = taskSCHEDULER_NOT_STARTED;
  3224. }
  3225. else
  3226. {
  3227. if (uxSchedulerSuspended == (UBaseType_t)pdFALSE)
  3228. {
  3229. xReturn = taskSCHEDULER_RUNNING;
  3230. }
  3231. else
  3232. {
  3233. xReturn = taskSCHEDULER_SUSPENDED;
  3234. }
  3235. }
  3236. return xReturn;
  3237. }
  3238. #endif
  3239. #if (configUSE_MUTEXES == 1)
  3240. /**
  3241. * @pxMutexHolder: 持有互斥锁的任务
  3242. */
  3243. BaseType_t xTaskPriorityInherit(TaskHandle_t const pxMutexHolder)
  3244. {
  3245. TCB_t * const pxMutexHolderTCB = pxMutexHolder;
  3246. BaseType_t xReturn = pdFALSE;
  3247. /**
  3248. * If the mutex was given back by an interrupt while the queue was
  3249. * locked then the mutex holder might now be NULL. _RB_ Is this still
  3250. * needed as interrupts can no longer use mutexes?
  3251. */
  3252. if (pxMutexHolder != NULL)
  3253. {
  3254. /**
  3255. * If the holder of the mutex has a priority below the priority of
  3256. * the task attempting to obtain the mutex then it will temporarily
  3257. * inherit the priority of the task attempting to obtain the mutex.
  3258. * 出现高优先级任务尝试获取已经被低优先级任务持有的互斥锁
  3259. */
  3260. if (pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority)
  3261. {
  3262. /**
  3263. * Adjust the mutex holder state to account for its new
  3264. * priority. Only reset the event list item value if the value is
  3265. * not being used for anything else.
  3266. */
  3267. if ((listGET_LIST_ITEM_VALUE(&(pxMutexHolderTCB->xEventListItem)) & taskEVENT_LIST_ITEM_VALUE_IN_USE) == 0UL)
  3268. {
  3269. /* 临时提高持有互斥锁的低优先任务的优先级,这样在加入就绪队列的时候,处于队列的前面 */
  3270. listSET_LIST_ITEM_VALUE(&(pxMutexHolderTCB->xEventListItem),
  3271. (TickType_t)configMAX_PRIORITIES - (TickType_t)pxCurrentTCB->uxPriority);
  3272. }
  3273. /* If the task being modified is in the ready state it will need
  3274. * to be moved into a new list.
  3275. * 低优先级的任务,已经准备要开始运行
  3276. */
  3277. if (listIS_CONTAINED_WITHIN(&(pxReadyTasksLists[pxMutexHolderTCB->uxPriority]),
  3278. &(pxMutexHolderTCB->xStateListItem)) != pdFALSE)
  3279. {
  3280. if (uxListRemove(&(pxMutexHolderTCB->xStateListItem)) == (UBaseType_t)0)
  3281. {
  3282. /* It is known that the task is in its ready list so
  3283. * there is no need to check again and the port level
  3284. * reset macro can be called directly. */
  3285. portRESET_READY_PRIORITY(pxMutexHolderTCB->uxPriority, uxTopReadyPriority);
  3286. }
  3287. /**
  3288. * Inherit the priority before being moved into the new list.
  3289. * 提高低优先级任务的优先级
  3290. */
  3291. pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
  3292. prvAddTaskToReadyList(pxMutexHolderTCB);
  3293. }
  3294. else
  3295. {
  3296. /**
  3297. * Just inherit the priority.
  3298. * 提高低优先级任务的优先级
  3299. */
  3300. pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
  3301. }
  3302. traceTASK_PRIORITY_INHERIT(pxMutexHolderTCB, pxCurrentTCB->uxPriority);
  3303. /**
  3304. * Inheritance occurred.
  3305. * 出现优先级继承
  3306. */
  3307. xReturn = pdTRUE;
  3308. }
  3309. else
  3310. {
  3311. if (pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority)
  3312. {
  3313. /* The base priority of the mutex holder is lower than the
  3314. * priority of the task attempting to take the mutex, but the
  3315. * current priority of the mutex holder is not lower than the
  3316. * priority of the task attempting to take the mutex.
  3317. * Therefore the mutex holder must have already inherited a
  3318. * priority, but inheritance would have occurred if that had
  3319. * not been the case. */
  3320. xReturn = pdTRUE;
  3321. }
  3322. }
  3323. }
  3324. return xReturn;
  3325. }
  3326. BaseType_t xTaskPriorityDisinherit(TaskHandle_t const pxMutexHolder)
  3327. {
  3328. TCB_t * const pxTCB = pxMutexHolder;
  3329. BaseType_t xReturn = pdFALSE;
  3330. if (pxMutexHolder != NULL)
  3331. {
  3332. /* A task can only have an inherited priority if it holds the mutex.
  3333. * If the mutex is held by a task then it cannot be given from an
  3334. * interrupt, and if a mutex is given by the holding task then it must
  3335. * be the running state task. */
  3336. configASSERT(pxTCB == pxCurrentTCB);
  3337. configASSERT(pxTCB->uxMutexesHeld);
  3338. (pxTCB->uxMutexesHeld)--;
  3339. /* Has the holder of the mutex inherited the priority of another
  3340. * task? */
  3341. if (pxTCB->uxPriority != pxTCB->uxBasePriority)
  3342. {
  3343. /* Only disinherit if no other mutexes are held. */
  3344. if (pxTCB->uxMutexesHeld == (UBaseType_t)0)
  3345. {
  3346. /* A task can only have an inherited priority if it holds
  3347. * the mutex. If the mutex is held by a task then it cannot be
  3348. * given from an interrupt, and if a mutex is given by the
  3349. * holding task then it must be the running state task. Remove
  3350. * the holding task from the ready list. */
  3351. if (uxListRemove(&(pxTCB->xStateListItem)) == (UBaseType_t)0)
  3352. {
  3353. portRESET_READY_PRIORITY(pxTCB->uxPriority, uxTopReadyPriority);
  3354. }
  3355. /* Disinherit the priority before adding the task into the
  3356. * new ready list. */
  3357. traceTASK_PRIORITY_DISINHERIT(pxTCB, pxTCB->uxBasePriority);
  3358. pxTCB->uxPriority = pxTCB->uxBasePriority;
  3359. /* Reset the event list item value. It cannot be in use for
  3360. * any other purpose if this task is running, and it must be
  3361. * running to give back the mutex. */
  3362. listSET_LIST_ITEM_VALUE(&(pxTCB->xEventListItem),
  3363. (TickType_t)configMAX_PRIORITIES - (TickType_t)pxTCB->uxPriority);
  3364. prvAddTaskToReadyList(pxTCB);
  3365. /* Return true to indicate that a context switch is required.
  3366. * This is only actually required in the corner case whereby
  3367. * multiple mutexes were held and the mutexes were given back
  3368. * in an order different to that in which they were taken.
  3369. * If a context switch did not occur when the first mutex was
  3370. * returned, even if a task was waiting on it, then a context
  3371. * switch should occur when the last mutex is returned whether
  3372. * a task is waiting on it or not. */
  3373. xReturn = pdTRUE;
  3374. }
  3375. }
  3376. }
  3377. return xReturn;
  3378. }
  3379. /**
  3380. * @pxMutexHolder: 互斥锁的持有者
  3381. * @uxHighestPriorityWaitingTask: 等待互斥锁的最高优先级的任务
  3382. */
  3383. void vTaskPriorityDisinheritAfterTimeout(TaskHandle_t const pxMutexHolder,
  3384. UBaseType_t uxHighestPriorityWaitingTask)
  3385. {
  3386. TCB_t * const pxTCB = pxMutexHolder;
  3387. UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse;
  3388. const UBaseType_t uxOnlyOneMutexHeld = (UBaseType_t)1;
  3389. if (pxMutexHolder != NULL)
  3390. {
  3391. /* If pxMutexHolder is not NULL then the holder must hold at least
  3392. * one mutex. */
  3393. configASSERT(pxTCB->uxMutexesHeld);
  3394. /* Determine the priority to which the priority of the task that
  3395. * holds the mutex should be set. This will be the greater of the
  3396. * holding task's base priority and the priority of the highest
  3397. * priority task that is waiting to obtain the mutex. */
  3398. if (pxTCB->uxBasePriority < uxHighestPriorityWaitingTask)
  3399. {
  3400. uxPriorityToUse = uxHighestPriorityWaitingTask;
  3401. }
  3402. else
  3403. {
  3404. uxPriorityToUse = pxTCB->uxBasePriority;
  3405. }
  3406. /* Does the priority need to change? */
  3407. if (pxTCB->uxPriority != uxPriorityToUse)
  3408. {
  3409. /* Only disinherit if no other mutexes are held. This is a
  3410. * simplification in the priority inheritance implementation. If
  3411. * the task that holds the mutex is also holding other mutexes then
  3412. * the other mutexes may have caused the priority inheritance. */
  3413. if (pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld)
  3414. {
  3415. /* If a task has timed out because it already holds the
  3416. * mutex it was trying to obtain then it cannot of inherited
  3417. * its own priority. */
  3418. configASSERT(pxTCB != pxCurrentTCB);
  3419. /* Disinherit the priority, remembering the previous
  3420. * priority to facilitate determining the subject task's
  3421. * state. */
  3422. traceTASK_PRIORITY_DISINHERIT(pxTCB, uxPriorityToUse);
  3423. uxPriorityUsedOnEntry = pxTCB->uxPriority;
  3424. /* 临时调高持有互斥锁任务的优先级 */
  3425. pxTCB->uxPriority = uxPriorityToUse;
  3426. /* Only reset the event list item value if the value is not
  3427. * being used for anything else. */
  3428. if ((listGET_LIST_ITEM_VALUE(&(pxTCB->xEventListItem)) & taskEVENT_LIST_ITEM_VALUE_IN_USE) == 0UL)
  3429. {
  3430. listSET_LIST_ITEM_VALUE(&(pxTCB->xEventListItem), (TickType_t) configMAX_PRIORITIES - (TickType_t) uxPriorityToUse);
  3431. }
  3432. /* If the running task is not the task that holds the mutex
  3433. * then the task that holds the mutex could be in either the
  3434. * Ready, Blocked or Suspended states. Only remove the task
  3435. * from its current state list if it is in the Ready state as
  3436. * the task's priority is going to change and there is one
  3437. * Ready list per priority. */
  3438. if (listIS_CONTAINED_WITHIN(&(pxReadyTasksLists[uxPriorityUsedOnEntry]), &(pxTCB->xStateListItem)) != pdFALSE)
  3439. {
  3440. if (uxListRemove(&(pxTCB->xStateListItem)) == (UBaseType_t)0)
  3441. {
  3442. /* It is known that the task is in its ready list so
  3443. * there is no need to check again and the port level
  3444. * reset macro can be called directly. */
  3445. portRESET_READY_PRIORITY(pxTCB->uxPriority, uxTopReadyPriority);
  3446. }
  3447. prvAddTaskToReadyList(pxTCB);
  3448. }
  3449. }
  3450. }
  3451. }
  3452. }
  3453. #endif
  3454. #if (portCRITICAL_NESTING_IN_TCB == 1)
  3455. void vTaskEnterCritical(void)
  3456. {
  3457. portDISABLE_INTERRUPTS();
  3458. if (xSchedulerRunning != pdFALSE)
  3459. {
  3460. (pxCurrentTCB->uxCriticalNesting)++;
  3461. /* This is not the interrupt safe version of the enter critical
  3462. * function so assert() if it is being called from an interrupt
  3463. * context. Only API functions that end in "FromISR" can be used in an
  3464. * interrupt. Only assert if the critical nesting count is 1 to
  3465. * protect against recursive calls if the assert function also uses a
  3466. * critical section. */
  3467. if (pxCurrentTCB->uxCriticalNesting == 1)
  3468. {
  3469. portASSERT_IF_IN_ISR();
  3470. }
  3471. }
  3472. }
  3473. #endif /* portCRITICAL_NESTING_IN_TCB */
  3474. #if (portCRITICAL_NESTING_IN_TCB == 1)
  3475. void vTaskExitCritical(void)
  3476. {
  3477. if (xSchedulerRunning != pdFALSE)
  3478. {
  3479. if (pxCurrentTCB->uxCriticalNesting > 0U)
  3480. {
  3481. (pxCurrentTCB->uxCriticalNesting)--;
  3482. if (pxCurrentTCB->uxCriticalNesting == 0U)
  3483. {
  3484. portENABLE_INTERRUPTS();
  3485. }
  3486. }
  3487. }
  3488. }
  3489. #endif /* portCRITICAL_NESTING_IN_TCB */
  3490. #if (configUSE_STATS_FORMATTING_FUNCTIONS > 0)
  3491. static char * prvWriteNameToBuffer(char * pcBuffer, const char * pcTaskName)
  3492. {
  3493. size_t x;
  3494. /* Start by copying the entire string. */
  3495. strcpy(pcBuffer, pcTaskName);
  3496. /* Pad the end of the string with spaces to ensure columns line up when
  3497. * printed out. */
  3498. for (x = strlen(pcBuffer); x < (size_t) (configMAX_TASK_NAME_LEN - 1); x++)
  3499. {
  3500. pcBuffer[x] = ' ';
  3501. }
  3502. /* Terminate. */
  3503. pcBuffer[x] = (char) 0x00;
  3504. /* Return the new end of string. */
  3505. return &(pcBuffer[x]);
  3506. }
  3507. #endif /* (configUSE_STATS_FORMATTING_FUNCTIONS > 0) */
  3508. #if ((configUSE_TRACE_FACILITY == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS > 0))
  3509. void vTaskList(char * pcWriteBuffer)
  3510. {
  3511. TaskStatus_t * pxTaskStatusArray;
  3512. UBaseType_t uxArraySize, x;
  3513. char cStatus;
  3514. /*
  3515. * PLEASE NOTE:
  3516. *
  3517. * This function is provided for convenience only, and is used by many
  3518. * of the demo applications. Do not consider it to be part of the
  3519. * scheduler.
  3520. *
  3521. * vTaskList() calls uxTaskGetSystemState(), then formats part of the
  3522. * uxTaskGetSystemState() output into a human readable table that
  3523. * displays task: names, states, priority, stack usage and task number.
  3524. * Stack usage specified as the number of unused StackType_t words stack can hold
  3525. * on top of stack - not the number of bytes.
  3526. *
  3527. * vTaskList() has a dependency on the sprintf() C library function that
  3528. * might bloat the code size, use a lot of stack, and provide different
  3529. * results on different platforms. An alternative, tiny, third party,
  3530. * and limited functionality implementation of sprintf() is provided in
  3531. * many of the FreeRTOS/Demo sub-directories in a file called
  3532. * printf-stdarg.c (note printf-stdarg.c does not provide a full
  3533. * snprintf() implementation!).
  3534. *
  3535. * It is recommended that production systems call uxTaskGetSystemState()
  3536. * directly to get access to raw stats data, rather than indirectly
  3537. * through a call to vTaskList().
  3538. */
  3539. /* Make sure the write buffer does not contain a string. */
  3540. *pcWriteBuffer = (char) 0x00;
  3541. /* Take a snapshot of the number of tasks in case it changes while this
  3542. * function is executing. */
  3543. uxArraySize = uxCurrentNumberOfTasks;
  3544. pxTaskStatusArray = pvPortMalloc(uxCurrentNumberOfTasks*sizeof(TaskStatus_t));
  3545. if (pxTaskStatusArray != NULL)
  3546. {
  3547. /* Generate the (binary) data. */
  3548. uxArraySize = uxTaskGetSystemState(pxTaskStatusArray, uxArraySize, NULL);
  3549. /* Create a human readable table from the binary data. */
  3550. for (x = 0; x < uxArraySize; x++)
  3551. {
  3552. switch(pxTaskStatusArray[x].eCurrentState)
  3553. {
  3554. case eRunning:
  3555. cStatus = tskRUNNING_CHAR;
  3556. break;
  3557. case eReady:
  3558. cStatus = tskREADY_CHAR;
  3559. break;
  3560. case eBlocked:
  3561. cStatus = tskBLOCKED_CHAR;
  3562. break;
  3563. case eSuspended:
  3564. cStatus = tskSUSPENDED_CHAR;
  3565. break;
  3566. case eDeleted:
  3567. cStatus = tskDELETED_CHAR;
  3568. break;
  3569. case eInvalid: /* Fall through. */
  3570. default: /* Should not get here, but it is included
  3571. * to prevent static checking errors. */
  3572. cStatus = (char) 0x00;
  3573. break;
  3574. }
  3575. /* Write the task name to the string, padding with spaces so it
  3576. * can be printed in tabular form more easily. */
  3577. pcWriteBuffer = prvWriteNameToBuffer(pcWriteBuffer, pxTaskStatusArray[x].pcTaskName);
  3578. /* Write the rest of the string. */
  3579. sprintf(pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n",
  3580. cStatus,
  3581. (unsigned int)pxTaskStatusArray[x].uxCurrentPriority,
  3582. (unsigned int)pxTaskStatusArray[x].usStackHighWaterMark,
  3583. (unsigned int)pxTaskStatusArray[x].xTaskNumber);
  3584. pcWriteBuffer += strlen(pcWriteBuffer);
  3585. }
  3586. vPortFree(pxTaskStatusArray);
  3587. }
  3588. }
  3589. #endif /* ((configUSE_TRACE_FACILITY == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS > 0)) */
  3590. #if ((configGENERATE_RUN_TIME_STATS == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS > 0) && (configUSE_TRACE_FACILITY == 1))
  3591. void vTaskGetRunTimeStats(char * pcWriteBuffer)
  3592. {
  3593. TaskStatus_t * pxTaskStatusArray;
  3594. UBaseType_t uxArraySize, x;
  3595. configRUN_TIME_COUNTER_TYPE ulTotalTime, ulStatsAsPercentage;
  3596. /*
  3597. * PLEASE NOTE:
  3598. *
  3599. * This function is provided for convenience only, and is used by many
  3600. * of the demo applications. Do not consider it to be part of the
  3601. * scheduler.
  3602. *
  3603. * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part
  3604. * of the uxTaskGetSystemState() output into a human readable table that
  3605. * displays the amount of time each task has spent in the Running state
  3606. * in both absolute and percentage terms.
  3607. *
  3608. * vTaskGetRunTimeStats() has a dependency on the sprintf() C library
  3609. * function that might bloat the code size, use a lot of stack, and
  3610. * provide different results on different platforms. An alternative,
  3611. * tiny, third party, and limited functionality implementation of
  3612. * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in
  3613. * a file called printf-stdarg.c (note printf-stdarg.c does not provide
  3614. * a full snprintf() implementation!).
  3615. *
  3616. * It is recommended that production systems call uxTaskGetSystemState()
  3617. * directly to get access to raw stats data, rather than indirectly
  3618. * through a call to vTaskGetRunTimeStats().
  3619. */
  3620. /* Make sure the write buffer does not contain a string. */
  3621. *pcWriteBuffer = (char) 0x00;
  3622. /* Take a snapshot of the number of tasks in case it changes while this
  3623. * function is executing. */
  3624. uxArraySize = uxCurrentNumberOfTasks;
  3625. pxTaskStatusArray = pvPortMalloc(uxCurrentNumberOfTasks * sizeof(TaskStatus_t));
  3626. if (pxTaskStatusArray != NULL)
  3627. {
  3628. /* Generate the (binary) data. */
  3629. uxArraySize = uxTaskGetSystemState(pxTaskStatusArray, uxArraySize, &ulTotalTime);
  3630. /* For percentage calculations. */
  3631. ulTotalTime /= 100UL;
  3632. /* Avoid divide by zero errors. */
  3633. if (ulTotalTime > 0UL)
  3634. {
  3635. /* Create a human readable table from the binary data. */
  3636. for (x = 0; x < uxArraySize; x++)
  3637. {
  3638. /* What percentage of the total run time has the task used?
  3639. * This will always be rounded down to the nearest integer.
  3640. * ulTotalRunTime has already been divided by 100. */
  3641. ulStatsAsPercentage = pxTaskStatusArray[x].ulRunTimeCounter / ulTotalTime;
  3642. /* Write the task name to the string, padding with
  3643. * spaces so it can be printed in tabular form more
  3644. * easily. */
  3645. pcWriteBuffer = prvWriteNameToBuffer(pcWriteBuffer, pxTaskStatusArray[x].pcTaskName);
  3646. if (ulStatsAsPercentage > 0UL)
  3647. {
  3648. #ifdef portLU_PRINTF_SPECIFIER_REQUIRED
  3649. {
  3650. sprintf(pcWriteBuffer, "\t%lu\t\t%lu%%\r\n",
  3651. pxTaskStatusArray[x].ulRunTimeCounter, ulStatsAsPercentage);
  3652. }
  3653. #else
  3654. {
  3655. /* sizeof(int) == sizeof(long) so a smaller
  3656. * printf() library can be used. */
  3657. sprintf(pcWriteBuffer, "\t%u\t\t%u%%\r\n",
  3658. (unsigned int)pxTaskStatusArray[x].ulRunTimeCounter, (unsigned int)ulStatsAsPercentage);
  3659. }
  3660. #endif
  3661. }
  3662. else
  3663. {
  3664. /* If the percentage is zero here then the task has
  3665. * consumed less than 1% of the total run time. */
  3666. #ifdef portLU_PRINTF_SPECIFIER_REQUIRED
  3667. {
  3668. sprintf(pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[x].ulRunTimeCounter);
  3669. }
  3670. #else
  3671. {
  3672. /* sizeof(int) == sizeof(long) so a smaller
  3673. * printf() library can be used. */
  3674. sprintf(pcWriteBuffer, "\t%u\t\t<1%%\r\n",
  3675. (unsigned int)pxTaskStatusArray[x].ulRunTimeCounter);
  3676. }
  3677. #endif
  3678. }
  3679. pcWriteBuffer += strlen(pcWriteBuffer);
  3680. }
  3681. }
  3682. vPortFree(pxTaskStatusArray);
  3683. }
  3684. }
  3685. #endif /* ((configGENERATE_RUN_TIME_STATS == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS > 0)) */
  3686. TickType_t uxTaskResetEventItemValue(void)
  3687. {
  3688. TickType_t uxReturn;
  3689. TickType_t uxValue;
  3690. uxReturn = listGET_LIST_ITEM_VALUE(&(pxCurrentTCB->xEventListItem));
  3691. /* Reset the event list item to its normal value - so it can be used with
  3692. * queues and semaphores. */
  3693. uxValue = (TickType_t)configMAX_PRIORITIES - (TickType_t)pxCurrentTCB->uxPriority;
  3694. listSET_LIST_ITEM_VALUE(&(pxCurrentTCB->xEventListItem), uxValue);
  3695. return uxReturn;
  3696. }
  3697. #if (configUSE_MUTEXES == 1)
  3698. TaskHandle_t pvTaskIncrementMutexHeldCount(void)
  3699. {
  3700. /* If xSemaphoreCreateMutex() is called before any tasks have been created
  3701. * then pxCurrentTCB will be NULL. */
  3702. if (pxCurrentTCB != NULL)
  3703. {
  3704. (pxCurrentTCB->uxMutexesHeld)++;
  3705. }
  3706. return pxCurrentTCB;
  3707. }
  3708. #endif
  3709. #if (configUSE_TASK_NOTIFICATIONS == 1)
  3710. uint32_t ulTaskGenericNotifyTake(UBaseType_t uxIndexToWait,
  3711. BaseType_t xClearCountOnExit,
  3712. TickType_t xTicksToWait)
  3713. {
  3714. uint32_t ulReturn;
  3715. configASSERT(uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES);
  3716. taskENTER_CRITICAL();
  3717. {
  3718. /* Only block if the notification count is not already non-zero. */
  3719. if (pxCurrentTCB->ulNotifiedValue[uxIndexToWait] == 0UL)
  3720. {
  3721. /* Mark this task as waiting for a notification. */
  3722. pxCurrentTCB->ucNotifyState[uxIndexToWait] = taskWAITING_NOTIFICATION;
  3723. if (xTicksToWait > (TickType_t) 0)
  3724. {
  3725. prvAddCurrentTaskToDelayedList(xTicksToWait, pdTRUE);
  3726. traceTASK_NOTIFY_TAKE_BLOCK(uxIndexToWait);
  3727. /* All ports are written to allow a yield in a critical
  3728. * section (some will yield immediately, others wait until the
  3729. * critical section exits) - but it is not something that
  3730. * application code should ever do. */
  3731. portYIELD_WITHIN_API();
  3732. }
  3733. }
  3734. }
  3735. taskEXIT_CRITICAL();
  3736. taskENTER_CRITICAL();
  3737. {
  3738. traceTASK_NOTIFY_TAKE(uxIndexToWait);
  3739. ulReturn = pxCurrentTCB->ulNotifiedValue[uxIndexToWait];
  3740. if (ulReturn != 0UL)
  3741. {
  3742. if (xClearCountOnExit != pdFALSE)
  3743. {
  3744. pxCurrentTCB->ulNotifiedValue[uxIndexToWait] = 0UL;
  3745. }
  3746. else
  3747. {
  3748. pxCurrentTCB->ulNotifiedValue[uxIndexToWait] = ulReturn - (uint32_t) 1;
  3749. }
  3750. }
  3751. pxCurrentTCB->ucNotifyState[uxIndexToWait] = taskNOT_WAITING_NOTIFICATION;
  3752. }
  3753. taskEXIT_CRITICAL();
  3754. return ulReturn;
  3755. }
  3756. #endif
  3757. #if (configUSE_TASK_NOTIFICATIONS == 1)
  3758. BaseType_t xTaskGenericNotifyWait(UBaseType_t uxIndexToWait,
  3759. uint32_t ulBitsToClearOnEntry,
  3760. uint32_t ulBitsToClearOnExit,
  3761. uint32_t * pulNotificationValue,
  3762. TickType_t xTicksToWait)
  3763. {
  3764. BaseType_t xReturn;
  3765. configASSERT(uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES);
  3766. taskENTER_CRITICAL();
  3767. {
  3768. /**
  3769. * Only block if a notification is not already pending.
  3770. * 没有接收到通知
  3771. */
  3772. if (pxCurrentTCB->ucNotifyState[uxIndexToWait] != taskNOTIFICATION_RECEIVED)
  3773. {
  3774. /* Clear bits in the task's notification value as bits may get
  3775. * set by the notifying task or interrupt. This can be used to
  3776. * clear the value to zero. */
  3777. pxCurrentTCB->ulNotifiedValue[uxIndexToWait] &= ~ulBitsToClearOnEntry;
  3778. /* Mark this task as waiting for a notification. */
  3779. pxCurrentTCB->ucNotifyState[uxIndexToWait] = taskWAITING_NOTIFICATION;
  3780. /* 加入延迟等待队列 */
  3781. if (xTicksToWait > (TickType_t)0)
  3782. {
  3783. prvAddCurrentTaskToDelayedList(xTicksToWait, pdTRUE);
  3784. traceTASK_NOTIFY_WAIT_BLOCK(uxIndexToWait);
  3785. /* All ports are written to allow a yield in a critical
  3786. * section (some will yield immediately, others wait until the
  3787. * critical section exits) - but it is not something that
  3788. * application code should ever do.
  3789. * 触发任务调度
  3790. */
  3791. portYIELD_WITHIN_API();
  3792. }
  3793. }
  3794. }
  3795. taskEXIT_CRITICAL();
  3796. /* 接收到了任务通知事件或者发生超时,任务恢复执行 */
  3797. taskENTER_CRITICAL();
  3798. {
  3799. traceTASK_NOTIFY_WAIT(uxIndexToWait);
  3800. if (pulNotificationValue != NULL)
  3801. {
  3802. /* Output the current notification value, which may or may not
  3803. * have changed. */
  3804. *pulNotificationValue = pxCurrentTCB->ulNotifiedValue[uxIndexToWait];
  3805. }
  3806. /* If ucNotifyValue is set then either the task never entered the
  3807. * blocked state (because a notification was already pending) or the
  3808. * task unblocked because of a notification. Otherwise the task
  3809. * unblocked because of a timeout. */
  3810. if (pxCurrentTCB->ucNotifyState[uxIndexToWait] != taskNOTIFICATION_RECEIVED)
  3811. {
  3812. /**
  3813. * A notification was not received.
  3814. * 等待超时
  3815. */
  3816. xReturn = pdFALSE;
  3817. }
  3818. else
  3819. {
  3820. /* A notification was already pending or a notification was
  3821. * received while the task was waiting.
  3822. * 接收到任务通知
  3823. */
  3824. pxCurrentTCB->ulNotifiedValue[uxIndexToWait] &= ~ulBitsToClearOnExit;
  3825. xReturn = pdTRUE;
  3826. }
  3827. pxCurrentTCB->ucNotifyState[uxIndexToWait] = taskNOT_WAITING_NOTIFICATION;
  3828. }
  3829. taskEXIT_CRITICAL();
  3830. return xReturn;
  3831. }
  3832. #endif
  3833. #if (configUSE_TASK_NOTIFICATIONS == 1)
  3834. /**
  3835. * @xTaskToNotify: 给接收任务通知的task发送任务通知信息
  3836. * @ulValue: 通知值
  3837. * @eAction: 更新值的方式
  3838. */
  3839. BaseType_t xTaskGenericNotify(TaskHandle_t xTaskToNotify,
  3840. UBaseType_t uxIndexToNotify,
  3841. uint32_t ulValue,
  3842. eNotifyAction eAction,
  3843. uint32_t * pulPreviousNotificationValue)
  3844. {
  3845. TCB_t * pxTCB;
  3846. BaseType_t xReturn = pdPASS;
  3847. uint8_t ucOriginalNotifyState;
  3848. configASSERT(uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES);
  3849. configASSERT(xTaskToNotify);
  3850. pxTCB = xTaskToNotify;
  3851. taskENTER_CRITICAL();
  3852. {
  3853. if (pulPreviousNotificationValue != NULL)
  3854. {
  3855. *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[uxIndexToNotify];
  3856. }
  3857. ucOriginalNotifyState = pxTCB->ucNotifyState[uxIndexToNotify];
  3858. pxTCB->ucNotifyState[uxIndexToNotify] = taskNOTIFICATION_RECEIVED;
  3859. switch(eAction)
  3860. {
  3861. case eSetBits:
  3862. pxTCB->ulNotifiedValue[uxIndexToNotify] |= ulValue;
  3863. break;
  3864. case eIncrement:
  3865. (pxTCB->ulNotifiedValue[uxIndexToNotify])++;
  3866. break;
  3867. case eSetValueWithOverwrite:
  3868. pxTCB->ulNotifiedValue[uxIndexToNotify] = ulValue;
  3869. break;
  3870. case eSetValueWithoutOverwrite:
  3871. if (ucOriginalNotifyState != taskNOTIFICATION_RECEIVED)
  3872. {
  3873. pxTCB->ulNotifiedValue[uxIndexToNotify] = ulValue;
  3874. }
  3875. else
  3876. {
  3877. /* The value could not be written to the task. */
  3878. xReturn = pdFAIL;
  3879. }
  3880. break;
  3881. case eNoAction:
  3882. /* The task is being notified without its notify value being
  3883. * updated. */
  3884. break;
  3885. default:
  3886. /* Should not get here if all enums are handled.
  3887. * Artificially force an assert by testing a value the
  3888. * compiler can't assume is const. */
  3889. configASSERT(xTickCount == (TickType_t) 0);
  3890. break;
  3891. }
  3892. traceTASK_NOTIFY(uxIndexToNotify);
  3893. /**
  3894. * If the task is in the blocked state specifically to wait for a
  3895. * notification then unblock it now.
  3896. * 任务阻塞等待接收通知
  3897. */
  3898. if (ucOriginalNotifyState == taskWAITING_NOTIFICATION)
  3899. {
  3900. listREMOVE_ITEM(&(pxTCB->xStateListItem));
  3901. prvAddTaskToReadyList(pxTCB);
  3902. /* The task should not have been on an event list. */
  3903. configASSERT(listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) == NULL);
  3904. #if (configUSE_TICKLESS_IDLE != 0)
  3905. {
  3906. /* If a task is blocked waiting for a notification then
  3907. * xNextTaskUnblockTime might be set to the blocked task's time
  3908. * out time. If the task is unblocked for a reason other than
  3909. * a timeout xNextTaskUnblockTime is normally left unchanged,
  3910. * because it will automatically get reset to a new value when
  3911. * the tick count equals xNextTaskUnblockTime. However if
  3912. * tickless idling is used it might be more important to enter
  3913. * sleep mode at the earliest possible time - so reset
  3914. * xNextTaskUnblockTime here to ensure it is updated at the
  3915. * earliest possible time. */
  3916. prvResetNextTaskUnblockTime();
  3917. }
  3918. #endif
  3919. if (pxTCB->uxPriority > pxCurrentTCB->uxPriority)
  3920. {
  3921. /* The notified task has a priority above the currently
  3922. * executing task so a yield is required. */
  3923. taskYIELD_IF_USING_PREEMPTION();
  3924. }
  3925. }
  3926. }
  3927. taskEXIT_CRITICAL();
  3928. return xReturn;
  3929. }
  3930. #endif
  3931. #if (configUSE_TASK_NOTIFICATIONS == 1)
  3932. BaseType_t xTaskGenericNotifyFromISR(TaskHandle_t xTaskToNotify,
  3933. UBaseType_t uxIndexToNotify,
  3934. uint32_t ulValue,
  3935. eNotifyAction eAction,
  3936. uint32_t * pulPreviousNotificationValue,
  3937. BaseType_t * pxHigherPriorityTaskWoken)
  3938. {
  3939. TCB_t * pxTCB;
  3940. uint8_t ucOriginalNotifyState;
  3941. BaseType_t xReturn = pdPASS;
  3942. UBaseType_t uxSavedInterruptStatus;
  3943. configASSERT(xTaskToNotify);
  3944. configASSERT(uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES);
  3945. /* RTOS ports that support interrupt nesting have the concept of a
  3946. * maximum system call (or maximum API call) interrupt priority.
  3947. * Interrupts that are above the maximum system call priority are keep
  3948. * permanently enabled, even when the RTOS kernel is in a critical section,
  3949. * but cannot make any calls to FreeRTOS API functions. If configASSERT()
  3950. * is defined in FreeRTOSConfig.h then
  3951. * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
  3952. * failure if a FreeRTOS API function is called from an interrupt that has
  3953. * been assigned a priority above the configured maximum system call
  3954. * priority. Only FreeRTOS functions that end in FromISR can be called
  3955. * from interrupts that have been assigned a priority at or (logically)
  3956. * below the maximum system call interrupt priority. FreeRTOS maintains a
  3957. * separate interrupt safe API to ensure interrupt entry is as fast and as
  3958. * simple as possible. More information (albeit Cortex-M specific) is
  3959. * provided on the following link:
  3960. * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
  3961. portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
  3962. pxTCB = xTaskToNotify;
  3963. uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
  3964. {
  3965. if (pulPreviousNotificationValue != NULL)
  3966. {
  3967. *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[uxIndexToNotify];
  3968. }
  3969. ucOriginalNotifyState = pxTCB->ucNotifyState[uxIndexToNotify];
  3970. pxTCB->ucNotifyState[uxIndexToNotify] = taskNOTIFICATION_RECEIVED;
  3971. switch(eAction)
  3972. {
  3973. case eSetBits:
  3974. pxTCB->ulNotifiedValue[uxIndexToNotify] |= ulValue;
  3975. break;
  3976. case eIncrement:
  3977. (pxTCB->ulNotifiedValue[uxIndexToNotify])++;
  3978. break;
  3979. case eSetValueWithOverwrite:
  3980. pxTCB->ulNotifiedValue[uxIndexToNotify] = ulValue;
  3981. break;
  3982. case eSetValueWithoutOverwrite:
  3983. if (ucOriginalNotifyState != taskNOTIFICATION_RECEIVED)
  3984. {
  3985. pxTCB->ulNotifiedValue[uxIndexToNotify] = ulValue;
  3986. }
  3987. else
  3988. {
  3989. /* The value could not be written to the task. */
  3990. xReturn = pdFAIL;
  3991. }
  3992. break;
  3993. case eNoAction:
  3994. /* The task is being notified without its notify value being
  3995. * updated. */
  3996. break;
  3997. default:
  3998. /* Should not get here if all enums are handled.
  3999. * Artificially force an assert by testing a value the
  4000. * compiler can't assume is const. */
  4001. configASSERT(xTickCount == (TickType_t)0);
  4002. break;
  4003. }
  4004. traceTASK_NOTIFY_FROM_ISR(uxIndexToNotify);
  4005. /* If the task is in the blocked state specifically to wait for a
  4006. * notification then unblock it now. */
  4007. if (ucOriginalNotifyState == taskWAITING_NOTIFICATION)
  4008. {
  4009. /* The task should not have been on an event list. */
  4010. configASSERT(listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) == NULL);
  4011. if (uxSchedulerSuspended == (UBaseType_t) pdFALSE)
  4012. {
  4013. listREMOVE_ITEM(&(pxTCB->xStateListItem));
  4014. prvAddTaskToReadyList(pxTCB);
  4015. }
  4016. else
  4017. {
  4018. /* The delayed and ready lists cannot be accessed, so hold
  4019. * this task pending until the scheduler is resumed. */
  4020. listINSERT_END(&(xPendingReadyList), &(pxTCB->xEventListItem));
  4021. }
  4022. if (pxTCB->uxPriority > pxCurrentTCB->uxPriority)
  4023. {
  4024. /* The notified task has a priority above the currently
  4025. * executing task so a yield is required. */
  4026. if (pxHigherPriorityTaskWoken != NULL)
  4027. {
  4028. *pxHigherPriorityTaskWoken = pdTRUE;
  4029. }
  4030. /* Mark that a yield is pending in case the user is not
  4031. * using the "xHigherPriorityTaskWoken" parameter to an ISR
  4032. * safe FreeRTOS function. */
  4033. xYieldPending = pdTRUE;
  4034. }
  4035. }
  4036. }
  4037. portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
  4038. return xReturn;
  4039. }
  4040. #endif
  4041. #if (configUSE_TASK_NOTIFICATIONS == 1)
  4042. void vTaskGenericNotifyGiveFromISR(TaskHandle_t xTaskToNotify,
  4043. UBaseType_t uxIndexToNotify,
  4044. BaseType_t * pxHigherPriorityTaskWoken)
  4045. {
  4046. TCB_t * pxTCB;
  4047. uint8_t ucOriginalNotifyState;
  4048. UBaseType_t uxSavedInterruptStatus;
  4049. configASSERT(xTaskToNotify);
  4050. configASSERT(uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES);
  4051. /* RTOS ports that support interrupt nesting have the concept of a
  4052. * maximum system call (or maximum API call) interrupt priority.
  4053. * Interrupts that are above the maximum system call priority are keep
  4054. * permanently enabled, even when the RTOS kernel is in a critical section,
  4055. * but cannot make any calls to FreeRTOS API functions. If configASSERT()
  4056. * is defined in FreeRTOSConfig.h then
  4057. * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
  4058. * failure if a FreeRTOS API function is called from an interrupt that has
  4059. * been assigned a priority above the configured maximum system call
  4060. * priority. Only FreeRTOS functions that end in FromISR can be called
  4061. * from interrupts that have been assigned a priority at or (logically)
  4062. * below the maximum system call interrupt priority. FreeRTOS maintains a
  4063. * separate interrupt safe API to ensure interrupt entry is as fast and as
  4064. * simple as possible. More information (albeit Cortex-M specific) is
  4065. * provided on the following link:
  4066. * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
  4067. portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
  4068. pxTCB = xTaskToNotify;
  4069. uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
  4070. {
  4071. ucOriginalNotifyState = pxTCB->ucNotifyState[uxIndexToNotify];
  4072. pxTCB->ucNotifyState[uxIndexToNotify] = taskNOTIFICATION_RECEIVED;
  4073. /* 'Giving' is equivalent to incrementing a count in a counting
  4074. * semaphore. */
  4075. (pxTCB->ulNotifiedValue[uxIndexToNotify])++;
  4076. traceTASK_NOTIFY_GIVE_FROM_ISR(uxIndexToNotify);
  4077. /* If the task is in the blocked state specifically to wait for a
  4078. * notification then unblock it now. */
  4079. if (ucOriginalNotifyState == taskWAITING_NOTIFICATION)
  4080. {
  4081. /* The task should not have been on an event list. */
  4082. configASSERT(listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) == NULL);
  4083. if (uxSchedulerSuspended == (UBaseType_t)pdFALSE)
  4084. {
  4085. listREMOVE_ITEM(&(pxTCB->xStateListItem));
  4086. prvAddTaskToReadyList(pxTCB);
  4087. }
  4088. else
  4089. {
  4090. /* The delayed and ready lists cannot be accessed, so hold
  4091. * this task pending until the scheduler is resumed. */
  4092. listINSERT_END(&(xPendingReadyList), &(pxTCB->xEventListItem));
  4093. }
  4094. if (pxTCB->uxPriority > pxCurrentTCB->uxPriority)
  4095. {
  4096. /* The notified task has a priority above the currently
  4097. * executing task so a yield is required. */
  4098. if (pxHigherPriorityTaskWoken != NULL)
  4099. {
  4100. *pxHigherPriorityTaskWoken = pdTRUE;
  4101. }
  4102. /* Mark that a yield is pending in case the user is not
  4103. * using the "xHigherPriorityTaskWoken" parameter in an ISR
  4104. * safe FreeRTOS function. */
  4105. xYieldPending = pdTRUE;
  4106. }
  4107. }
  4108. }
  4109. portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
  4110. }
  4111. #endif
  4112. #if (configUSE_TASK_NOTIFICATIONS == 1)
  4113. BaseType_t xTaskGenericNotifyStateClear(TaskHandle_t xTask,
  4114. UBaseType_t uxIndexToClear)
  4115. {
  4116. TCB_t * pxTCB;
  4117. BaseType_t xReturn;
  4118. configASSERT(uxIndexToClear < configTASK_NOTIFICATION_ARRAY_ENTRIES);
  4119. /* If null is passed in here then it is the calling task that is having
  4120. * its notification state cleared. */
  4121. pxTCB = prvGetTCBFromHandle(xTask);
  4122. taskENTER_CRITICAL();
  4123. {
  4124. if (pxTCB->ucNotifyState[uxIndexToClear] == taskNOTIFICATION_RECEIVED)
  4125. {
  4126. pxTCB->ucNotifyState[uxIndexToClear] = taskNOT_WAITING_NOTIFICATION;
  4127. xReturn = pdPASS;
  4128. }
  4129. else
  4130. {
  4131. xReturn = pdFAIL;
  4132. }
  4133. }
  4134. taskEXIT_CRITICAL();
  4135. return xReturn;
  4136. }
  4137. #endif
  4138. #if (configUSE_TASK_NOTIFICATIONS == 1)
  4139. uint32_t ulTaskGenericNotifyValueClear(TaskHandle_t xTask,
  4140. UBaseType_t uxIndexToClear,
  4141. uint32_t ulBitsToClear)
  4142. {
  4143. TCB_t * pxTCB;
  4144. uint32_t ulReturn;
  4145. /* If null is passed in here then it is the calling task that is having
  4146. * its notification state cleared. */
  4147. pxTCB = prvGetTCBFromHandle(xTask);
  4148. taskENTER_CRITICAL();
  4149. {
  4150. /* Return the notification as it was before the bits were cleared,
  4151. * then clear the bit mask. */
  4152. ulReturn = pxTCB->ulNotifiedValue[uxIndexToClear];
  4153. pxTCB->ulNotifiedValue[uxIndexToClear] &= ~ulBitsToClear;
  4154. }
  4155. taskEXIT_CRITICAL();
  4156. return ulReturn;
  4157. }
  4158. #endif
  4159. #if ((configGENERATE_RUN_TIME_STATS == 1) && (INCLUDE_xTaskGetIdleTaskHandle == 1))
  4160. configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimeCounter(void)
  4161. {
  4162. return xIdleTaskHandle->ulRunTimeCounter;
  4163. }
  4164. #endif
  4165. #if ((configGENERATE_RUN_TIME_STATS == 1) && (INCLUDE_xTaskGetIdleTaskHandle == 1))
  4166. configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimePercent(void)
  4167. {
  4168. configRUN_TIME_COUNTER_TYPE ulTotalTime, ulReturn;
  4169. ulTotalTime = portGET_RUN_TIME_COUNTER_VALUE();
  4170. /* For percentage calculations. */
  4171. ulTotalTime /= (configRUN_TIME_COUNTER_TYPE) 100;
  4172. /* Avoid divide by zero errors. */
  4173. if (ulTotalTime > (configRUN_TIME_COUNTER_TYPE) 0)
  4174. {
  4175. ulReturn = xIdleTaskHandle->ulRunTimeCounter / ulTotalTime;
  4176. }
  4177. else
  4178. {
  4179. ulReturn = 0;
  4180. }
  4181. return ulReturn;
  4182. }
  4183. #endif
  4184. static void prvAddCurrentTaskToDelayedList(TickType_t xTicksToWait,
  4185. const BaseType_t xCanBlockIndefinitely)
  4186. {
  4187. TickType_t xTimeToWake;
  4188. const TickType_t xConstTickCount = xTickCount;
  4189. #if (INCLUDE_xTaskAbortDelay == 1)
  4190. {
  4191. /* About to enter a delayed list, so ensure the ucDelayAborted flag is
  4192. * reset to pdFALSE so it can be detected as having been set to pdTRUE
  4193. * when the task leaves the Blocked state. */
  4194. pxCurrentTCB->ucDelayAborted = pdFALSE;
  4195. }
  4196. #endif
  4197. /**
  4198. * Remove the task from the ready list before adding it to the blocked list
  4199. * as the same list item is used for both lists.、
  4200. * 当前任务从就绪队列删除
  4201. */
  4202. if (uxListRemove(&(pxCurrentTCB->xStateListItem)) == (UBaseType_t)0)
  4203. {
  4204. /**
  4205. * The current task must be in a ready list, so there is no need to
  4206. * check, and the port reset macro can be called directly.
  4207. * 取消任务的uxTopReadyPriority标记
  4208. */
  4209. portRESET_READY_PRIORITY(pxCurrentTCB->uxPriority, uxTopReadyPriority);
  4210. }
  4211. #if (INCLUDE_vTaskSuspend == 1)
  4212. {
  4213. /* 无限等待 */
  4214. if ((xTicksToWait == portMAX_DELAY) && (xCanBlockIndefinitely != pdFALSE))
  4215. {
  4216. /* Add the task to the suspended task list instead of a delayed task
  4217. * list to ensure it is not woken by a timing event. It will block
  4218. * indefinitely.
  4219. * 无限等待,直接加入到挂起队列
  4220. */
  4221. listINSERT_END(&xSuspendedTaskList, &(pxCurrentTCB->xStateListItem));
  4222. }
  4223. else
  4224. {
  4225. /* Calculate the time at which the task should be woken if the event
  4226. * does not occur. This may overflow but this doesn't matter, the
  4227. * kernel will manage it correctly.
  4228. * 计算任务绝对唤醒的时间点
  4229. */
  4230. xTimeToWake = xConstTickCount + xTicksToWait;
  4231. /**
  4232. * The list item will be inserted in wake time order.
  4233. * 设置任务延迟超时时间
  4234. */
  4235. listSET_LIST_ITEM_VALUE(&(pxCurrentTCB->xStateListItem), xTimeToWake);
  4236. /* 发生溢出 */
  4237. if (xTimeToWake < xConstTickCount)
  4238. {
  4239. /**
  4240. * Wake time has overflowed. Place this item in the overflow
  4241. * list
  4242. * 任务已经超时
  4243. */
  4244. vListInsert(pxOverflowDelayedTaskList, &(pxCurrentTCB->xStateListItem));
  4245. }
  4246. else
  4247. {
  4248. /**
  4249. * The wake time has not overflowed, so the current block list
  4250. * is used.
  4251. */
  4252. vListInsert(pxDelayedTaskList, &(pxCurrentTCB->xStateListItem));
  4253. /* If the task entering the blocked state was placed at the
  4254. * head of the list of blocked tasks then xNextTaskUnblockTime
  4255. * needs to be updated too. */
  4256. if (xTimeToWake < xNextTaskUnblockTime)
  4257. {
  4258. /* 更新下一个取消任务阻塞的时间点 */
  4259. xNextTaskUnblockTime = xTimeToWake;
  4260. }
  4261. }
  4262. }
  4263. }
  4264. #else /* INCLUDE_vTaskSuspend */
  4265. {
  4266. /* Calculate the time at which the task should be woken if the event
  4267. * does not occur. This may overflow but this doesn't matter, the kernel
  4268. * will manage it correctly. */
  4269. xTimeToWake = xConstTickCount + xTicksToWait;
  4270. /* The list item will be inserted in wake time order. */
  4271. listSET_LIST_ITEM_VALUE(&(pxCurrentTCB->xStateListItem), xTimeToWake);
  4272. if (xTimeToWake < xConstTickCount)
  4273. {
  4274. /* Wake time has overflowed. Place this item in the overflow list. */
  4275. vListInsert(pxOverflowDelayedTaskList, &(pxCurrentTCB->xStateListItem));
  4276. }
  4277. else
  4278. {
  4279. /* The wake time has not overflowed, so the current block list is used. */
  4280. vListInsert(pxDelayedTaskList, &(pxCurrentTCB->xStateListItem));
  4281. /* If the task entering the blocked state was placed at the head of the
  4282. * list of blocked tasks then xNextTaskUnblockTime needs to be updated
  4283. * too. */
  4284. if (xTimeToWake < xNextTaskUnblockTime)
  4285. {
  4286. xNextTaskUnblockTime = xTimeToWake;
  4287. }
  4288. }
  4289. /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */
  4290. (void) xCanBlockIndefinitely;
  4291. }
  4292. #endif
  4293. }