core.c 272 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * kernel/sched/core.c
  4. *
  5. * Core kernel CPU scheduler code
  6. *
  7. * Copyright (C) 1991-2002 Linus Torvalds
  8. * Copyright (C) 1998-2024 Ingo Molnar, Red Hat
  9. */
  10. #include <linux/highmem.h>
  11. #include <linux/hrtimer_api.h>
  12. #include <linux/ktime_api.h>
  13. #include <linux/sched/signal.h>
  14. #include <linux/syscalls_api.h>
  15. #include <linux/debug_locks.h>
  16. #include <linux/prefetch.h>
  17. #include <linux/capability.h>
  18. #include <linux/pgtable_api.h>
  19. #include <linux/wait_bit.h>
  20. #include <linux/jiffies.h>
  21. #include <linux/spinlock_api.h>
  22. #include <linux/cpumask_api.h>
  23. #include <linux/lockdep_api.h>
  24. #include <linux/hardirq.h>
  25. #include <linux/softirq.h>
  26. #include <linux/refcount_api.h>
  27. #include <linux/topology.h>
  28. #include <linux/sched/clock.h>
  29. #include <linux/sched/cond_resched.h>
  30. #include <linux/sched/cputime.h>
  31. #include <linux/sched/debug.h>
  32. #include <linux/sched/hotplug.h>
  33. #include <linux/sched/init.h>
  34. #include <linux/sched/isolation.h>
  35. #include <linux/sched/loadavg.h>
  36. #include <linux/sched/mm.h>
  37. #include <linux/sched/nohz.h>
  38. #include <linux/sched/rseq_api.h>
  39. #include <linux/sched/rt.h>
  40. #include <linux/blkdev.h>
  41. #include <linux/context_tracking.h>
  42. #include <linux/cpuset.h>
  43. #include <linux/delayacct.h>
  44. #include <linux/init_task.h>
  45. #include <linux/interrupt.h>
  46. #include <linux/ioprio.h>
  47. #include <linux/kallsyms.h>
  48. #include <linux/kcov.h>
  49. #include <linux/kprobes.h>
  50. #include <linux/llist_api.h>
  51. #include <linux/mmu_context.h>
  52. #include <linux/mmzone.h>
  53. #include <linux/mutex_api.h>
  54. #include <linux/nmi.h>
  55. #include <linux/nospec.h>
  56. #include <linux/perf_event_api.h>
  57. #include <linux/profile.h>
  58. #include <linux/psi.h>
  59. #include <linux/rcuwait_api.h>
  60. #include <linux/rseq.h>
  61. #include <linux/sched/wake_q.h>
  62. #include <linux/scs.h>
  63. #include <linux/slab.h>
  64. #include <linux/syscalls.h>
  65. #include <linux/vtime.h>
  66. #include <linux/wait_api.h>
  67. #include <linux/workqueue_api.h>
  68. #ifdef CONFIG_PREEMPT_DYNAMIC
  69. # ifdef CONFIG_GENERIC_ENTRY
  70. # include <linux/entry-common.h>
  71. # endif
  72. #endif
  73. #include <uapi/linux/sched/types.h>
  74. #include <asm/irq_regs.h>
  75. #include <asm/switch_to.h>
  76. #include <asm/tlb.h>
  77. #define CREATE_TRACE_POINTS
  78. #include <linux/sched/rseq_api.h>
  79. #include <trace/events/sched.h>
  80. #include <trace/events/ipi.h>
  81. #undef CREATE_TRACE_POINTS
  82. #include "sched.h"
  83. #include "stats.h"
  84. #include "autogroup.h"
  85. #include "pelt.h"
  86. #include "smp.h"
  87. #include "stats.h"
  88. #include "../workqueue_internal.h"
  89. #include "../../io_uring/io-wq.h"
  90. #include "../smpboot.h"
  91. EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpu);
  92. EXPORT_TRACEPOINT_SYMBOL_GPL(ipi_send_cpumask);
  93. /*
  94. * Export tracepoints that act as a bare tracehook (ie: have no trace event
  95. * associated with them) to allow external modules to probe them.
  96. */
  97. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_cfs_tp);
  98. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_rt_tp);
  99. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_dl_tp);
  100. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp);
  101. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_se_tp);
  102. EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_hw_tp);
  103. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_cpu_capacity_tp);
  104. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_overutilized_tp);
  105. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_cfs_tp);
  106. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_se_tp);
  107. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_update_nr_running_tp);
  108. EXPORT_TRACEPOINT_SYMBOL_GPL(sched_compute_energy_tp);
  109. DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
  110. #ifdef CONFIG_SCHED_DEBUG
  111. /*
  112. * Debugging: various feature bits
  113. *
  114. * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
  115. * sysctl_sched_features, defined in sched.h, to allow constants propagation
  116. * at compile time and compiler optimization based on features default.
  117. */
  118. #define SCHED_FEAT(name, enabled) \
  119. (1UL << __SCHED_FEAT_##name) * enabled |
  120. const_debug unsigned int sysctl_sched_features =
  121. #include "features.h"
  122. 0;
  123. #undef SCHED_FEAT
  124. /*
  125. * Print a warning if need_resched is set for the given duration (if
  126. * LATENCY_WARN is enabled).
  127. *
  128. * If sysctl_resched_latency_warn_once is set, only one warning will be shown
  129. * per boot.
  130. */
  131. __read_mostly int sysctl_resched_latency_warn_ms = 100;
  132. __read_mostly int sysctl_resched_latency_warn_once = 1;
  133. #endif /* CONFIG_SCHED_DEBUG */
  134. /*
  135. * Number of tasks to iterate in a single balance run.
  136. * Limited because this is done with IRQs disabled.
  137. */
  138. const_debug unsigned int sysctl_sched_nr_migrate = SCHED_NR_MIGRATE_BREAK;
  139. __read_mostly int scheduler_running;
  140. #ifdef CONFIG_SCHED_CORE
  141. DEFINE_STATIC_KEY_FALSE(__sched_core_enabled);
  142. /* kernel prio, less is more */
  143. static inline int __task_prio(const struct task_struct *p)
  144. {
  145. if (p->sched_class == &stop_sched_class) /* trumps deadline */
  146. return -2;
  147. if (p->dl_server)
  148. return -1; /* deadline */
  149. if (rt_or_dl_prio(p->prio))
  150. return p->prio; /* [-1, 99] */
  151. if (p->sched_class == &idle_sched_class)
  152. return MAX_RT_PRIO + NICE_WIDTH; /* 140 */
  153. if (task_on_scx(p))
  154. return MAX_RT_PRIO + MAX_NICE + 1; /* 120, squash ext */
  155. return MAX_RT_PRIO + MAX_NICE; /* 119, squash fair */
  156. }
  157. /*
  158. * l(a,b)
  159. * le(a,b) := !l(b,a)
  160. * g(a,b) := l(b,a)
  161. * ge(a,b) := !l(a,b)
  162. */
  163. /* real prio, less is less */
  164. static inline bool prio_less(const struct task_struct *a,
  165. const struct task_struct *b, bool in_fi)
  166. {
  167. int pa = __task_prio(a), pb = __task_prio(b);
  168. if (-pa < -pb)
  169. return true;
  170. if (-pb < -pa)
  171. return false;
  172. if (pa == -1) { /* dl_prio() doesn't work because of stop_class above */
  173. const struct sched_dl_entity *a_dl, *b_dl;
  174. a_dl = &a->dl;
  175. /*
  176. * Since,'a' and 'b' can be CFS tasks served by DL server,
  177. * __task_prio() can return -1 (for DL) even for those. In that
  178. * case, get to the dl_server's DL entity.
  179. */
  180. if (a->dl_server)
  181. a_dl = a->dl_server;
  182. b_dl = &b->dl;
  183. if (b->dl_server)
  184. b_dl = b->dl_server;
  185. return !dl_time_before(a_dl->deadline, b_dl->deadline);
  186. }
  187. if (pa == MAX_RT_PRIO + MAX_NICE) /* fair */
  188. return cfs_prio_less(a, b, in_fi);
  189. #ifdef CONFIG_SCHED_CLASS_EXT
  190. if (pa == MAX_RT_PRIO + MAX_NICE + 1) /* ext */
  191. return scx_prio_less(a, b, in_fi);
  192. #endif
  193. return false;
  194. }
  195. static inline bool __sched_core_less(const struct task_struct *a,
  196. const struct task_struct *b)
  197. {
  198. if (a->core_cookie < b->core_cookie)
  199. return true;
  200. if (a->core_cookie > b->core_cookie)
  201. return false;
  202. /* flip prio, so high prio is leftmost */
  203. if (prio_less(b, a, !!task_rq(a)->core->core_forceidle_count))
  204. return true;
  205. return false;
  206. }
  207. #define __node_2_sc(node) rb_entry((node), struct task_struct, core_node)
  208. static inline bool rb_sched_core_less(struct rb_node *a, const struct rb_node *b)
  209. {
  210. return __sched_core_less(__node_2_sc(a), __node_2_sc(b));
  211. }
  212. static inline int rb_sched_core_cmp(const void *key, const struct rb_node *node)
  213. {
  214. const struct task_struct *p = __node_2_sc(node);
  215. unsigned long cookie = (unsigned long)key;
  216. if (cookie < p->core_cookie)
  217. return -1;
  218. if (cookie > p->core_cookie)
  219. return 1;
  220. return 0;
  221. }
  222. void sched_core_enqueue(struct rq *rq, struct task_struct *p)
  223. {
  224. if (p->se.sched_delayed)
  225. return;
  226. rq->core->core_task_seq++;
  227. if (!p->core_cookie)
  228. return;
  229. rb_add(&p->core_node, &rq->core_tree, rb_sched_core_less);
  230. }
  231. void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags)
  232. {
  233. if (p->se.sched_delayed)
  234. return;
  235. rq->core->core_task_seq++;
  236. if (sched_core_enqueued(p)) {
  237. rb_erase(&p->core_node, &rq->core_tree);
  238. RB_CLEAR_NODE(&p->core_node);
  239. }
  240. /*
  241. * Migrating the last task off the cpu, with the cpu in forced idle
  242. * state. Reschedule to create an accounting edge for forced idle,
  243. * and re-examine whether the core is still in forced idle state.
  244. */
  245. if (!(flags & DEQUEUE_SAVE) && rq->nr_running == 1 &&
  246. rq->core->core_forceidle_count && rq->curr == rq->idle)
  247. resched_curr(rq);
  248. }
  249. static int sched_task_is_throttled(struct task_struct *p, int cpu)
  250. {
  251. if (p->sched_class->task_is_throttled)
  252. return p->sched_class->task_is_throttled(p, cpu);
  253. return 0;
  254. }
  255. static struct task_struct *sched_core_next(struct task_struct *p, unsigned long cookie)
  256. {
  257. struct rb_node *node = &p->core_node;
  258. int cpu = task_cpu(p);
  259. do {
  260. node = rb_next(node);
  261. if (!node)
  262. return NULL;
  263. p = __node_2_sc(node);
  264. if (p->core_cookie != cookie)
  265. return NULL;
  266. } while (sched_task_is_throttled(p, cpu));
  267. return p;
  268. }
  269. /*
  270. * Find left-most (aka, highest priority) and unthrottled task matching @cookie.
  271. * If no suitable task is found, NULL will be returned.
  272. */
  273. static struct task_struct *sched_core_find(struct rq *rq, unsigned long cookie)
  274. {
  275. struct task_struct *p;
  276. struct rb_node *node;
  277. node = rb_find_first((void *)cookie, &rq->core_tree, rb_sched_core_cmp);
  278. if (!node)
  279. return NULL;
  280. p = __node_2_sc(node);
  281. if (!sched_task_is_throttled(p, rq->cpu))
  282. return p;
  283. return sched_core_next(p, cookie);
  284. }
  285. /*
  286. * Magic required such that:
  287. *
  288. * raw_spin_rq_lock(rq);
  289. * ...
  290. * raw_spin_rq_unlock(rq);
  291. *
  292. * ends up locking and unlocking the _same_ lock, and all CPUs
  293. * always agree on what rq has what lock.
  294. *
  295. * XXX entirely possible to selectively enable cores, don't bother for now.
  296. */
  297. static DEFINE_MUTEX(sched_core_mutex);
  298. static atomic_t sched_core_count;
  299. static struct cpumask sched_core_mask;
  300. static void sched_core_lock(int cpu, unsigned long *flags)
  301. {
  302. const struct cpumask *smt_mask = cpu_smt_mask(cpu);
  303. int t, i = 0;
  304. local_irq_save(*flags);
  305. for_each_cpu(t, smt_mask)
  306. raw_spin_lock_nested(&cpu_rq(t)->__lock, i++);
  307. }
  308. static void sched_core_unlock(int cpu, unsigned long *flags)
  309. {
  310. const struct cpumask *smt_mask = cpu_smt_mask(cpu);
  311. int t;
  312. for_each_cpu(t, smt_mask)
  313. raw_spin_unlock(&cpu_rq(t)->__lock);
  314. local_irq_restore(*flags);
  315. }
  316. static void __sched_core_flip(bool enabled)
  317. {
  318. unsigned long flags;
  319. int cpu, t;
  320. cpus_read_lock();
  321. /*
  322. * Toggle the online cores, one by one.
  323. */
  324. cpumask_copy(&sched_core_mask, cpu_online_mask);
  325. for_each_cpu(cpu, &sched_core_mask) {
  326. const struct cpumask *smt_mask = cpu_smt_mask(cpu);
  327. sched_core_lock(cpu, &flags);
  328. for_each_cpu(t, smt_mask)
  329. cpu_rq(t)->core_enabled = enabled;
  330. cpu_rq(cpu)->core->core_forceidle_start = 0;
  331. sched_core_unlock(cpu, &flags);
  332. cpumask_andnot(&sched_core_mask, &sched_core_mask, smt_mask);
  333. }
  334. /*
  335. * Toggle the offline CPUs.
  336. */
  337. for_each_cpu_andnot(cpu, cpu_possible_mask, cpu_online_mask)
  338. cpu_rq(cpu)->core_enabled = enabled;
  339. cpus_read_unlock();
  340. }
  341. static void sched_core_assert_empty(void)
  342. {
  343. int cpu;
  344. for_each_possible_cpu(cpu)
  345. WARN_ON_ONCE(!RB_EMPTY_ROOT(&cpu_rq(cpu)->core_tree));
  346. }
  347. static void __sched_core_enable(void)
  348. {
  349. static_branch_enable(&__sched_core_enabled);
  350. /*
  351. * Ensure all previous instances of raw_spin_rq_*lock() have finished
  352. * and future ones will observe !sched_core_disabled().
  353. */
  354. synchronize_rcu();
  355. __sched_core_flip(true);
  356. sched_core_assert_empty();
  357. }
  358. static void __sched_core_disable(void)
  359. {
  360. sched_core_assert_empty();
  361. __sched_core_flip(false);
  362. static_branch_disable(&__sched_core_enabled);
  363. }
  364. void sched_core_get(void)
  365. {
  366. if (atomic_inc_not_zero(&sched_core_count))
  367. return;
  368. mutex_lock(&sched_core_mutex);
  369. if (!atomic_read(&sched_core_count))
  370. __sched_core_enable();
  371. smp_mb__before_atomic();
  372. atomic_inc(&sched_core_count);
  373. mutex_unlock(&sched_core_mutex);
  374. }
  375. static void __sched_core_put(struct work_struct *work)
  376. {
  377. if (atomic_dec_and_mutex_lock(&sched_core_count, &sched_core_mutex)) {
  378. __sched_core_disable();
  379. mutex_unlock(&sched_core_mutex);
  380. }
  381. }
  382. void sched_core_put(void)
  383. {
  384. static DECLARE_WORK(_work, __sched_core_put);
  385. /*
  386. * "There can be only one"
  387. *
  388. * Either this is the last one, or we don't actually need to do any
  389. * 'work'. If it is the last *again*, we rely on
  390. * WORK_STRUCT_PENDING_BIT.
  391. */
  392. if (!atomic_add_unless(&sched_core_count, -1, 1))
  393. schedule_work(&_work);
  394. }
  395. #else /* !CONFIG_SCHED_CORE */
  396. static inline void sched_core_enqueue(struct rq *rq, struct task_struct *p) { }
  397. static inline void
  398. sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) { }
  399. #endif /* CONFIG_SCHED_CORE */
  400. /*
  401. * Serialization rules:
  402. *
  403. * Lock order:
  404. *
  405. * p->pi_lock
  406. * rq->lock
  407. * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls)
  408. *
  409. * rq1->lock
  410. * rq2->lock where: rq1 < rq2
  411. *
  412. * Regular state:
  413. *
  414. * Normal scheduling state is serialized by rq->lock. __schedule() takes the
  415. * local CPU's rq->lock, it optionally removes the task from the runqueue and
  416. * always looks at the local rq data structures to find the most eligible task
  417. * to run next.
  418. *
  419. * Task enqueue is also under rq->lock, possibly taken from another CPU.
  420. * Wakeups from another LLC domain might use an IPI to transfer the enqueue to
  421. * the local CPU to avoid bouncing the runqueue state around [ see
  422. * ttwu_queue_wakelist() ]
  423. *
  424. * Task wakeup, specifically wakeups that involve migration, are horribly
  425. * complicated to avoid having to take two rq->locks.
  426. *
  427. * Special state:
  428. *
  429. * System-calls and anything external will use task_rq_lock() which acquires
  430. * both p->pi_lock and rq->lock. As a consequence the state they change is
  431. * stable while holding either lock:
  432. *
  433. * - sched_setaffinity()/
  434. * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed
  435. * - set_user_nice(): p->se.load, p->*prio
  436. * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio,
  437. * p->se.load, p->rt_priority,
  438. * p->dl.dl_{runtime, deadline, period, flags, bw, density}
  439. * - sched_setnuma(): p->numa_preferred_nid
  440. * - sched_move_task(): p->sched_task_group
  441. * - uclamp_update_active() p->uclamp*
  442. *
  443. * p->state <- TASK_*:
  444. *
  445. * is changed locklessly using set_current_state(), __set_current_state() or
  446. * set_special_state(), see their respective comments, or by
  447. * try_to_wake_up(). This latter uses p->pi_lock to serialize against
  448. * concurrent self.
  449. *
  450. * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }:
  451. *
  452. * is set by activate_task() and cleared by deactivate_task(), under
  453. * rq->lock. Non-zero indicates the task is runnable, the special
  454. * ON_RQ_MIGRATING state is used for migration without holding both
  455. * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock().
  456. *
  457. * Additionally it is possible to be ->on_rq but still be considered not
  458. * runnable when p->se.sched_delayed is true. These tasks are on the runqueue
  459. * but will be dequeued as soon as they get picked again. See the
  460. * task_is_runnable() helper.
  461. *
  462. * p->on_cpu <- { 0, 1 }:
  463. *
  464. * is set by prepare_task() and cleared by finish_task() such that it will be
  465. * set before p is scheduled-in and cleared after p is scheduled-out, both
  466. * under rq->lock. Non-zero indicates the task is running on its CPU.
  467. *
  468. * [ The astute reader will observe that it is possible for two tasks on one
  469. * CPU to have ->on_cpu = 1 at the same time. ]
  470. *
  471. * task_cpu(p): is changed by set_task_cpu(), the rules are:
  472. *
  473. * - Don't call set_task_cpu() on a blocked task:
  474. *
  475. * We don't care what CPU we're not running on, this simplifies hotplug,
  476. * the CPU assignment of blocked tasks isn't required to be valid.
  477. *
  478. * - for try_to_wake_up(), called under p->pi_lock:
  479. *
  480. * This allows try_to_wake_up() to only take one rq->lock, see its comment.
  481. *
  482. * - for migration called under rq->lock:
  483. * [ see task_on_rq_migrating() in task_rq_lock() ]
  484. *
  485. * o move_queued_task()
  486. * o detach_task()
  487. *
  488. * - for migration called under double_rq_lock():
  489. *
  490. * o __migrate_swap_task()
  491. * o push_rt_task() / pull_rt_task()
  492. * o push_dl_task() / pull_dl_task()
  493. * o dl_task_offline_migration()
  494. *
  495. */
  496. void raw_spin_rq_lock_nested(struct rq *rq, int subclass)
  497. {
  498. raw_spinlock_t *lock;
  499. /* Matches synchronize_rcu() in __sched_core_enable() */
  500. preempt_disable();
  501. if (sched_core_disabled()) {
  502. raw_spin_lock_nested(&rq->__lock, subclass);
  503. /* preempt_count *MUST* be > 1 */
  504. preempt_enable_no_resched();
  505. return;
  506. }
  507. for (;;) {
  508. lock = __rq_lockp(rq);
  509. raw_spin_lock_nested(lock, subclass);
  510. if (likely(lock == __rq_lockp(rq))) {
  511. /* preempt_count *MUST* be > 1 */
  512. preempt_enable_no_resched();
  513. return;
  514. }
  515. raw_spin_unlock(lock);
  516. }
  517. }
  518. bool raw_spin_rq_trylock(struct rq *rq)
  519. {
  520. raw_spinlock_t *lock;
  521. bool ret;
  522. /* Matches synchronize_rcu() in __sched_core_enable() */
  523. preempt_disable();
  524. if (sched_core_disabled()) {
  525. ret = raw_spin_trylock(&rq->__lock);
  526. preempt_enable();
  527. return ret;
  528. }
  529. for (;;) {
  530. lock = __rq_lockp(rq);
  531. ret = raw_spin_trylock(lock);
  532. if (!ret || (likely(lock == __rq_lockp(rq)))) {
  533. preempt_enable();
  534. return ret;
  535. }
  536. raw_spin_unlock(lock);
  537. }
  538. }
  539. void raw_spin_rq_unlock(struct rq *rq)
  540. {
  541. raw_spin_unlock(rq_lockp(rq));
  542. }
  543. #ifdef CONFIG_SMP
  544. /*
  545. * double_rq_lock - safely lock two runqueues
  546. */
  547. void double_rq_lock(struct rq *rq1, struct rq *rq2)
  548. {
  549. lockdep_assert_irqs_disabled();
  550. if (rq_order_less(rq2, rq1))
  551. swap(rq1, rq2);
  552. raw_spin_rq_lock(rq1);
  553. if (__rq_lockp(rq1) != __rq_lockp(rq2))
  554. raw_spin_rq_lock_nested(rq2, SINGLE_DEPTH_NESTING);
  555. double_rq_clock_clear_update(rq1, rq2);
  556. }
  557. #endif
  558. /*
  559. * __task_rq_lock - lock the rq @p resides on.
  560. */
  561. struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  562. __acquires(rq->lock)
  563. {
  564. struct rq *rq;
  565. lockdep_assert_held(&p->pi_lock);
  566. for (;;) {
  567. rq = task_rq(p);
  568. raw_spin_rq_lock(rq);
  569. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  570. rq_pin_lock(rq, rf);
  571. return rq;
  572. }
  573. raw_spin_rq_unlock(rq);
  574. while (unlikely(task_on_rq_migrating(p)))
  575. cpu_relax();
  576. }
  577. }
  578. /*
  579. * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
  580. */
  581. struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  582. __acquires(p->pi_lock)
  583. __acquires(rq->lock)
  584. {
  585. struct rq *rq;
  586. for (;;) {
  587. raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
  588. rq = task_rq(p);
  589. raw_spin_rq_lock(rq);
  590. /*
  591. * move_queued_task() task_rq_lock()
  592. *
  593. * ACQUIRE (rq->lock)
  594. * [S] ->on_rq = MIGRATING [L] rq = task_rq()
  595. * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
  596. * [S] ->cpu = new_cpu [L] task_rq()
  597. * [L] ->on_rq
  598. * RELEASE (rq->lock)
  599. *
  600. * If we observe the old CPU in task_rq_lock(), the acquire of
  601. * the old rq->lock will fully serialize against the stores.
  602. *
  603. * If we observe the new CPU in task_rq_lock(), the address
  604. * dependency headed by '[L] rq = task_rq()' and the acquire
  605. * will pair with the WMB to ensure we then also see migrating.
  606. */
  607. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  608. rq_pin_lock(rq, rf);
  609. return rq;
  610. }
  611. raw_spin_rq_unlock(rq);
  612. raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
  613. while (unlikely(task_on_rq_migrating(p)))
  614. cpu_relax();
  615. }
  616. }
  617. /*
  618. * RQ-clock updating methods:
  619. */
  620. static void update_rq_clock_task(struct rq *rq, s64 delta)
  621. {
  622. /*
  623. * In theory, the compile should just see 0 here, and optimize out the call
  624. * to sched_rt_avg_update. But I don't trust it...
  625. */
  626. s64 __maybe_unused steal = 0, irq_delta = 0;
  627. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  628. irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
  629. /*
  630. * Since irq_time is only updated on {soft,}irq_exit, we might run into
  631. * this case when a previous update_rq_clock() happened inside a
  632. * {soft,}IRQ region.
  633. *
  634. * When this happens, we stop ->clock_task and only update the
  635. * prev_irq_time stamp to account for the part that fit, so that a next
  636. * update will consume the rest. This ensures ->clock_task is
  637. * monotonic.
  638. *
  639. * It does however cause some slight miss-attribution of {soft,}IRQ
  640. * time, a more accurate solution would be to update the irq_time using
  641. * the current rq->clock timestamp, except that would require using
  642. * atomic ops.
  643. */
  644. if (irq_delta > delta)
  645. irq_delta = delta;
  646. rq->prev_irq_time += irq_delta;
  647. delta -= irq_delta;
  648. delayacct_irq(rq->curr, irq_delta);
  649. #endif
  650. #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
  651. if (static_key_false((&paravirt_steal_rq_enabled))) {
  652. u64 prev_steal;
  653. steal = prev_steal = paravirt_steal_clock(cpu_of(rq));
  654. steal -= rq->prev_steal_time_rq;
  655. if (unlikely(steal > delta))
  656. steal = delta;
  657. rq->prev_steal_time_rq = prev_steal;
  658. delta -= steal;
  659. }
  660. #endif
  661. rq->clock_task += delta;
  662. #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
  663. if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
  664. update_irq_load_avg(rq, irq_delta + steal);
  665. #endif
  666. update_rq_clock_pelt(rq, delta);
  667. }
  668. void update_rq_clock(struct rq *rq)
  669. {
  670. s64 delta;
  671. lockdep_assert_rq_held(rq);
  672. if (rq->clock_update_flags & RQCF_ACT_SKIP)
  673. return;
  674. #ifdef CONFIG_SCHED_DEBUG
  675. if (sched_feat(WARN_DOUBLE_CLOCK))
  676. SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
  677. rq->clock_update_flags |= RQCF_UPDATED;
  678. #endif
  679. delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
  680. if (delta < 0)
  681. return;
  682. rq->clock += delta;
  683. update_rq_clock_task(rq, delta);
  684. }
  685. #ifdef CONFIG_SCHED_HRTICK
  686. /*
  687. * Use HR-timers to deliver accurate preemption points.
  688. */
  689. static void hrtick_clear(struct rq *rq)
  690. {
  691. if (hrtimer_active(&rq->hrtick_timer))
  692. hrtimer_cancel(&rq->hrtick_timer);
  693. }
  694. /*
  695. * High-resolution timer tick.
  696. * Runs from hardirq context with interrupts disabled.
  697. */
  698. static enum hrtimer_restart hrtick(struct hrtimer *timer)
  699. {
  700. struct rq *rq = container_of(timer, struct rq, hrtick_timer);
  701. struct rq_flags rf;
  702. WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
  703. rq_lock(rq, &rf);
  704. update_rq_clock(rq);
  705. rq->curr->sched_class->task_tick(rq, rq->curr, 1);
  706. rq_unlock(rq, &rf);
  707. return HRTIMER_NORESTART;
  708. }
  709. #ifdef CONFIG_SMP
  710. static void __hrtick_restart(struct rq *rq)
  711. {
  712. struct hrtimer *timer = &rq->hrtick_timer;
  713. ktime_t time = rq->hrtick_time;
  714. hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD);
  715. }
  716. /*
  717. * called from hardirq (IPI) context
  718. */
  719. static void __hrtick_start(void *arg)
  720. {
  721. struct rq *rq = arg;
  722. struct rq_flags rf;
  723. rq_lock(rq, &rf);
  724. __hrtick_restart(rq);
  725. rq_unlock(rq, &rf);
  726. }
  727. /*
  728. * Called to set the hrtick timer state.
  729. *
  730. * called with rq->lock held and IRQs disabled
  731. */
  732. void hrtick_start(struct rq *rq, u64 delay)
  733. {
  734. struct hrtimer *timer = &rq->hrtick_timer;
  735. s64 delta;
  736. /*
  737. * Don't schedule slices shorter than 10000ns, that just
  738. * doesn't make sense and can cause timer DoS.
  739. */
  740. delta = max_t(s64, delay, 10000LL);
  741. rq->hrtick_time = ktime_add_ns(timer->base->get_time(), delta);
  742. if (rq == this_rq())
  743. __hrtick_restart(rq);
  744. else
  745. smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
  746. }
  747. #else
  748. /*
  749. * Called to set the hrtick timer state.
  750. *
  751. * called with rq->lock held and IRQs disabled
  752. */
  753. void hrtick_start(struct rq *rq, u64 delay)
  754. {
  755. /*
  756. * Don't schedule slices shorter than 10000ns, that just
  757. * doesn't make sense. Rely on vruntime for fairness.
  758. */
  759. delay = max_t(u64, delay, 10000LL);
  760. hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
  761. HRTIMER_MODE_REL_PINNED_HARD);
  762. }
  763. #endif /* CONFIG_SMP */
  764. static void hrtick_rq_init(struct rq *rq)
  765. {
  766. #ifdef CONFIG_SMP
  767. INIT_CSD(&rq->hrtick_csd, __hrtick_start, rq);
  768. #endif
  769. hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
  770. rq->hrtick_timer.function = hrtick;
  771. }
  772. #else /* CONFIG_SCHED_HRTICK */
  773. static inline void hrtick_clear(struct rq *rq)
  774. {
  775. }
  776. static inline void hrtick_rq_init(struct rq *rq)
  777. {
  778. }
  779. #endif /* CONFIG_SCHED_HRTICK */
  780. /*
  781. * try_cmpxchg based fetch_or() macro so it works for different integer types:
  782. */
  783. #define fetch_or(ptr, mask) \
  784. ({ \
  785. typeof(ptr) _ptr = (ptr); \
  786. typeof(mask) _mask = (mask); \
  787. typeof(*_ptr) _val = *_ptr; \
  788. \
  789. do { \
  790. } while (!try_cmpxchg(_ptr, &_val, _val | _mask)); \
  791. _val; \
  792. })
  793. #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
  794. /*
  795. * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
  796. * this avoids any races wrt polling state changes and thereby avoids
  797. * spurious IPIs.
  798. */
  799. static inline bool set_nr_and_not_polling(struct task_struct *p)
  800. {
  801. struct thread_info *ti = task_thread_info(p);
  802. return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
  803. }
  804. /*
  805. * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
  806. *
  807. * If this returns true, then the idle task promises to call
  808. * sched_ttwu_pending() and reschedule soon.
  809. */
  810. static bool set_nr_if_polling(struct task_struct *p)
  811. {
  812. struct thread_info *ti = task_thread_info(p);
  813. typeof(ti->flags) val = READ_ONCE(ti->flags);
  814. do {
  815. if (!(val & _TIF_POLLING_NRFLAG))
  816. return false;
  817. if (val & _TIF_NEED_RESCHED)
  818. return true;
  819. } while (!try_cmpxchg(&ti->flags, &val, val | _TIF_NEED_RESCHED));
  820. return true;
  821. }
  822. #else
  823. static inline bool set_nr_and_not_polling(struct task_struct *p)
  824. {
  825. set_tsk_need_resched(p);
  826. return true;
  827. }
  828. #ifdef CONFIG_SMP
  829. static inline bool set_nr_if_polling(struct task_struct *p)
  830. {
  831. return false;
  832. }
  833. #endif
  834. #endif
  835. static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
  836. {
  837. struct wake_q_node *node = &task->wake_q;
  838. /*
  839. * Atomically grab the task, if ->wake_q is !nil already it means
  840. * it's already queued (either by us or someone else) and will get the
  841. * wakeup due to that.
  842. *
  843. * In order to ensure that a pending wakeup will observe our pending
  844. * state, even in the failed case, an explicit smp_mb() must be used.
  845. */
  846. smp_mb__before_atomic();
  847. if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
  848. return false;
  849. /*
  850. * The head is context local, there can be no concurrency.
  851. */
  852. *head->lastp = node;
  853. head->lastp = &node->next;
  854. return true;
  855. }
  856. /**
  857. * wake_q_add() - queue a wakeup for 'later' waking.
  858. * @head: the wake_q_head to add @task to
  859. * @task: the task to queue for 'later' wakeup
  860. *
  861. * Queue a task for later wakeup, most likely by the wake_up_q() call in the
  862. * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
  863. * instantly.
  864. *
  865. * This function must be used as-if it were wake_up_process(); IOW the task
  866. * must be ready to be woken at this location.
  867. */
  868. void wake_q_add(struct wake_q_head *head, struct task_struct *task)
  869. {
  870. if (__wake_q_add(head, task))
  871. get_task_struct(task);
  872. }
  873. /**
  874. * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
  875. * @head: the wake_q_head to add @task to
  876. * @task: the task to queue for 'later' wakeup
  877. *
  878. * Queue a task for later wakeup, most likely by the wake_up_q() call in the
  879. * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
  880. * instantly.
  881. *
  882. * This function must be used as-if it were wake_up_process(); IOW the task
  883. * must be ready to be woken at this location.
  884. *
  885. * This function is essentially a task-safe equivalent to wake_q_add(). Callers
  886. * that already hold reference to @task can call the 'safe' version and trust
  887. * wake_q to do the right thing depending whether or not the @task is already
  888. * queued for wakeup.
  889. */
  890. void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
  891. {
  892. if (!__wake_q_add(head, task))
  893. put_task_struct(task);
  894. }
  895. void wake_up_q(struct wake_q_head *head)
  896. {
  897. struct wake_q_node *node = head->first;
  898. while (node != WAKE_Q_TAIL) {
  899. struct task_struct *task;
  900. task = container_of(node, struct task_struct, wake_q);
  901. /* Task can safely be re-inserted now: */
  902. node = node->next;
  903. task->wake_q.next = NULL;
  904. /*
  905. * wake_up_process() executes a full barrier, which pairs with
  906. * the queueing in wake_q_add() so as not to miss wakeups.
  907. */
  908. wake_up_process(task);
  909. put_task_struct(task);
  910. }
  911. }
  912. /*
  913. * resched_curr - mark rq's current task 'to be rescheduled now'.
  914. *
  915. * On UP this means the setting of the need_resched flag, on SMP it
  916. * might also involve a cross-CPU call to trigger the scheduler on
  917. * the target CPU.
  918. */
  919. void resched_curr(struct rq *rq)
  920. {
  921. struct task_struct *curr = rq->curr;
  922. int cpu;
  923. lockdep_assert_rq_held(rq);
  924. if (test_tsk_need_resched(curr))
  925. return;
  926. cpu = cpu_of(rq);
  927. if (cpu == smp_processor_id()) {
  928. set_tsk_need_resched(curr);
  929. set_preempt_need_resched();
  930. return;
  931. }
  932. if (set_nr_and_not_polling(curr))
  933. smp_send_reschedule(cpu);
  934. else
  935. trace_sched_wake_idle_without_ipi(cpu);
  936. }
  937. void resched_cpu(int cpu)
  938. {
  939. struct rq *rq = cpu_rq(cpu);
  940. unsigned long flags;
  941. raw_spin_rq_lock_irqsave(rq, flags);
  942. if (cpu_online(cpu) || cpu == smp_processor_id())
  943. resched_curr(rq);
  944. raw_spin_rq_unlock_irqrestore(rq, flags);
  945. }
  946. #ifdef CONFIG_SMP
  947. #ifdef CONFIG_NO_HZ_COMMON
  948. /*
  949. * In the semi idle case, use the nearest busy CPU for migrating timers
  950. * from an idle CPU. This is good for power-savings.
  951. *
  952. * We don't do similar optimization for completely idle system, as
  953. * selecting an idle CPU will add more delays to the timers than intended
  954. * (as that CPU's timer base may not be up to date wrt jiffies etc).
  955. */
  956. int get_nohz_timer_target(void)
  957. {
  958. int i, cpu = smp_processor_id(), default_cpu = -1;
  959. struct sched_domain *sd;
  960. const struct cpumask *hk_mask;
  961. if (housekeeping_cpu(cpu, HK_TYPE_TIMER)) {
  962. if (!idle_cpu(cpu))
  963. return cpu;
  964. default_cpu = cpu;
  965. }
  966. hk_mask = housekeeping_cpumask(HK_TYPE_TIMER);
  967. guard(rcu)();
  968. for_each_domain(cpu, sd) {
  969. for_each_cpu_and(i, sched_domain_span(sd), hk_mask) {
  970. if (cpu == i)
  971. continue;
  972. if (!idle_cpu(i))
  973. return i;
  974. }
  975. }
  976. if (default_cpu == -1)
  977. default_cpu = housekeeping_any_cpu(HK_TYPE_TIMER);
  978. return default_cpu;
  979. }
  980. /*
  981. * When add_timer_on() enqueues a timer into the timer wheel of an
  982. * idle CPU then this timer might expire before the next timer event
  983. * which is scheduled to wake up that CPU. In case of a completely
  984. * idle system the next event might even be infinite time into the
  985. * future. wake_up_idle_cpu() ensures that the CPU is woken up and
  986. * leaves the inner idle loop so the newly added timer is taken into
  987. * account when the CPU goes back to idle and evaluates the timer
  988. * wheel for the next timer event.
  989. */
  990. static void wake_up_idle_cpu(int cpu)
  991. {
  992. struct rq *rq = cpu_rq(cpu);
  993. if (cpu == smp_processor_id())
  994. return;
  995. /*
  996. * Set TIF_NEED_RESCHED and send an IPI if in the non-polling
  997. * part of the idle loop. This forces an exit from the idle loop
  998. * and a round trip to schedule(). Now this could be optimized
  999. * because a simple new idle loop iteration is enough to
  1000. * re-evaluate the next tick. Provided some re-ordering of tick
  1001. * nohz functions that would need to follow TIF_NR_POLLING
  1002. * clearing:
  1003. *
  1004. * - On most architectures, a simple fetch_or on ti::flags with a
  1005. * "0" value would be enough to know if an IPI needs to be sent.
  1006. *
  1007. * - x86 needs to perform a last need_resched() check between
  1008. * monitor and mwait which doesn't take timers into account.
  1009. * There a dedicated TIF_TIMER flag would be required to
  1010. * fetch_or here and be checked along with TIF_NEED_RESCHED
  1011. * before mwait().
  1012. *
  1013. * However, remote timer enqueue is not such a frequent event
  1014. * and testing of the above solutions didn't appear to report
  1015. * much benefits.
  1016. */
  1017. if (set_nr_and_not_polling(rq->idle))
  1018. smp_send_reschedule(cpu);
  1019. else
  1020. trace_sched_wake_idle_without_ipi(cpu);
  1021. }
  1022. static bool wake_up_full_nohz_cpu(int cpu)
  1023. {
  1024. /*
  1025. * We just need the target to call irq_exit() and re-evaluate
  1026. * the next tick. The nohz full kick at least implies that.
  1027. * If needed we can still optimize that later with an
  1028. * empty IRQ.
  1029. */
  1030. if (cpu_is_offline(cpu))
  1031. return true; /* Don't try to wake offline CPUs. */
  1032. if (tick_nohz_full_cpu(cpu)) {
  1033. if (cpu != smp_processor_id() ||
  1034. tick_nohz_tick_stopped())
  1035. tick_nohz_full_kick_cpu(cpu);
  1036. return true;
  1037. }
  1038. return false;
  1039. }
  1040. /*
  1041. * Wake up the specified CPU. If the CPU is going offline, it is the
  1042. * caller's responsibility to deal with the lost wakeup, for example,
  1043. * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
  1044. */
  1045. void wake_up_nohz_cpu(int cpu)
  1046. {
  1047. if (!wake_up_full_nohz_cpu(cpu))
  1048. wake_up_idle_cpu(cpu);
  1049. }
  1050. static void nohz_csd_func(void *info)
  1051. {
  1052. struct rq *rq = info;
  1053. int cpu = cpu_of(rq);
  1054. unsigned int flags;
  1055. /*
  1056. * Release the rq::nohz_csd.
  1057. */
  1058. flags = atomic_fetch_andnot(NOHZ_KICK_MASK | NOHZ_NEWILB_KICK, nohz_flags(cpu));
  1059. WARN_ON(!(flags & NOHZ_KICK_MASK));
  1060. rq->idle_balance = idle_cpu(cpu);
  1061. if (rq->idle_balance) {
  1062. rq->nohz_idle_balance = flags;
  1063. __raise_softirq_irqoff(SCHED_SOFTIRQ);
  1064. }
  1065. }
  1066. #endif /* CONFIG_NO_HZ_COMMON */
  1067. #ifdef CONFIG_NO_HZ_FULL
  1068. static inline bool __need_bw_check(struct rq *rq, struct task_struct *p)
  1069. {
  1070. if (rq->nr_running != 1)
  1071. return false;
  1072. if (p->sched_class != &fair_sched_class)
  1073. return false;
  1074. if (!task_on_rq_queued(p))
  1075. return false;
  1076. return true;
  1077. }
  1078. bool sched_can_stop_tick(struct rq *rq)
  1079. {
  1080. int fifo_nr_running;
  1081. /* Deadline tasks, even if single, need the tick */
  1082. if (rq->dl.dl_nr_running)
  1083. return false;
  1084. /*
  1085. * If there are more than one RR tasks, we need the tick to affect the
  1086. * actual RR behaviour.
  1087. */
  1088. if (rq->rt.rr_nr_running) {
  1089. if (rq->rt.rr_nr_running == 1)
  1090. return true;
  1091. else
  1092. return false;
  1093. }
  1094. /*
  1095. * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
  1096. * forced preemption between FIFO tasks.
  1097. */
  1098. fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
  1099. if (fifo_nr_running)
  1100. return true;
  1101. /*
  1102. * If there are no DL,RR/FIFO tasks, there must only be CFS or SCX tasks
  1103. * left. For CFS, if there's more than one we need the tick for
  1104. * involuntary preemption. For SCX, ask.
  1105. */
  1106. if (scx_enabled() && !scx_can_stop_tick(rq))
  1107. return false;
  1108. if (rq->cfs.h_nr_running > 1)
  1109. return false;
  1110. /*
  1111. * If there is one task and it has CFS runtime bandwidth constraints
  1112. * and it's on the cpu now we don't want to stop the tick.
  1113. * This check prevents clearing the bit if a newly enqueued task here is
  1114. * dequeued by migrating while the constrained task continues to run.
  1115. * E.g. going from 2->1 without going through pick_next_task().
  1116. */
  1117. if (__need_bw_check(rq, rq->curr)) {
  1118. if (cfs_task_bw_constrained(rq->curr))
  1119. return false;
  1120. }
  1121. return true;
  1122. }
  1123. #endif /* CONFIG_NO_HZ_FULL */
  1124. #endif /* CONFIG_SMP */
  1125. #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
  1126. (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
  1127. /*
  1128. * Iterate task_group tree rooted at *from, calling @down when first entering a
  1129. * node and @up when leaving it for the final time.
  1130. *
  1131. * Caller must hold rcu_lock or sufficient equivalent.
  1132. */
  1133. int walk_tg_tree_from(struct task_group *from,
  1134. tg_visitor down, tg_visitor up, void *data)
  1135. {
  1136. struct task_group *parent, *child;
  1137. int ret;
  1138. parent = from;
  1139. down:
  1140. ret = (*down)(parent, data);
  1141. if (ret)
  1142. goto out;
  1143. list_for_each_entry_rcu(child, &parent->children, siblings) {
  1144. parent = child;
  1145. goto down;
  1146. up:
  1147. continue;
  1148. }
  1149. ret = (*up)(parent, data);
  1150. if (ret || parent == from)
  1151. goto out;
  1152. child = parent;
  1153. parent = parent->parent;
  1154. if (parent)
  1155. goto up;
  1156. out:
  1157. return ret;
  1158. }
  1159. int tg_nop(struct task_group *tg, void *data)
  1160. {
  1161. return 0;
  1162. }
  1163. #endif
  1164. void set_load_weight(struct task_struct *p, bool update_load)
  1165. {
  1166. int prio = p->static_prio - MAX_RT_PRIO;
  1167. struct load_weight lw;
  1168. if (task_has_idle_policy(p)) {
  1169. lw.weight = scale_load(WEIGHT_IDLEPRIO);
  1170. lw.inv_weight = WMULT_IDLEPRIO;
  1171. } else {
  1172. lw.weight = scale_load(sched_prio_to_weight[prio]);
  1173. lw.inv_weight = sched_prio_to_wmult[prio];
  1174. }
  1175. /*
  1176. * SCHED_OTHER tasks have to update their load when changing their
  1177. * weight
  1178. */
  1179. if (update_load && p->sched_class->reweight_task)
  1180. p->sched_class->reweight_task(task_rq(p), p, &lw);
  1181. else
  1182. p->se.load = lw;
  1183. }
  1184. #ifdef CONFIG_UCLAMP_TASK
  1185. /*
  1186. * Serializes updates of utilization clamp values
  1187. *
  1188. * The (slow-path) user-space triggers utilization clamp value updates which
  1189. * can require updates on (fast-path) scheduler's data structures used to
  1190. * support enqueue/dequeue operations.
  1191. * While the per-CPU rq lock protects fast-path update operations, user-space
  1192. * requests are serialized using a mutex to reduce the risk of conflicting
  1193. * updates or API abuses.
  1194. */
  1195. static DEFINE_MUTEX(uclamp_mutex);
  1196. /* Max allowed minimum utilization */
  1197. static unsigned int __maybe_unused sysctl_sched_uclamp_util_min = SCHED_CAPACITY_SCALE;
  1198. /* Max allowed maximum utilization */
  1199. static unsigned int __maybe_unused sysctl_sched_uclamp_util_max = SCHED_CAPACITY_SCALE;
  1200. /*
  1201. * By default RT tasks run at the maximum performance point/capacity of the
  1202. * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to
  1203. * SCHED_CAPACITY_SCALE.
  1204. *
  1205. * This knob allows admins to change the default behavior when uclamp is being
  1206. * used. In battery powered devices, particularly, running at the maximum
  1207. * capacity and frequency will increase energy consumption and shorten the
  1208. * battery life.
  1209. *
  1210. * This knob only affects RT tasks that their uclamp_se->user_defined == false.
  1211. *
  1212. * This knob will not override the system default sched_util_clamp_min defined
  1213. * above.
  1214. */
  1215. unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE;
  1216. /* All clamps are required to be less or equal than these values */
  1217. static struct uclamp_se uclamp_default[UCLAMP_CNT];
  1218. /*
  1219. * This static key is used to reduce the uclamp overhead in the fast path. It
  1220. * primarily disables the call to uclamp_rq_{inc, dec}() in
  1221. * enqueue/dequeue_task().
  1222. *
  1223. * This allows users to continue to enable uclamp in their kernel config with
  1224. * minimum uclamp overhead in the fast path.
  1225. *
  1226. * As soon as userspace modifies any of the uclamp knobs, the static key is
  1227. * enabled, since we have an actual users that make use of uclamp
  1228. * functionality.
  1229. *
  1230. * The knobs that would enable this static key are:
  1231. *
  1232. * * A task modifying its uclamp value with sched_setattr().
  1233. * * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs.
  1234. * * An admin modifying the cgroup cpu.uclamp.{min, max}
  1235. */
  1236. DEFINE_STATIC_KEY_FALSE(sched_uclamp_used);
  1237. static inline unsigned int
  1238. uclamp_idle_value(struct rq *rq, enum uclamp_id clamp_id,
  1239. unsigned int clamp_value)
  1240. {
  1241. /*
  1242. * Avoid blocked utilization pushing up the frequency when we go
  1243. * idle (which drops the max-clamp) by retaining the last known
  1244. * max-clamp.
  1245. */
  1246. if (clamp_id == UCLAMP_MAX) {
  1247. rq->uclamp_flags |= UCLAMP_FLAG_IDLE;
  1248. return clamp_value;
  1249. }
  1250. return uclamp_none(UCLAMP_MIN);
  1251. }
  1252. static inline void uclamp_idle_reset(struct rq *rq, enum uclamp_id clamp_id,
  1253. unsigned int clamp_value)
  1254. {
  1255. /* Reset max-clamp retention only on idle exit */
  1256. if (!(rq->uclamp_flags & UCLAMP_FLAG_IDLE))
  1257. return;
  1258. uclamp_rq_set(rq, clamp_id, clamp_value);
  1259. }
  1260. static inline
  1261. unsigned int uclamp_rq_max_value(struct rq *rq, enum uclamp_id clamp_id,
  1262. unsigned int clamp_value)
  1263. {
  1264. struct uclamp_bucket *bucket = rq->uclamp[clamp_id].bucket;
  1265. int bucket_id = UCLAMP_BUCKETS - 1;
  1266. /*
  1267. * Since both min and max clamps are max aggregated, find the
  1268. * top most bucket with tasks in.
  1269. */
  1270. for ( ; bucket_id >= 0; bucket_id--) {
  1271. if (!bucket[bucket_id].tasks)
  1272. continue;
  1273. return bucket[bucket_id].value;
  1274. }
  1275. /* No tasks -- default clamp values */
  1276. return uclamp_idle_value(rq, clamp_id, clamp_value);
  1277. }
  1278. static void __uclamp_update_util_min_rt_default(struct task_struct *p)
  1279. {
  1280. unsigned int default_util_min;
  1281. struct uclamp_se *uc_se;
  1282. lockdep_assert_held(&p->pi_lock);
  1283. uc_se = &p->uclamp_req[UCLAMP_MIN];
  1284. /* Only sync if user didn't override the default */
  1285. if (uc_se->user_defined)
  1286. return;
  1287. default_util_min = sysctl_sched_uclamp_util_min_rt_default;
  1288. uclamp_se_set(uc_se, default_util_min, false);
  1289. }
  1290. static void uclamp_update_util_min_rt_default(struct task_struct *p)
  1291. {
  1292. if (!rt_task(p))
  1293. return;
  1294. /* Protect updates to p->uclamp_* */
  1295. guard(task_rq_lock)(p);
  1296. __uclamp_update_util_min_rt_default(p);
  1297. }
  1298. static inline struct uclamp_se
  1299. uclamp_tg_restrict(struct task_struct *p, enum uclamp_id clamp_id)
  1300. {
  1301. /* Copy by value as we could modify it */
  1302. struct uclamp_se uc_req = p->uclamp_req[clamp_id];
  1303. #ifdef CONFIG_UCLAMP_TASK_GROUP
  1304. unsigned int tg_min, tg_max, value;
  1305. /*
  1306. * Tasks in autogroups or root task group will be
  1307. * restricted by system defaults.
  1308. */
  1309. if (task_group_is_autogroup(task_group(p)))
  1310. return uc_req;
  1311. if (task_group(p) == &root_task_group)
  1312. return uc_req;
  1313. tg_min = task_group(p)->uclamp[UCLAMP_MIN].value;
  1314. tg_max = task_group(p)->uclamp[UCLAMP_MAX].value;
  1315. value = uc_req.value;
  1316. value = clamp(value, tg_min, tg_max);
  1317. uclamp_se_set(&uc_req, value, false);
  1318. #endif
  1319. return uc_req;
  1320. }
  1321. /*
  1322. * The effective clamp bucket index of a task depends on, by increasing
  1323. * priority:
  1324. * - the task specific clamp value, when explicitly requested from userspace
  1325. * - the task group effective clamp value, for tasks not either in the root
  1326. * group or in an autogroup
  1327. * - the system default clamp value, defined by the sysadmin
  1328. */
  1329. static inline struct uclamp_se
  1330. uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id)
  1331. {
  1332. struct uclamp_se uc_req = uclamp_tg_restrict(p, clamp_id);
  1333. struct uclamp_se uc_max = uclamp_default[clamp_id];
  1334. /* System default restrictions always apply */
  1335. if (unlikely(uc_req.value > uc_max.value))
  1336. return uc_max;
  1337. return uc_req;
  1338. }
  1339. unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id)
  1340. {
  1341. struct uclamp_se uc_eff;
  1342. /* Task currently refcounted: use back-annotated (effective) value */
  1343. if (p->uclamp[clamp_id].active)
  1344. return (unsigned long)p->uclamp[clamp_id].value;
  1345. uc_eff = uclamp_eff_get(p, clamp_id);
  1346. return (unsigned long)uc_eff.value;
  1347. }
  1348. /*
  1349. * When a task is enqueued on a rq, the clamp bucket currently defined by the
  1350. * task's uclamp::bucket_id is refcounted on that rq. This also immediately
  1351. * updates the rq's clamp value if required.
  1352. *
  1353. * Tasks can have a task-specific value requested from user-space, track
  1354. * within each bucket the maximum value for tasks refcounted in it.
  1355. * This "local max aggregation" allows to track the exact "requested" value
  1356. * for each bucket when all its RUNNABLE tasks require the same clamp.
  1357. */
  1358. static inline void uclamp_rq_inc_id(struct rq *rq, struct task_struct *p,
  1359. enum uclamp_id clamp_id)
  1360. {
  1361. struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
  1362. struct uclamp_se *uc_se = &p->uclamp[clamp_id];
  1363. struct uclamp_bucket *bucket;
  1364. lockdep_assert_rq_held(rq);
  1365. /* Update task effective clamp */
  1366. p->uclamp[clamp_id] = uclamp_eff_get(p, clamp_id);
  1367. bucket = &uc_rq->bucket[uc_se->bucket_id];
  1368. bucket->tasks++;
  1369. uc_se->active = true;
  1370. uclamp_idle_reset(rq, clamp_id, uc_se->value);
  1371. /*
  1372. * Local max aggregation: rq buckets always track the max
  1373. * "requested" clamp value of its RUNNABLE tasks.
  1374. */
  1375. if (bucket->tasks == 1 || uc_se->value > bucket->value)
  1376. bucket->value = uc_se->value;
  1377. if (uc_se->value > uclamp_rq_get(rq, clamp_id))
  1378. uclamp_rq_set(rq, clamp_id, uc_se->value);
  1379. }
  1380. /*
  1381. * When a task is dequeued from a rq, the clamp bucket refcounted by the task
  1382. * is released. If this is the last task reference counting the rq's max
  1383. * active clamp value, then the rq's clamp value is updated.
  1384. *
  1385. * Both refcounted tasks and rq's cached clamp values are expected to be
  1386. * always valid. If it's detected they are not, as defensive programming,
  1387. * enforce the expected state and warn.
  1388. */
  1389. static inline void uclamp_rq_dec_id(struct rq *rq, struct task_struct *p,
  1390. enum uclamp_id clamp_id)
  1391. {
  1392. struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
  1393. struct uclamp_se *uc_se = &p->uclamp[clamp_id];
  1394. struct uclamp_bucket *bucket;
  1395. unsigned int bkt_clamp;
  1396. unsigned int rq_clamp;
  1397. lockdep_assert_rq_held(rq);
  1398. /*
  1399. * If sched_uclamp_used was enabled after task @p was enqueued,
  1400. * we could end up with unbalanced call to uclamp_rq_dec_id().
  1401. *
  1402. * In this case the uc_se->active flag should be false since no uclamp
  1403. * accounting was performed at enqueue time and we can just return
  1404. * here.
  1405. *
  1406. * Need to be careful of the following enqueue/dequeue ordering
  1407. * problem too
  1408. *
  1409. * enqueue(taskA)
  1410. * // sched_uclamp_used gets enabled
  1411. * enqueue(taskB)
  1412. * dequeue(taskA)
  1413. * // Must not decrement bucket->tasks here
  1414. * dequeue(taskB)
  1415. *
  1416. * where we could end up with stale data in uc_se and
  1417. * bucket[uc_se->bucket_id].
  1418. *
  1419. * The following check here eliminates the possibility of such race.
  1420. */
  1421. if (unlikely(!uc_se->active))
  1422. return;
  1423. bucket = &uc_rq->bucket[uc_se->bucket_id];
  1424. SCHED_WARN_ON(!bucket->tasks);
  1425. if (likely(bucket->tasks))
  1426. bucket->tasks--;
  1427. uc_se->active = false;
  1428. /*
  1429. * Keep "local max aggregation" simple and accept to (possibly)
  1430. * overboost some RUNNABLE tasks in the same bucket.
  1431. * The rq clamp bucket value is reset to its base value whenever
  1432. * there are no more RUNNABLE tasks refcounting it.
  1433. */
  1434. if (likely(bucket->tasks))
  1435. return;
  1436. rq_clamp = uclamp_rq_get(rq, clamp_id);
  1437. /*
  1438. * Defensive programming: this should never happen. If it happens,
  1439. * e.g. due to future modification, warn and fix up the expected value.
  1440. */
  1441. SCHED_WARN_ON(bucket->value > rq_clamp);
  1442. if (bucket->value >= rq_clamp) {
  1443. bkt_clamp = uclamp_rq_max_value(rq, clamp_id, uc_se->value);
  1444. uclamp_rq_set(rq, clamp_id, bkt_clamp);
  1445. }
  1446. }
  1447. static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p)
  1448. {
  1449. enum uclamp_id clamp_id;
  1450. /*
  1451. * Avoid any overhead until uclamp is actually used by the userspace.
  1452. *
  1453. * The condition is constructed such that a NOP is generated when
  1454. * sched_uclamp_used is disabled.
  1455. */
  1456. if (!static_branch_unlikely(&sched_uclamp_used))
  1457. return;
  1458. if (unlikely(!p->sched_class->uclamp_enabled))
  1459. return;
  1460. if (p->se.sched_delayed)
  1461. return;
  1462. for_each_clamp_id(clamp_id)
  1463. uclamp_rq_inc_id(rq, p, clamp_id);
  1464. /* Reset clamp idle holding when there is one RUNNABLE task */
  1465. if (rq->uclamp_flags & UCLAMP_FLAG_IDLE)
  1466. rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
  1467. }
  1468. static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p)
  1469. {
  1470. enum uclamp_id clamp_id;
  1471. /*
  1472. * Avoid any overhead until uclamp is actually used by the userspace.
  1473. *
  1474. * The condition is constructed such that a NOP is generated when
  1475. * sched_uclamp_used is disabled.
  1476. */
  1477. if (!static_branch_unlikely(&sched_uclamp_used))
  1478. return;
  1479. if (unlikely(!p->sched_class->uclamp_enabled))
  1480. return;
  1481. if (p->se.sched_delayed)
  1482. return;
  1483. for_each_clamp_id(clamp_id)
  1484. uclamp_rq_dec_id(rq, p, clamp_id);
  1485. }
  1486. static inline void uclamp_rq_reinc_id(struct rq *rq, struct task_struct *p,
  1487. enum uclamp_id clamp_id)
  1488. {
  1489. if (!p->uclamp[clamp_id].active)
  1490. return;
  1491. uclamp_rq_dec_id(rq, p, clamp_id);
  1492. uclamp_rq_inc_id(rq, p, clamp_id);
  1493. /*
  1494. * Make sure to clear the idle flag if we've transiently reached 0
  1495. * active tasks on rq.
  1496. */
  1497. if (clamp_id == UCLAMP_MAX && (rq->uclamp_flags & UCLAMP_FLAG_IDLE))
  1498. rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
  1499. }
  1500. static inline void
  1501. uclamp_update_active(struct task_struct *p)
  1502. {
  1503. enum uclamp_id clamp_id;
  1504. struct rq_flags rf;
  1505. struct rq *rq;
  1506. /*
  1507. * Lock the task and the rq where the task is (or was) queued.
  1508. *
  1509. * We might lock the (previous) rq of a !RUNNABLE task, but that's the
  1510. * price to pay to safely serialize util_{min,max} updates with
  1511. * enqueues, dequeues and migration operations.
  1512. * This is the same locking schema used by __set_cpus_allowed_ptr().
  1513. */
  1514. rq = task_rq_lock(p, &rf);
  1515. /*
  1516. * Setting the clamp bucket is serialized by task_rq_lock().
  1517. * If the task is not yet RUNNABLE and its task_struct is not
  1518. * affecting a valid clamp bucket, the next time it's enqueued,
  1519. * it will already see the updated clamp bucket value.
  1520. */
  1521. for_each_clamp_id(clamp_id)
  1522. uclamp_rq_reinc_id(rq, p, clamp_id);
  1523. task_rq_unlock(rq, p, &rf);
  1524. }
  1525. #ifdef CONFIG_UCLAMP_TASK_GROUP
  1526. static inline void
  1527. uclamp_update_active_tasks(struct cgroup_subsys_state *css)
  1528. {
  1529. struct css_task_iter it;
  1530. struct task_struct *p;
  1531. css_task_iter_start(css, 0, &it);
  1532. while ((p = css_task_iter_next(&it)))
  1533. uclamp_update_active(p);
  1534. css_task_iter_end(&it);
  1535. }
  1536. static void cpu_util_update_eff(struct cgroup_subsys_state *css);
  1537. #endif
  1538. #ifdef CONFIG_SYSCTL
  1539. #ifdef CONFIG_UCLAMP_TASK_GROUP
  1540. static void uclamp_update_root_tg(void)
  1541. {
  1542. struct task_group *tg = &root_task_group;
  1543. uclamp_se_set(&tg->uclamp_req[UCLAMP_MIN],
  1544. sysctl_sched_uclamp_util_min, false);
  1545. uclamp_se_set(&tg->uclamp_req[UCLAMP_MAX],
  1546. sysctl_sched_uclamp_util_max, false);
  1547. guard(rcu)();
  1548. cpu_util_update_eff(&root_task_group.css);
  1549. }
  1550. #else
  1551. static void uclamp_update_root_tg(void) { }
  1552. #endif
  1553. static void uclamp_sync_util_min_rt_default(void)
  1554. {
  1555. struct task_struct *g, *p;
  1556. /*
  1557. * copy_process() sysctl_uclamp
  1558. * uclamp_min_rt = X;
  1559. * write_lock(&tasklist_lock) read_lock(&tasklist_lock)
  1560. * // link thread smp_mb__after_spinlock()
  1561. * write_unlock(&tasklist_lock) read_unlock(&tasklist_lock);
  1562. * sched_post_fork() for_each_process_thread()
  1563. * __uclamp_sync_rt() __uclamp_sync_rt()
  1564. *
  1565. * Ensures that either sched_post_fork() will observe the new
  1566. * uclamp_min_rt or for_each_process_thread() will observe the new
  1567. * task.
  1568. */
  1569. read_lock(&tasklist_lock);
  1570. smp_mb__after_spinlock();
  1571. read_unlock(&tasklist_lock);
  1572. guard(rcu)();
  1573. for_each_process_thread(g, p)
  1574. uclamp_update_util_min_rt_default(p);
  1575. }
  1576. static int sysctl_sched_uclamp_handler(const struct ctl_table *table, int write,
  1577. void *buffer, size_t *lenp, loff_t *ppos)
  1578. {
  1579. bool update_root_tg = false;
  1580. int old_min, old_max, old_min_rt;
  1581. int result;
  1582. guard(mutex)(&uclamp_mutex);
  1583. old_min = sysctl_sched_uclamp_util_min;
  1584. old_max = sysctl_sched_uclamp_util_max;
  1585. old_min_rt = sysctl_sched_uclamp_util_min_rt_default;
  1586. result = proc_dointvec(table, write, buffer, lenp, ppos);
  1587. if (result)
  1588. goto undo;
  1589. if (!write)
  1590. return 0;
  1591. if (sysctl_sched_uclamp_util_min > sysctl_sched_uclamp_util_max ||
  1592. sysctl_sched_uclamp_util_max > SCHED_CAPACITY_SCALE ||
  1593. sysctl_sched_uclamp_util_min_rt_default > SCHED_CAPACITY_SCALE) {
  1594. result = -EINVAL;
  1595. goto undo;
  1596. }
  1597. if (old_min != sysctl_sched_uclamp_util_min) {
  1598. uclamp_se_set(&uclamp_default[UCLAMP_MIN],
  1599. sysctl_sched_uclamp_util_min, false);
  1600. update_root_tg = true;
  1601. }
  1602. if (old_max != sysctl_sched_uclamp_util_max) {
  1603. uclamp_se_set(&uclamp_default[UCLAMP_MAX],
  1604. sysctl_sched_uclamp_util_max, false);
  1605. update_root_tg = true;
  1606. }
  1607. if (update_root_tg) {
  1608. static_branch_enable(&sched_uclamp_used);
  1609. uclamp_update_root_tg();
  1610. }
  1611. if (old_min_rt != sysctl_sched_uclamp_util_min_rt_default) {
  1612. static_branch_enable(&sched_uclamp_used);
  1613. uclamp_sync_util_min_rt_default();
  1614. }
  1615. /*
  1616. * We update all RUNNABLE tasks only when task groups are in use.
  1617. * Otherwise, keep it simple and do just a lazy update at each next
  1618. * task enqueue time.
  1619. */
  1620. return 0;
  1621. undo:
  1622. sysctl_sched_uclamp_util_min = old_min;
  1623. sysctl_sched_uclamp_util_max = old_max;
  1624. sysctl_sched_uclamp_util_min_rt_default = old_min_rt;
  1625. return result;
  1626. }
  1627. #endif
  1628. static void uclamp_fork(struct task_struct *p)
  1629. {
  1630. enum uclamp_id clamp_id;
  1631. /*
  1632. * We don't need to hold task_rq_lock() when updating p->uclamp_* here
  1633. * as the task is still at its early fork stages.
  1634. */
  1635. for_each_clamp_id(clamp_id)
  1636. p->uclamp[clamp_id].active = false;
  1637. if (likely(!p->sched_reset_on_fork))
  1638. return;
  1639. for_each_clamp_id(clamp_id) {
  1640. uclamp_se_set(&p->uclamp_req[clamp_id],
  1641. uclamp_none(clamp_id), false);
  1642. }
  1643. }
  1644. static void uclamp_post_fork(struct task_struct *p)
  1645. {
  1646. uclamp_update_util_min_rt_default(p);
  1647. }
  1648. static void __init init_uclamp_rq(struct rq *rq)
  1649. {
  1650. enum uclamp_id clamp_id;
  1651. struct uclamp_rq *uc_rq = rq->uclamp;
  1652. for_each_clamp_id(clamp_id) {
  1653. uc_rq[clamp_id] = (struct uclamp_rq) {
  1654. .value = uclamp_none(clamp_id)
  1655. };
  1656. }
  1657. rq->uclamp_flags = UCLAMP_FLAG_IDLE;
  1658. }
  1659. static void __init init_uclamp(void)
  1660. {
  1661. struct uclamp_se uc_max = {};
  1662. enum uclamp_id clamp_id;
  1663. int cpu;
  1664. for_each_possible_cpu(cpu)
  1665. init_uclamp_rq(cpu_rq(cpu));
  1666. for_each_clamp_id(clamp_id) {
  1667. uclamp_se_set(&init_task.uclamp_req[clamp_id],
  1668. uclamp_none(clamp_id), false);
  1669. }
  1670. /* System defaults allow max clamp values for both indexes */
  1671. uclamp_se_set(&uc_max, uclamp_none(UCLAMP_MAX), false);
  1672. for_each_clamp_id(clamp_id) {
  1673. uclamp_default[clamp_id] = uc_max;
  1674. #ifdef CONFIG_UCLAMP_TASK_GROUP
  1675. root_task_group.uclamp_req[clamp_id] = uc_max;
  1676. root_task_group.uclamp[clamp_id] = uc_max;
  1677. #endif
  1678. }
  1679. }
  1680. #else /* !CONFIG_UCLAMP_TASK */
  1681. static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { }
  1682. static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { }
  1683. static inline void uclamp_fork(struct task_struct *p) { }
  1684. static inline void uclamp_post_fork(struct task_struct *p) { }
  1685. static inline void init_uclamp(void) { }
  1686. #endif /* CONFIG_UCLAMP_TASK */
  1687. bool sched_task_on_rq(struct task_struct *p)
  1688. {
  1689. return task_on_rq_queued(p);
  1690. }
  1691. unsigned long get_wchan(struct task_struct *p)
  1692. {
  1693. unsigned long ip = 0;
  1694. unsigned int state;
  1695. if (!p || p == current)
  1696. return 0;
  1697. /* Only get wchan if task is blocked and we can keep it that way. */
  1698. raw_spin_lock_irq(&p->pi_lock);
  1699. state = READ_ONCE(p->__state);
  1700. smp_rmb(); /* see try_to_wake_up() */
  1701. if (state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq)
  1702. ip = __get_wchan(p);
  1703. raw_spin_unlock_irq(&p->pi_lock);
  1704. return ip;
  1705. }
  1706. void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
  1707. {
  1708. if (!(flags & ENQUEUE_NOCLOCK))
  1709. update_rq_clock(rq);
  1710. p->sched_class->enqueue_task(rq, p, flags);
  1711. /*
  1712. * Must be after ->enqueue_task() because ENQUEUE_DELAYED can clear
  1713. * ->sched_delayed.
  1714. */
  1715. uclamp_rq_inc(rq, p);
  1716. psi_enqueue(p, flags);
  1717. if (!(flags & ENQUEUE_RESTORE))
  1718. sched_info_enqueue(rq, p);
  1719. if (sched_core_enabled(rq))
  1720. sched_core_enqueue(rq, p);
  1721. }
  1722. /*
  1723. * Must only return false when DEQUEUE_SLEEP.
  1724. */
  1725. inline bool dequeue_task(struct rq *rq, struct task_struct *p, int flags)
  1726. {
  1727. if (sched_core_enabled(rq))
  1728. sched_core_dequeue(rq, p, flags);
  1729. if (!(flags & DEQUEUE_NOCLOCK))
  1730. update_rq_clock(rq);
  1731. if (!(flags & DEQUEUE_SAVE))
  1732. sched_info_dequeue(rq, p);
  1733. psi_dequeue(p, flags);
  1734. /*
  1735. * Must be before ->dequeue_task() because ->dequeue_task() can 'fail'
  1736. * and mark the task ->sched_delayed.
  1737. */
  1738. uclamp_rq_dec(rq, p);
  1739. return p->sched_class->dequeue_task(rq, p, flags);
  1740. }
  1741. void activate_task(struct rq *rq, struct task_struct *p, int flags)
  1742. {
  1743. if (task_on_rq_migrating(p))
  1744. flags |= ENQUEUE_MIGRATED;
  1745. if (flags & ENQUEUE_MIGRATED)
  1746. sched_mm_cid_migrate_to(rq, p);
  1747. enqueue_task(rq, p, flags);
  1748. WRITE_ONCE(p->on_rq, TASK_ON_RQ_QUEUED);
  1749. ASSERT_EXCLUSIVE_WRITER(p->on_rq);
  1750. }
  1751. void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
  1752. {
  1753. SCHED_WARN_ON(flags & DEQUEUE_SLEEP);
  1754. WRITE_ONCE(p->on_rq, TASK_ON_RQ_MIGRATING);
  1755. ASSERT_EXCLUSIVE_WRITER(p->on_rq);
  1756. /*
  1757. * Code explicitly relies on TASK_ON_RQ_MIGRATING begin set *before*
  1758. * dequeue_task() and cleared *after* enqueue_task().
  1759. */
  1760. dequeue_task(rq, p, flags);
  1761. }
  1762. static void block_task(struct rq *rq, struct task_struct *p, int flags)
  1763. {
  1764. if (dequeue_task(rq, p, DEQUEUE_SLEEP | flags))
  1765. __block_task(rq, p);
  1766. }
  1767. /**
  1768. * task_curr - is this task currently executing on a CPU?
  1769. * @p: the task in question.
  1770. *
  1771. * Return: 1 if the task is currently executing. 0 otherwise.
  1772. */
  1773. inline int task_curr(const struct task_struct *p)
  1774. {
  1775. return cpu_curr(task_cpu(p)) == p;
  1776. }
  1777. /*
  1778. * ->switching_to() is called with the pi_lock and rq_lock held and must not
  1779. * mess with locking.
  1780. */
  1781. void check_class_changing(struct rq *rq, struct task_struct *p,
  1782. const struct sched_class *prev_class)
  1783. {
  1784. if (prev_class != p->sched_class && p->sched_class->switching_to)
  1785. p->sched_class->switching_to(rq, p);
  1786. }
  1787. /*
  1788. * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
  1789. * use the balance_callback list if you want balancing.
  1790. *
  1791. * this means any call to check_class_changed() must be followed by a call to
  1792. * balance_callback().
  1793. */
  1794. void check_class_changed(struct rq *rq, struct task_struct *p,
  1795. const struct sched_class *prev_class,
  1796. int oldprio)
  1797. {
  1798. if (prev_class != p->sched_class) {
  1799. if (prev_class->switched_from)
  1800. prev_class->switched_from(rq, p);
  1801. p->sched_class->switched_to(rq, p);
  1802. } else if (oldprio != p->prio || dl_task(p))
  1803. p->sched_class->prio_changed(rq, p, oldprio);
  1804. }
  1805. void wakeup_preempt(struct rq *rq, struct task_struct *p, int flags)
  1806. {
  1807. if (p->sched_class == rq->curr->sched_class)
  1808. rq->curr->sched_class->wakeup_preempt(rq, p, flags);
  1809. else if (sched_class_above(p->sched_class, rq->curr->sched_class))
  1810. resched_curr(rq);
  1811. /*
  1812. * A queue event has occurred, and we're going to schedule. In
  1813. * this case, we can save a useless back to back clock update.
  1814. */
  1815. if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
  1816. rq_clock_skip_update(rq);
  1817. }
  1818. static __always_inline
  1819. int __task_state_match(struct task_struct *p, unsigned int state)
  1820. {
  1821. if (READ_ONCE(p->__state) & state)
  1822. return 1;
  1823. if (READ_ONCE(p->saved_state) & state)
  1824. return -1;
  1825. return 0;
  1826. }
  1827. static __always_inline
  1828. int task_state_match(struct task_struct *p, unsigned int state)
  1829. {
  1830. /*
  1831. * Serialize against current_save_and_set_rtlock_wait_state(),
  1832. * current_restore_rtlock_saved_state(), and __refrigerator().
  1833. */
  1834. guard(raw_spinlock_irq)(&p->pi_lock);
  1835. return __task_state_match(p, state);
  1836. }
  1837. /*
  1838. * wait_task_inactive - wait for a thread to unschedule.
  1839. *
  1840. * Wait for the thread to block in any of the states set in @match_state.
  1841. * If it changes, i.e. @p might have woken up, then return zero. When we
  1842. * succeed in waiting for @p to be off its CPU, we return a positive number
  1843. * (its total switch count). If a second call a short while later returns the
  1844. * same number, the caller can be sure that @p has remained unscheduled the
  1845. * whole time.
  1846. *
  1847. * The caller must ensure that the task *will* unschedule sometime soon,
  1848. * else this function might spin for a *long* time. This function can't
  1849. * be called with interrupts off, or it may introduce deadlock with
  1850. * smp_call_function() if an IPI is sent by the same process we are
  1851. * waiting to become inactive.
  1852. */
  1853. unsigned long wait_task_inactive(struct task_struct *p, unsigned int match_state)
  1854. {
  1855. int running, queued, match;
  1856. struct rq_flags rf;
  1857. unsigned long ncsw;
  1858. struct rq *rq;
  1859. for (;;) {
  1860. /*
  1861. * We do the initial early heuristics without holding
  1862. * any task-queue locks at all. We'll only try to get
  1863. * the runqueue lock when things look like they will
  1864. * work out!
  1865. */
  1866. rq = task_rq(p);
  1867. /*
  1868. * If the task is actively running on another CPU
  1869. * still, just relax and busy-wait without holding
  1870. * any locks.
  1871. *
  1872. * NOTE! Since we don't hold any locks, it's not
  1873. * even sure that "rq" stays as the right runqueue!
  1874. * But we don't care, since "task_on_cpu()" will
  1875. * return false if the runqueue has changed and p
  1876. * is actually now running somewhere else!
  1877. */
  1878. while (task_on_cpu(rq, p)) {
  1879. if (!task_state_match(p, match_state))
  1880. return 0;
  1881. cpu_relax();
  1882. }
  1883. /*
  1884. * Ok, time to look more closely! We need the rq
  1885. * lock now, to be *sure*. If we're wrong, we'll
  1886. * just go back and repeat.
  1887. */
  1888. rq = task_rq_lock(p, &rf);
  1889. trace_sched_wait_task(p);
  1890. running = task_on_cpu(rq, p);
  1891. queued = task_on_rq_queued(p);
  1892. ncsw = 0;
  1893. if ((match = __task_state_match(p, match_state))) {
  1894. /*
  1895. * When matching on p->saved_state, consider this task
  1896. * still queued so it will wait.
  1897. */
  1898. if (match < 0)
  1899. queued = 1;
  1900. ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
  1901. }
  1902. task_rq_unlock(rq, p, &rf);
  1903. /*
  1904. * If it changed from the expected state, bail out now.
  1905. */
  1906. if (unlikely(!ncsw))
  1907. break;
  1908. /*
  1909. * Was it really running after all now that we
  1910. * checked with the proper locks actually held?
  1911. *
  1912. * Oops. Go back and try again..
  1913. */
  1914. if (unlikely(running)) {
  1915. cpu_relax();
  1916. continue;
  1917. }
  1918. /*
  1919. * It's not enough that it's not actively running,
  1920. * it must be off the runqueue _entirely_, and not
  1921. * preempted!
  1922. *
  1923. * So if it was still runnable (but just not actively
  1924. * running right now), it's preempted, and we should
  1925. * yield - it could be a while.
  1926. */
  1927. if (unlikely(queued)) {
  1928. ktime_t to = NSEC_PER_SEC / HZ;
  1929. set_current_state(TASK_UNINTERRUPTIBLE);
  1930. schedule_hrtimeout(&to, HRTIMER_MODE_REL_HARD);
  1931. continue;
  1932. }
  1933. /*
  1934. * Ahh, all good. It wasn't running, and it wasn't
  1935. * runnable, which means that it will never become
  1936. * running in the future either. We're all done!
  1937. */
  1938. break;
  1939. }
  1940. return ncsw;
  1941. }
  1942. #ifdef CONFIG_SMP
  1943. static void
  1944. __do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx);
  1945. static void migrate_disable_switch(struct rq *rq, struct task_struct *p)
  1946. {
  1947. struct affinity_context ac = {
  1948. .new_mask = cpumask_of(rq->cpu),
  1949. .flags = SCA_MIGRATE_DISABLE,
  1950. };
  1951. if (likely(!p->migration_disabled))
  1952. return;
  1953. if (p->cpus_ptr != &p->cpus_mask)
  1954. return;
  1955. /*
  1956. * Violates locking rules! See comment in __do_set_cpus_allowed().
  1957. */
  1958. __do_set_cpus_allowed(p, &ac);
  1959. }
  1960. void migrate_disable(void)
  1961. {
  1962. struct task_struct *p = current;
  1963. if (p->migration_disabled) {
  1964. #ifdef CONFIG_DEBUG_PREEMPT
  1965. /*
  1966. *Warn about overflow half-way through the range.
  1967. */
  1968. WARN_ON_ONCE((s16)p->migration_disabled < 0);
  1969. #endif
  1970. p->migration_disabled++;
  1971. return;
  1972. }
  1973. guard(preempt)();
  1974. this_rq()->nr_pinned++;
  1975. p->migration_disabled = 1;
  1976. }
  1977. EXPORT_SYMBOL_GPL(migrate_disable);
  1978. void migrate_enable(void)
  1979. {
  1980. struct task_struct *p = current;
  1981. struct affinity_context ac = {
  1982. .new_mask = &p->cpus_mask,
  1983. .flags = SCA_MIGRATE_ENABLE,
  1984. };
  1985. #ifdef CONFIG_DEBUG_PREEMPT
  1986. /*
  1987. * Check both overflow from migrate_disable() and superfluous
  1988. * migrate_enable().
  1989. */
  1990. if (WARN_ON_ONCE((s16)p->migration_disabled <= 0))
  1991. return;
  1992. #endif
  1993. if (p->migration_disabled > 1) {
  1994. p->migration_disabled--;
  1995. return;
  1996. }
  1997. /*
  1998. * Ensure stop_task runs either before or after this, and that
  1999. * __set_cpus_allowed_ptr(SCA_MIGRATE_ENABLE) doesn't schedule().
  2000. */
  2001. guard(preempt)();
  2002. if (p->cpus_ptr != &p->cpus_mask)
  2003. __set_cpus_allowed_ptr(p, &ac);
  2004. /*
  2005. * Mustn't clear migration_disabled() until cpus_ptr points back at the
  2006. * regular cpus_mask, otherwise things that race (eg.
  2007. * select_fallback_rq) get confused.
  2008. */
  2009. barrier();
  2010. p->migration_disabled = 0;
  2011. this_rq()->nr_pinned--;
  2012. }
  2013. EXPORT_SYMBOL_GPL(migrate_enable);
  2014. static inline bool rq_has_pinned_tasks(struct rq *rq)
  2015. {
  2016. return rq->nr_pinned;
  2017. }
  2018. /*
  2019. * Per-CPU kthreads are allowed to run on !active && online CPUs, see
  2020. * __set_cpus_allowed_ptr() and select_fallback_rq().
  2021. */
  2022. static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
  2023. {
  2024. /* When not in the task's cpumask, no point in looking further. */
  2025. if (!task_allowed_on_cpu(p, cpu))
  2026. return false;
  2027. /* migrate_disabled() must be allowed to finish. */
  2028. if (is_migration_disabled(p))
  2029. return cpu_online(cpu);
  2030. /* Non kernel threads are not allowed during either online or offline. */
  2031. if (!(p->flags & PF_KTHREAD))
  2032. return cpu_active(cpu);
  2033. /* KTHREAD_IS_PER_CPU is always allowed. */
  2034. if (kthread_is_per_cpu(p))
  2035. return cpu_online(cpu);
  2036. /* Regular kernel threads don't get to stay during offline. */
  2037. if (cpu_dying(cpu))
  2038. return false;
  2039. /* But are allowed during online. */
  2040. return cpu_online(cpu);
  2041. }
  2042. /*
  2043. * This is how migration works:
  2044. *
  2045. * 1) we invoke migration_cpu_stop() on the target CPU using
  2046. * stop_one_cpu().
  2047. * 2) stopper starts to run (implicitly forcing the migrated thread
  2048. * off the CPU)
  2049. * 3) it checks whether the migrated task is still in the wrong runqueue.
  2050. * 4) if it's in the wrong runqueue then the migration thread removes
  2051. * it and puts it into the right queue.
  2052. * 5) stopper completes and stop_one_cpu() returns and the migration
  2053. * is done.
  2054. */
  2055. /*
  2056. * move_queued_task - move a queued task to new rq.
  2057. *
  2058. * Returns (locked) new rq. Old rq's lock is released.
  2059. */
  2060. static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
  2061. struct task_struct *p, int new_cpu)
  2062. {
  2063. lockdep_assert_rq_held(rq);
  2064. deactivate_task(rq, p, DEQUEUE_NOCLOCK);
  2065. set_task_cpu(p, new_cpu);
  2066. rq_unlock(rq, rf);
  2067. rq = cpu_rq(new_cpu);
  2068. rq_lock(rq, rf);
  2069. WARN_ON_ONCE(task_cpu(p) != new_cpu);
  2070. activate_task(rq, p, 0);
  2071. wakeup_preempt(rq, p, 0);
  2072. return rq;
  2073. }
  2074. struct migration_arg {
  2075. struct task_struct *task;
  2076. int dest_cpu;
  2077. struct set_affinity_pending *pending;
  2078. };
  2079. /*
  2080. * @refs: number of wait_for_completion()
  2081. * @stop_pending: is @stop_work in use
  2082. */
  2083. struct set_affinity_pending {
  2084. refcount_t refs;
  2085. unsigned int stop_pending;
  2086. struct completion done;
  2087. struct cpu_stop_work stop_work;
  2088. struct migration_arg arg;
  2089. };
  2090. /*
  2091. * Move (not current) task off this CPU, onto the destination CPU. We're doing
  2092. * this because either it can't run here any more (set_cpus_allowed()
  2093. * away from this CPU, or CPU going down), or because we're
  2094. * attempting to rebalance this task on exec (sched_exec).
  2095. *
  2096. * So we race with normal scheduler movements, but that's OK, as long
  2097. * as the task is no longer on this CPU.
  2098. */
  2099. static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
  2100. struct task_struct *p, int dest_cpu)
  2101. {
  2102. /* Affinity changed (again). */
  2103. if (!is_cpu_allowed(p, dest_cpu))
  2104. return rq;
  2105. rq = move_queued_task(rq, rf, p, dest_cpu);
  2106. return rq;
  2107. }
  2108. /*
  2109. * migration_cpu_stop - this will be executed by a high-prio stopper thread
  2110. * and performs thread migration by bumping thread off CPU then
  2111. * 'pushing' onto another runqueue.
  2112. */
  2113. static int migration_cpu_stop(void *data)
  2114. {
  2115. struct migration_arg *arg = data;
  2116. struct set_affinity_pending *pending = arg->pending;
  2117. struct task_struct *p = arg->task;
  2118. struct rq *rq = this_rq();
  2119. bool complete = false;
  2120. struct rq_flags rf;
  2121. /*
  2122. * The original target CPU might have gone down and we might
  2123. * be on another CPU but it doesn't matter.
  2124. */
  2125. local_irq_save(rf.flags);
  2126. /*
  2127. * We need to explicitly wake pending tasks before running
  2128. * __migrate_task() such that we will not miss enforcing cpus_ptr
  2129. * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
  2130. */
  2131. flush_smp_call_function_queue();
  2132. raw_spin_lock(&p->pi_lock);
  2133. rq_lock(rq, &rf);
  2134. /*
  2135. * If we were passed a pending, then ->stop_pending was set, thus
  2136. * p->migration_pending must have remained stable.
  2137. */
  2138. WARN_ON_ONCE(pending && pending != p->migration_pending);
  2139. /*
  2140. * If task_rq(p) != rq, it cannot be migrated here, because we're
  2141. * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
  2142. * we're holding p->pi_lock.
  2143. */
  2144. if (task_rq(p) == rq) {
  2145. if (is_migration_disabled(p))
  2146. goto out;
  2147. if (pending) {
  2148. p->migration_pending = NULL;
  2149. complete = true;
  2150. if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask))
  2151. goto out;
  2152. }
  2153. if (task_on_rq_queued(p)) {
  2154. update_rq_clock(rq);
  2155. rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
  2156. } else {
  2157. p->wake_cpu = arg->dest_cpu;
  2158. }
  2159. /*
  2160. * XXX __migrate_task() can fail, at which point we might end
  2161. * up running on a dodgy CPU, AFAICT this can only happen
  2162. * during CPU hotplug, at which point we'll get pushed out
  2163. * anyway, so it's probably not a big deal.
  2164. */
  2165. } else if (pending) {
  2166. /*
  2167. * This happens when we get migrated between migrate_enable()'s
  2168. * preempt_enable() and scheduling the stopper task. At that
  2169. * point we're a regular task again and not current anymore.
  2170. *
  2171. * A !PREEMPT kernel has a giant hole here, which makes it far
  2172. * more likely.
  2173. */
  2174. /*
  2175. * The task moved before the stopper got to run. We're holding
  2176. * ->pi_lock, so the allowed mask is stable - if it got
  2177. * somewhere allowed, we're done.
  2178. */
  2179. if (cpumask_test_cpu(task_cpu(p), p->cpus_ptr)) {
  2180. p->migration_pending = NULL;
  2181. complete = true;
  2182. goto out;
  2183. }
  2184. /*
  2185. * When migrate_enable() hits a rq mis-match we can't reliably
  2186. * determine is_migration_disabled() and so have to chase after
  2187. * it.
  2188. */
  2189. WARN_ON_ONCE(!pending->stop_pending);
  2190. preempt_disable();
  2191. task_rq_unlock(rq, p, &rf);
  2192. stop_one_cpu_nowait(task_cpu(p), migration_cpu_stop,
  2193. &pending->arg, &pending->stop_work);
  2194. preempt_enable();
  2195. return 0;
  2196. }
  2197. out:
  2198. if (pending)
  2199. pending->stop_pending = false;
  2200. task_rq_unlock(rq, p, &rf);
  2201. if (complete)
  2202. complete_all(&pending->done);
  2203. return 0;
  2204. }
  2205. int push_cpu_stop(void *arg)
  2206. {
  2207. struct rq *lowest_rq = NULL, *rq = this_rq();
  2208. struct task_struct *p = arg;
  2209. raw_spin_lock_irq(&p->pi_lock);
  2210. raw_spin_rq_lock(rq);
  2211. if (task_rq(p) != rq)
  2212. goto out_unlock;
  2213. if (is_migration_disabled(p)) {
  2214. p->migration_flags |= MDF_PUSH;
  2215. goto out_unlock;
  2216. }
  2217. p->migration_flags &= ~MDF_PUSH;
  2218. if (p->sched_class->find_lock_rq)
  2219. lowest_rq = p->sched_class->find_lock_rq(p, rq);
  2220. if (!lowest_rq)
  2221. goto out_unlock;
  2222. // XXX validate p is still the highest prio task
  2223. if (task_rq(p) == rq) {
  2224. deactivate_task(rq, p, 0);
  2225. set_task_cpu(p, lowest_rq->cpu);
  2226. activate_task(lowest_rq, p, 0);
  2227. resched_curr(lowest_rq);
  2228. }
  2229. double_unlock_balance(rq, lowest_rq);
  2230. out_unlock:
  2231. rq->push_busy = false;
  2232. raw_spin_rq_unlock(rq);
  2233. raw_spin_unlock_irq(&p->pi_lock);
  2234. put_task_struct(p);
  2235. return 0;
  2236. }
  2237. /*
  2238. * sched_class::set_cpus_allowed must do the below, but is not required to
  2239. * actually call this function.
  2240. */
  2241. void set_cpus_allowed_common(struct task_struct *p, struct affinity_context *ctx)
  2242. {
  2243. if (ctx->flags & (SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) {
  2244. p->cpus_ptr = ctx->new_mask;
  2245. return;
  2246. }
  2247. cpumask_copy(&p->cpus_mask, ctx->new_mask);
  2248. p->nr_cpus_allowed = cpumask_weight(ctx->new_mask);
  2249. /*
  2250. * Swap in a new user_cpus_ptr if SCA_USER flag set
  2251. */
  2252. if (ctx->flags & SCA_USER)
  2253. swap(p->user_cpus_ptr, ctx->user_mask);
  2254. }
  2255. static void
  2256. __do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx)
  2257. {
  2258. struct rq *rq = task_rq(p);
  2259. bool queued, running;
  2260. /*
  2261. * This here violates the locking rules for affinity, since we're only
  2262. * supposed to change these variables while holding both rq->lock and
  2263. * p->pi_lock.
  2264. *
  2265. * HOWEVER, it magically works, because ttwu() is the only code that
  2266. * accesses these variables under p->pi_lock and only does so after
  2267. * smp_cond_load_acquire(&p->on_cpu, !VAL), and we're in __schedule()
  2268. * before finish_task().
  2269. *
  2270. * XXX do further audits, this smells like something putrid.
  2271. */
  2272. if (ctx->flags & SCA_MIGRATE_DISABLE)
  2273. SCHED_WARN_ON(!p->on_cpu);
  2274. else
  2275. lockdep_assert_held(&p->pi_lock);
  2276. queued = task_on_rq_queued(p);
  2277. running = task_current(rq, p);
  2278. if (queued) {
  2279. /*
  2280. * Because __kthread_bind() calls this on blocked tasks without
  2281. * holding rq->lock.
  2282. */
  2283. lockdep_assert_rq_held(rq);
  2284. dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
  2285. }
  2286. if (running)
  2287. put_prev_task(rq, p);
  2288. p->sched_class->set_cpus_allowed(p, ctx);
  2289. if (queued)
  2290. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  2291. if (running)
  2292. set_next_task(rq, p);
  2293. }
  2294. /*
  2295. * Used for kthread_bind() and select_fallback_rq(), in both cases the user
  2296. * affinity (if any) should be destroyed too.
  2297. */
  2298. void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
  2299. {
  2300. struct affinity_context ac = {
  2301. .new_mask = new_mask,
  2302. .user_mask = NULL,
  2303. .flags = SCA_USER, /* clear the user requested mask */
  2304. };
  2305. union cpumask_rcuhead {
  2306. cpumask_t cpumask;
  2307. struct rcu_head rcu;
  2308. };
  2309. __do_set_cpus_allowed(p, &ac);
  2310. /*
  2311. * Because this is called with p->pi_lock held, it is not possible
  2312. * to use kfree() here (when PREEMPT_RT=y), therefore punt to using
  2313. * kfree_rcu().
  2314. */
  2315. kfree_rcu((union cpumask_rcuhead *)ac.user_mask, rcu);
  2316. }
  2317. int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src,
  2318. int node)
  2319. {
  2320. cpumask_t *user_mask;
  2321. unsigned long flags;
  2322. /*
  2323. * Always clear dst->user_cpus_ptr first as their user_cpus_ptr's
  2324. * may differ by now due to racing.
  2325. */
  2326. dst->user_cpus_ptr = NULL;
  2327. /*
  2328. * This check is racy and losing the race is a valid situation.
  2329. * It is not worth the extra overhead of taking the pi_lock on
  2330. * every fork/clone.
  2331. */
  2332. if (data_race(!src->user_cpus_ptr))
  2333. return 0;
  2334. user_mask = alloc_user_cpus_ptr(node);
  2335. if (!user_mask)
  2336. return -ENOMEM;
  2337. /*
  2338. * Use pi_lock to protect content of user_cpus_ptr
  2339. *
  2340. * Though unlikely, user_cpus_ptr can be reset to NULL by a concurrent
  2341. * do_set_cpus_allowed().
  2342. */
  2343. raw_spin_lock_irqsave(&src->pi_lock, flags);
  2344. if (src->user_cpus_ptr) {
  2345. swap(dst->user_cpus_ptr, user_mask);
  2346. cpumask_copy(dst->user_cpus_ptr, src->user_cpus_ptr);
  2347. }
  2348. raw_spin_unlock_irqrestore(&src->pi_lock, flags);
  2349. if (unlikely(user_mask))
  2350. kfree(user_mask);
  2351. return 0;
  2352. }
  2353. static inline struct cpumask *clear_user_cpus_ptr(struct task_struct *p)
  2354. {
  2355. struct cpumask *user_mask = NULL;
  2356. swap(p->user_cpus_ptr, user_mask);
  2357. return user_mask;
  2358. }
  2359. void release_user_cpus_ptr(struct task_struct *p)
  2360. {
  2361. kfree(clear_user_cpus_ptr(p));
  2362. }
  2363. /*
  2364. * This function is wildly self concurrent; here be dragons.
  2365. *
  2366. *
  2367. * When given a valid mask, __set_cpus_allowed_ptr() must block until the
  2368. * designated task is enqueued on an allowed CPU. If that task is currently
  2369. * running, we have to kick it out using the CPU stopper.
  2370. *
  2371. * Migrate-Disable comes along and tramples all over our nice sandcastle.
  2372. * Consider:
  2373. *
  2374. * Initial conditions: P0->cpus_mask = [0, 1]
  2375. *
  2376. * P0@CPU0 P1
  2377. *
  2378. * migrate_disable();
  2379. * <preempted>
  2380. * set_cpus_allowed_ptr(P0, [1]);
  2381. *
  2382. * P1 *cannot* return from this set_cpus_allowed_ptr() call until P0 executes
  2383. * its outermost migrate_enable() (i.e. it exits its Migrate-Disable region).
  2384. * This means we need the following scheme:
  2385. *
  2386. * P0@CPU0 P1
  2387. *
  2388. * migrate_disable();
  2389. * <preempted>
  2390. * set_cpus_allowed_ptr(P0, [1]);
  2391. * <blocks>
  2392. * <resumes>
  2393. * migrate_enable();
  2394. * __set_cpus_allowed_ptr();
  2395. * <wakes local stopper>
  2396. * `--> <woken on migration completion>
  2397. *
  2398. * Now the fun stuff: there may be several P1-like tasks, i.e. multiple
  2399. * concurrent set_cpus_allowed_ptr(P0, [*]) calls. CPU affinity changes of any
  2400. * task p are serialized by p->pi_lock, which we can leverage: the one that
  2401. * should come into effect at the end of the Migrate-Disable region is the last
  2402. * one. This means we only need to track a single cpumask (i.e. p->cpus_mask),
  2403. * but we still need to properly signal those waiting tasks at the appropriate
  2404. * moment.
  2405. *
  2406. * This is implemented using struct set_affinity_pending. The first
  2407. * __set_cpus_allowed_ptr() caller within a given Migrate-Disable region will
  2408. * setup an instance of that struct and install it on the targeted task_struct.
  2409. * Any and all further callers will reuse that instance. Those then wait for
  2410. * a completion signaled at the tail of the CPU stopper callback (1), triggered
  2411. * on the end of the Migrate-Disable region (i.e. outermost migrate_enable()).
  2412. *
  2413. *
  2414. * (1) In the cases covered above. There is one more where the completion is
  2415. * signaled within affine_move_task() itself: when a subsequent affinity request
  2416. * occurs after the stopper bailed out due to the targeted task still being
  2417. * Migrate-Disable. Consider:
  2418. *
  2419. * Initial conditions: P0->cpus_mask = [0, 1]
  2420. *
  2421. * CPU0 P1 P2
  2422. * <P0>
  2423. * migrate_disable();
  2424. * <preempted>
  2425. * set_cpus_allowed_ptr(P0, [1]);
  2426. * <blocks>
  2427. * <migration/0>
  2428. * migration_cpu_stop()
  2429. * is_migration_disabled()
  2430. * <bails>
  2431. * set_cpus_allowed_ptr(P0, [0, 1]);
  2432. * <signal completion>
  2433. * <awakes>
  2434. *
  2435. * Note that the above is safe vs a concurrent migrate_enable(), as any
  2436. * pending affinity completion is preceded by an uninstallation of
  2437. * p->migration_pending done with p->pi_lock held.
  2438. */
  2439. static int affine_move_task(struct rq *rq, struct task_struct *p, struct rq_flags *rf,
  2440. int dest_cpu, unsigned int flags)
  2441. __releases(rq->lock)
  2442. __releases(p->pi_lock)
  2443. {
  2444. struct set_affinity_pending my_pending = { }, *pending = NULL;
  2445. bool stop_pending, complete = false;
  2446. /* Can the task run on the task's current CPU? If so, we're done */
  2447. if (cpumask_test_cpu(task_cpu(p), &p->cpus_mask)) {
  2448. struct task_struct *push_task = NULL;
  2449. if ((flags & SCA_MIGRATE_ENABLE) &&
  2450. (p->migration_flags & MDF_PUSH) && !rq->push_busy) {
  2451. rq->push_busy = true;
  2452. push_task = get_task_struct(p);
  2453. }
  2454. /*
  2455. * If there are pending waiters, but no pending stop_work,
  2456. * then complete now.
  2457. */
  2458. pending = p->migration_pending;
  2459. if (pending && !pending->stop_pending) {
  2460. p->migration_pending = NULL;
  2461. complete = true;
  2462. }
  2463. preempt_disable();
  2464. task_rq_unlock(rq, p, rf);
  2465. if (push_task) {
  2466. stop_one_cpu_nowait(rq->cpu, push_cpu_stop,
  2467. p, &rq->push_work);
  2468. }
  2469. preempt_enable();
  2470. if (complete)
  2471. complete_all(&pending->done);
  2472. return 0;
  2473. }
  2474. if (!(flags & SCA_MIGRATE_ENABLE)) {
  2475. /* serialized by p->pi_lock */
  2476. if (!p->migration_pending) {
  2477. /* Install the request */
  2478. refcount_set(&my_pending.refs, 1);
  2479. init_completion(&my_pending.done);
  2480. my_pending.arg = (struct migration_arg) {
  2481. .task = p,
  2482. .dest_cpu = dest_cpu,
  2483. .pending = &my_pending,
  2484. };
  2485. p->migration_pending = &my_pending;
  2486. } else {
  2487. pending = p->migration_pending;
  2488. refcount_inc(&pending->refs);
  2489. /*
  2490. * Affinity has changed, but we've already installed a
  2491. * pending. migration_cpu_stop() *must* see this, else
  2492. * we risk a completion of the pending despite having a
  2493. * task on a disallowed CPU.
  2494. *
  2495. * Serialized by p->pi_lock, so this is safe.
  2496. */
  2497. pending->arg.dest_cpu = dest_cpu;
  2498. }
  2499. }
  2500. pending = p->migration_pending;
  2501. /*
  2502. * - !MIGRATE_ENABLE:
  2503. * we'll have installed a pending if there wasn't one already.
  2504. *
  2505. * - MIGRATE_ENABLE:
  2506. * we're here because the current CPU isn't matching anymore,
  2507. * the only way that can happen is because of a concurrent
  2508. * set_cpus_allowed_ptr() call, which should then still be
  2509. * pending completion.
  2510. *
  2511. * Either way, we really should have a @pending here.
  2512. */
  2513. if (WARN_ON_ONCE(!pending)) {
  2514. task_rq_unlock(rq, p, rf);
  2515. return -EINVAL;
  2516. }
  2517. if (task_on_cpu(rq, p) || READ_ONCE(p->__state) == TASK_WAKING) {
  2518. /*
  2519. * MIGRATE_ENABLE gets here because 'p == current', but for
  2520. * anything else we cannot do is_migration_disabled(), punt
  2521. * and have the stopper function handle it all race-free.
  2522. */
  2523. stop_pending = pending->stop_pending;
  2524. if (!stop_pending)
  2525. pending->stop_pending = true;
  2526. if (flags & SCA_MIGRATE_ENABLE)
  2527. p->migration_flags &= ~MDF_PUSH;
  2528. preempt_disable();
  2529. task_rq_unlock(rq, p, rf);
  2530. if (!stop_pending) {
  2531. stop_one_cpu_nowait(cpu_of(rq), migration_cpu_stop,
  2532. &pending->arg, &pending->stop_work);
  2533. }
  2534. preempt_enable();
  2535. if (flags & SCA_MIGRATE_ENABLE)
  2536. return 0;
  2537. } else {
  2538. if (!is_migration_disabled(p)) {
  2539. if (task_on_rq_queued(p))
  2540. rq = move_queued_task(rq, rf, p, dest_cpu);
  2541. if (!pending->stop_pending) {
  2542. p->migration_pending = NULL;
  2543. complete = true;
  2544. }
  2545. }
  2546. task_rq_unlock(rq, p, rf);
  2547. if (complete)
  2548. complete_all(&pending->done);
  2549. }
  2550. wait_for_completion(&pending->done);
  2551. if (refcount_dec_and_test(&pending->refs))
  2552. wake_up_var(&pending->refs); /* No UaF, just an address */
  2553. /*
  2554. * Block the original owner of &pending until all subsequent callers
  2555. * have seen the completion and decremented the refcount
  2556. */
  2557. wait_var_event(&my_pending.refs, !refcount_read(&my_pending.refs));
  2558. /* ARGH */
  2559. WARN_ON_ONCE(my_pending.stop_pending);
  2560. return 0;
  2561. }
  2562. /*
  2563. * Called with both p->pi_lock and rq->lock held; drops both before returning.
  2564. */
  2565. static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
  2566. struct affinity_context *ctx,
  2567. struct rq *rq,
  2568. struct rq_flags *rf)
  2569. __releases(rq->lock)
  2570. __releases(p->pi_lock)
  2571. {
  2572. const struct cpumask *cpu_allowed_mask = task_cpu_possible_mask(p);
  2573. const struct cpumask *cpu_valid_mask = cpu_active_mask;
  2574. bool kthread = p->flags & PF_KTHREAD;
  2575. unsigned int dest_cpu;
  2576. int ret = 0;
  2577. update_rq_clock(rq);
  2578. if (kthread || is_migration_disabled(p)) {
  2579. /*
  2580. * Kernel threads are allowed on online && !active CPUs,
  2581. * however, during cpu-hot-unplug, even these might get pushed
  2582. * away if not KTHREAD_IS_PER_CPU.
  2583. *
  2584. * Specifically, migration_disabled() tasks must not fail the
  2585. * cpumask_any_and_distribute() pick below, esp. so on
  2586. * SCA_MIGRATE_ENABLE, otherwise we'll not call
  2587. * set_cpus_allowed_common() and actually reset p->cpus_ptr.
  2588. */
  2589. cpu_valid_mask = cpu_online_mask;
  2590. }
  2591. if (!kthread && !cpumask_subset(ctx->new_mask, cpu_allowed_mask)) {
  2592. ret = -EINVAL;
  2593. goto out;
  2594. }
  2595. /*
  2596. * Must re-check here, to close a race against __kthread_bind(),
  2597. * sched_setaffinity() is not guaranteed to observe the flag.
  2598. */
  2599. if ((ctx->flags & SCA_CHECK) && (p->flags & PF_NO_SETAFFINITY)) {
  2600. ret = -EINVAL;
  2601. goto out;
  2602. }
  2603. if (!(ctx->flags & SCA_MIGRATE_ENABLE)) {
  2604. if (cpumask_equal(&p->cpus_mask, ctx->new_mask)) {
  2605. if (ctx->flags & SCA_USER)
  2606. swap(p->user_cpus_ptr, ctx->user_mask);
  2607. goto out;
  2608. }
  2609. if (WARN_ON_ONCE(p == current &&
  2610. is_migration_disabled(p) &&
  2611. !cpumask_test_cpu(task_cpu(p), ctx->new_mask))) {
  2612. ret = -EBUSY;
  2613. goto out;
  2614. }
  2615. }
  2616. /*
  2617. * Picking a ~random cpu helps in cases where we are changing affinity
  2618. * for groups of tasks (ie. cpuset), so that load balancing is not
  2619. * immediately required to distribute the tasks within their new mask.
  2620. */
  2621. dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, ctx->new_mask);
  2622. if (dest_cpu >= nr_cpu_ids) {
  2623. ret = -EINVAL;
  2624. goto out;
  2625. }
  2626. __do_set_cpus_allowed(p, ctx);
  2627. return affine_move_task(rq, p, rf, dest_cpu, ctx->flags);
  2628. out:
  2629. task_rq_unlock(rq, p, rf);
  2630. return ret;
  2631. }
  2632. /*
  2633. * Change a given task's CPU affinity. Migrate the thread to a
  2634. * proper CPU and schedule it away if the CPU it's executing on
  2635. * is removed from the allowed bitmask.
  2636. *
  2637. * NOTE: the caller must have a valid reference to the task, the
  2638. * task must not exit() & deallocate itself prematurely. The
  2639. * call is not atomic; no spinlocks may be held.
  2640. */
  2641. int __set_cpus_allowed_ptr(struct task_struct *p, struct affinity_context *ctx)
  2642. {
  2643. struct rq_flags rf;
  2644. struct rq *rq;
  2645. rq = task_rq_lock(p, &rf);
  2646. /*
  2647. * Masking should be skipped if SCA_USER or any of the SCA_MIGRATE_*
  2648. * flags are set.
  2649. */
  2650. if (p->user_cpus_ptr &&
  2651. !(ctx->flags & (SCA_USER | SCA_MIGRATE_ENABLE | SCA_MIGRATE_DISABLE)) &&
  2652. cpumask_and(rq->scratch_mask, ctx->new_mask, p->user_cpus_ptr))
  2653. ctx->new_mask = rq->scratch_mask;
  2654. return __set_cpus_allowed_ptr_locked(p, ctx, rq, &rf);
  2655. }
  2656. int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
  2657. {
  2658. struct affinity_context ac = {
  2659. .new_mask = new_mask,
  2660. .flags = 0,
  2661. };
  2662. return __set_cpus_allowed_ptr(p, &ac);
  2663. }
  2664. EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
  2665. /*
  2666. * Change a given task's CPU affinity to the intersection of its current
  2667. * affinity mask and @subset_mask, writing the resulting mask to @new_mask.
  2668. * If user_cpus_ptr is defined, use it as the basis for restricting CPU
  2669. * affinity or use cpu_online_mask instead.
  2670. *
  2671. * If the resulting mask is empty, leave the affinity unchanged and return
  2672. * -EINVAL.
  2673. */
  2674. static int restrict_cpus_allowed_ptr(struct task_struct *p,
  2675. struct cpumask *new_mask,
  2676. const struct cpumask *subset_mask)
  2677. {
  2678. struct affinity_context ac = {
  2679. .new_mask = new_mask,
  2680. .flags = 0,
  2681. };
  2682. struct rq_flags rf;
  2683. struct rq *rq;
  2684. int err;
  2685. rq = task_rq_lock(p, &rf);
  2686. /*
  2687. * Forcefully restricting the affinity of a deadline task is
  2688. * likely to cause problems, so fail and noisily override the
  2689. * mask entirely.
  2690. */
  2691. if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
  2692. err = -EPERM;
  2693. goto err_unlock;
  2694. }
  2695. if (!cpumask_and(new_mask, task_user_cpus(p), subset_mask)) {
  2696. err = -EINVAL;
  2697. goto err_unlock;
  2698. }
  2699. return __set_cpus_allowed_ptr_locked(p, &ac, rq, &rf);
  2700. err_unlock:
  2701. task_rq_unlock(rq, p, &rf);
  2702. return err;
  2703. }
  2704. /*
  2705. * Restrict the CPU affinity of task @p so that it is a subset of
  2706. * task_cpu_possible_mask() and point @p->user_cpus_ptr to a copy of the
  2707. * old affinity mask. If the resulting mask is empty, we warn and walk
  2708. * up the cpuset hierarchy until we find a suitable mask.
  2709. */
  2710. void force_compatible_cpus_allowed_ptr(struct task_struct *p)
  2711. {
  2712. cpumask_var_t new_mask;
  2713. const struct cpumask *override_mask = task_cpu_possible_mask(p);
  2714. alloc_cpumask_var(&new_mask, GFP_KERNEL);
  2715. /*
  2716. * __migrate_task() can fail silently in the face of concurrent
  2717. * offlining of the chosen destination CPU, so take the hotplug
  2718. * lock to ensure that the migration succeeds.
  2719. */
  2720. cpus_read_lock();
  2721. if (!cpumask_available(new_mask))
  2722. goto out_set_mask;
  2723. if (!restrict_cpus_allowed_ptr(p, new_mask, override_mask))
  2724. goto out_free_mask;
  2725. /*
  2726. * We failed to find a valid subset of the affinity mask for the
  2727. * task, so override it based on its cpuset hierarchy.
  2728. */
  2729. cpuset_cpus_allowed(p, new_mask);
  2730. override_mask = new_mask;
  2731. out_set_mask:
  2732. if (printk_ratelimit()) {
  2733. printk_deferred("Overriding affinity for process %d (%s) to CPUs %*pbl\n",
  2734. task_pid_nr(p), p->comm,
  2735. cpumask_pr_args(override_mask));
  2736. }
  2737. WARN_ON(set_cpus_allowed_ptr(p, override_mask));
  2738. out_free_mask:
  2739. cpus_read_unlock();
  2740. free_cpumask_var(new_mask);
  2741. }
  2742. /*
  2743. * Restore the affinity of a task @p which was previously restricted by a
  2744. * call to force_compatible_cpus_allowed_ptr().
  2745. *
  2746. * It is the caller's responsibility to serialise this with any calls to
  2747. * force_compatible_cpus_allowed_ptr(@p).
  2748. */
  2749. void relax_compatible_cpus_allowed_ptr(struct task_struct *p)
  2750. {
  2751. struct affinity_context ac = {
  2752. .new_mask = task_user_cpus(p),
  2753. .flags = 0,
  2754. };
  2755. int ret;
  2756. /*
  2757. * Try to restore the old affinity mask with __sched_setaffinity().
  2758. * Cpuset masking will be done there too.
  2759. */
  2760. ret = __sched_setaffinity(p, &ac);
  2761. WARN_ON_ONCE(ret);
  2762. }
  2763. void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
  2764. {
  2765. #ifdef CONFIG_SCHED_DEBUG
  2766. unsigned int state = READ_ONCE(p->__state);
  2767. /*
  2768. * We should never call set_task_cpu() on a blocked task,
  2769. * ttwu() will sort out the placement.
  2770. */
  2771. WARN_ON_ONCE(state != TASK_RUNNING && state != TASK_WAKING && !p->on_rq);
  2772. /*
  2773. * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
  2774. * because schedstat_wait_{start,end} rebase migrating task's wait_start
  2775. * time relying on p->on_rq.
  2776. */
  2777. WARN_ON_ONCE(state == TASK_RUNNING &&
  2778. p->sched_class == &fair_sched_class &&
  2779. (p->on_rq && !task_on_rq_migrating(p)));
  2780. #ifdef CONFIG_LOCKDEP
  2781. /*
  2782. * The caller should hold either p->pi_lock or rq->lock, when changing
  2783. * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
  2784. *
  2785. * sched_move_task() holds both and thus holding either pins the cgroup,
  2786. * see task_group().
  2787. *
  2788. * Furthermore, all task_rq users should acquire both locks, see
  2789. * task_rq_lock().
  2790. */
  2791. WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
  2792. lockdep_is_held(__rq_lockp(task_rq(p)))));
  2793. #endif
  2794. /*
  2795. * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
  2796. */
  2797. WARN_ON_ONCE(!cpu_online(new_cpu));
  2798. WARN_ON_ONCE(is_migration_disabled(p));
  2799. #endif
  2800. trace_sched_migrate_task(p, new_cpu);
  2801. if (task_cpu(p) != new_cpu) {
  2802. if (p->sched_class->migrate_task_rq)
  2803. p->sched_class->migrate_task_rq(p, new_cpu);
  2804. p->se.nr_migrations++;
  2805. rseq_migrate(p);
  2806. sched_mm_cid_migrate_from(p);
  2807. perf_event_task_migrate(p);
  2808. }
  2809. __set_task_cpu(p, new_cpu);
  2810. }
  2811. #ifdef CONFIG_NUMA_BALANCING
  2812. static void __migrate_swap_task(struct task_struct *p, int cpu)
  2813. {
  2814. if (task_on_rq_queued(p)) {
  2815. struct rq *src_rq, *dst_rq;
  2816. struct rq_flags srf, drf;
  2817. src_rq = task_rq(p);
  2818. dst_rq = cpu_rq(cpu);
  2819. rq_pin_lock(src_rq, &srf);
  2820. rq_pin_lock(dst_rq, &drf);
  2821. deactivate_task(src_rq, p, 0);
  2822. set_task_cpu(p, cpu);
  2823. activate_task(dst_rq, p, 0);
  2824. wakeup_preempt(dst_rq, p, 0);
  2825. rq_unpin_lock(dst_rq, &drf);
  2826. rq_unpin_lock(src_rq, &srf);
  2827. } else {
  2828. /*
  2829. * Task isn't running anymore; make it appear like we migrated
  2830. * it before it went to sleep. This means on wakeup we make the
  2831. * previous CPU our target instead of where it really is.
  2832. */
  2833. p->wake_cpu = cpu;
  2834. }
  2835. }
  2836. struct migration_swap_arg {
  2837. struct task_struct *src_task, *dst_task;
  2838. int src_cpu, dst_cpu;
  2839. };
  2840. static int migrate_swap_stop(void *data)
  2841. {
  2842. struct migration_swap_arg *arg = data;
  2843. struct rq *src_rq, *dst_rq;
  2844. if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
  2845. return -EAGAIN;
  2846. src_rq = cpu_rq(arg->src_cpu);
  2847. dst_rq = cpu_rq(arg->dst_cpu);
  2848. guard(double_raw_spinlock)(&arg->src_task->pi_lock, &arg->dst_task->pi_lock);
  2849. guard(double_rq_lock)(src_rq, dst_rq);
  2850. if (task_cpu(arg->dst_task) != arg->dst_cpu)
  2851. return -EAGAIN;
  2852. if (task_cpu(arg->src_task) != arg->src_cpu)
  2853. return -EAGAIN;
  2854. if (!cpumask_test_cpu(arg->dst_cpu, arg->src_task->cpus_ptr))
  2855. return -EAGAIN;
  2856. if (!cpumask_test_cpu(arg->src_cpu, arg->dst_task->cpus_ptr))
  2857. return -EAGAIN;
  2858. __migrate_swap_task(arg->src_task, arg->dst_cpu);
  2859. __migrate_swap_task(arg->dst_task, arg->src_cpu);
  2860. return 0;
  2861. }
  2862. /*
  2863. * Cross migrate two tasks
  2864. */
  2865. int migrate_swap(struct task_struct *cur, struct task_struct *p,
  2866. int target_cpu, int curr_cpu)
  2867. {
  2868. struct migration_swap_arg arg;
  2869. int ret = -EINVAL;
  2870. arg = (struct migration_swap_arg){
  2871. .src_task = cur,
  2872. .src_cpu = curr_cpu,
  2873. .dst_task = p,
  2874. .dst_cpu = target_cpu,
  2875. };
  2876. if (arg.src_cpu == arg.dst_cpu)
  2877. goto out;
  2878. /*
  2879. * These three tests are all lockless; this is OK since all of them
  2880. * will be re-checked with proper locks held further down the line.
  2881. */
  2882. if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
  2883. goto out;
  2884. if (!cpumask_test_cpu(arg.dst_cpu, arg.src_task->cpus_ptr))
  2885. goto out;
  2886. if (!cpumask_test_cpu(arg.src_cpu, arg.dst_task->cpus_ptr))
  2887. goto out;
  2888. trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
  2889. ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
  2890. out:
  2891. return ret;
  2892. }
  2893. #endif /* CONFIG_NUMA_BALANCING */
  2894. /***
  2895. * kick_process - kick a running thread to enter/exit the kernel
  2896. * @p: the to-be-kicked thread
  2897. *
  2898. * Cause a process which is running on another CPU to enter
  2899. * kernel-mode, without any delay. (to get signals handled.)
  2900. *
  2901. * NOTE: this function doesn't have to take the runqueue lock,
  2902. * because all it wants to ensure is that the remote task enters
  2903. * the kernel. If the IPI races and the task has been migrated
  2904. * to another CPU then no harm is done and the purpose has been
  2905. * achieved as well.
  2906. */
  2907. void kick_process(struct task_struct *p)
  2908. {
  2909. guard(preempt)();
  2910. int cpu = task_cpu(p);
  2911. if ((cpu != smp_processor_id()) && task_curr(p))
  2912. smp_send_reschedule(cpu);
  2913. }
  2914. EXPORT_SYMBOL_GPL(kick_process);
  2915. /*
  2916. * ->cpus_ptr is protected by both rq->lock and p->pi_lock
  2917. *
  2918. * A few notes on cpu_active vs cpu_online:
  2919. *
  2920. * - cpu_active must be a subset of cpu_online
  2921. *
  2922. * - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
  2923. * see __set_cpus_allowed_ptr(). At this point the newly online
  2924. * CPU isn't yet part of the sched domains, and balancing will not
  2925. * see it.
  2926. *
  2927. * - on CPU-down we clear cpu_active() to mask the sched domains and
  2928. * avoid the load balancer to place new tasks on the to be removed
  2929. * CPU. Existing tasks will remain running there and will be taken
  2930. * off.
  2931. *
  2932. * This means that fallback selection must not select !active CPUs.
  2933. * And can assume that any active CPU must be online. Conversely
  2934. * select_task_rq() below may allow selection of !active CPUs in order
  2935. * to satisfy the above rules.
  2936. */
  2937. static int select_fallback_rq(int cpu, struct task_struct *p)
  2938. {
  2939. int nid = cpu_to_node(cpu);
  2940. const struct cpumask *nodemask = NULL;
  2941. enum { cpuset, possible, fail } state = cpuset;
  2942. int dest_cpu;
  2943. /*
  2944. * If the node that the CPU is on has been offlined, cpu_to_node()
  2945. * will return -1. There is no CPU on the node, and we should
  2946. * select the CPU on the other node.
  2947. */
  2948. if (nid != -1) {
  2949. nodemask = cpumask_of_node(nid);
  2950. /* Look for allowed, online CPU in same node. */
  2951. for_each_cpu(dest_cpu, nodemask) {
  2952. if (is_cpu_allowed(p, dest_cpu))
  2953. return dest_cpu;
  2954. }
  2955. }
  2956. for (;;) {
  2957. /* Any allowed, online CPU? */
  2958. for_each_cpu(dest_cpu, p->cpus_ptr) {
  2959. if (!is_cpu_allowed(p, dest_cpu))
  2960. continue;
  2961. goto out;
  2962. }
  2963. /* No more Mr. Nice Guy. */
  2964. switch (state) {
  2965. case cpuset:
  2966. if (cpuset_cpus_allowed_fallback(p)) {
  2967. state = possible;
  2968. break;
  2969. }
  2970. fallthrough;
  2971. case possible:
  2972. /*
  2973. * XXX When called from select_task_rq() we only
  2974. * hold p->pi_lock and again violate locking order.
  2975. *
  2976. * More yuck to audit.
  2977. */
  2978. do_set_cpus_allowed(p, task_cpu_possible_mask(p));
  2979. state = fail;
  2980. break;
  2981. case fail:
  2982. BUG();
  2983. break;
  2984. }
  2985. }
  2986. out:
  2987. if (state != cpuset) {
  2988. /*
  2989. * Don't tell them about moving exiting tasks or
  2990. * kernel threads (both mm NULL), since they never
  2991. * leave kernel.
  2992. */
  2993. if (p->mm && printk_ratelimit()) {
  2994. printk_deferred("process %d (%s) no longer affine to cpu%d\n",
  2995. task_pid_nr(p), p->comm, cpu);
  2996. }
  2997. }
  2998. return dest_cpu;
  2999. }
  3000. /*
  3001. * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable.
  3002. */
  3003. static inline
  3004. int select_task_rq(struct task_struct *p, int cpu, int *wake_flags)
  3005. {
  3006. lockdep_assert_held(&p->pi_lock);
  3007. if (p->nr_cpus_allowed > 1 && !is_migration_disabled(p)) {
  3008. cpu = p->sched_class->select_task_rq(p, cpu, *wake_flags);
  3009. *wake_flags |= WF_RQ_SELECTED;
  3010. } else {
  3011. cpu = cpumask_any(p->cpus_ptr);
  3012. }
  3013. /*
  3014. * In order not to call set_task_cpu() on a blocking task we need
  3015. * to rely on ttwu() to place the task on a valid ->cpus_ptr
  3016. * CPU.
  3017. *
  3018. * Since this is common to all placement strategies, this lives here.
  3019. *
  3020. * [ this allows ->select_task() to simply return task_cpu(p) and
  3021. * not worry about this generic constraint ]
  3022. */
  3023. if (unlikely(!is_cpu_allowed(p, cpu)))
  3024. cpu = select_fallback_rq(task_cpu(p), p);
  3025. return cpu;
  3026. }
  3027. void sched_set_stop_task(int cpu, struct task_struct *stop)
  3028. {
  3029. static struct lock_class_key stop_pi_lock;
  3030. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  3031. struct task_struct *old_stop = cpu_rq(cpu)->stop;
  3032. if (stop) {
  3033. /*
  3034. * Make it appear like a SCHED_FIFO task, its something
  3035. * userspace knows about and won't get confused about.
  3036. *
  3037. * Also, it will make PI more or less work without too
  3038. * much confusion -- but then, stop work should not
  3039. * rely on PI working anyway.
  3040. */
  3041. sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
  3042. stop->sched_class = &stop_sched_class;
  3043. /*
  3044. * The PI code calls rt_mutex_setprio() with ->pi_lock held to
  3045. * adjust the effective priority of a task. As a result,
  3046. * rt_mutex_setprio() can trigger (RT) balancing operations,
  3047. * which can then trigger wakeups of the stop thread to push
  3048. * around the current task.
  3049. *
  3050. * The stop task itself will never be part of the PI-chain, it
  3051. * never blocks, therefore that ->pi_lock recursion is safe.
  3052. * Tell lockdep about this by placing the stop->pi_lock in its
  3053. * own class.
  3054. */
  3055. lockdep_set_class(&stop->pi_lock, &stop_pi_lock);
  3056. }
  3057. cpu_rq(cpu)->stop = stop;
  3058. if (old_stop) {
  3059. /*
  3060. * Reset it back to a normal scheduling class so that
  3061. * it can die in pieces.
  3062. */
  3063. old_stop->sched_class = &rt_sched_class;
  3064. }
  3065. }
  3066. #else /* CONFIG_SMP */
  3067. static inline void migrate_disable_switch(struct rq *rq, struct task_struct *p) { }
  3068. static inline bool rq_has_pinned_tasks(struct rq *rq)
  3069. {
  3070. return false;
  3071. }
  3072. #endif /* !CONFIG_SMP */
  3073. static void
  3074. ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
  3075. {
  3076. struct rq *rq;
  3077. if (!schedstat_enabled())
  3078. return;
  3079. rq = this_rq();
  3080. #ifdef CONFIG_SMP
  3081. if (cpu == rq->cpu) {
  3082. __schedstat_inc(rq->ttwu_local);
  3083. __schedstat_inc(p->stats.nr_wakeups_local);
  3084. } else {
  3085. struct sched_domain *sd;
  3086. __schedstat_inc(p->stats.nr_wakeups_remote);
  3087. guard(rcu)();
  3088. for_each_domain(rq->cpu, sd) {
  3089. if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
  3090. __schedstat_inc(sd->ttwu_wake_remote);
  3091. break;
  3092. }
  3093. }
  3094. }
  3095. if (wake_flags & WF_MIGRATED)
  3096. __schedstat_inc(p->stats.nr_wakeups_migrate);
  3097. #endif /* CONFIG_SMP */
  3098. __schedstat_inc(rq->ttwu_count);
  3099. __schedstat_inc(p->stats.nr_wakeups);
  3100. if (wake_flags & WF_SYNC)
  3101. __schedstat_inc(p->stats.nr_wakeups_sync);
  3102. }
  3103. /*
  3104. * Mark the task runnable.
  3105. */
  3106. static inline void ttwu_do_wakeup(struct task_struct *p)
  3107. {
  3108. WRITE_ONCE(p->__state, TASK_RUNNING);
  3109. trace_sched_wakeup(p);
  3110. }
  3111. static void
  3112. ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
  3113. struct rq_flags *rf)
  3114. {
  3115. int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
  3116. lockdep_assert_rq_held(rq);
  3117. if (p->sched_contributes_to_load)
  3118. rq->nr_uninterruptible--;
  3119. #ifdef CONFIG_SMP
  3120. if (wake_flags & WF_RQ_SELECTED)
  3121. en_flags |= ENQUEUE_RQ_SELECTED;
  3122. if (wake_flags & WF_MIGRATED)
  3123. en_flags |= ENQUEUE_MIGRATED;
  3124. else
  3125. #endif
  3126. if (p->in_iowait) {
  3127. delayacct_blkio_end(p);
  3128. atomic_dec(&task_rq(p)->nr_iowait);
  3129. }
  3130. activate_task(rq, p, en_flags);
  3131. wakeup_preempt(rq, p, wake_flags);
  3132. ttwu_do_wakeup(p);
  3133. #ifdef CONFIG_SMP
  3134. if (p->sched_class->task_woken) {
  3135. /*
  3136. * Our task @p is fully woken up and running; so it's safe to
  3137. * drop the rq->lock, hereafter rq is only used for statistics.
  3138. */
  3139. rq_unpin_lock(rq, rf);
  3140. p->sched_class->task_woken(rq, p);
  3141. rq_repin_lock(rq, rf);
  3142. }
  3143. if (rq->idle_stamp) {
  3144. u64 delta = rq_clock(rq) - rq->idle_stamp;
  3145. u64 max = 2*rq->max_idle_balance_cost;
  3146. update_avg(&rq->avg_idle, delta);
  3147. if (rq->avg_idle > max)
  3148. rq->avg_idle = max;
  3149. rq->idle_stamp = 0;
  3150. }
  3151. #endif
  3152. }
  3153. /*
  3154. * Consider @p being inside a wait loop:
  3155. *
  3156. * for (;;) {
  3157. * set_current_state(TASK_UNINTERRUPTIBLE);
  3158. *
  3159. * if (CONDITION)
  3160. * break;
  3161. *
  3162. * schedule();
  3163. * }
  3164. * __set_current_state(TASK_RUNNING);
  3165. *
  3166. * between set_current_state() and schedule(). In this case @p is still
  3167. * runnable, so all that needs doing is change p->state back to TASK_RUNNING in
  3168. * an atomic manner.
  3169. *
  3170. * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq
  3171. * then schedule() must still happen and p->state can be changed to
  3172. * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we
  3173. * need to do a full wakeup with enqueue.
  3174. *
  3175. * Returns: %true when the wakeup is done,
  3176. * %false otherwise.
  3177. */
  3178. static int ttwu_runnable(struct task_struct *p, int wake_flags)
  3179. {
  3180. struct rq_flags rf;
  3181. struct rq *rq;
  3182. int ret = 0;
  3183. rq = __task_rq_lock(p, &rf);
  3184. if (task_on_rq_queued(p)) {
  3185. update_rq_clock(rq);
  3186. if (p->se.sched_delayed)
  3187. enqueue_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_DELAYED);
  3188. if (!task_on_cpu(rq, p)) {
  3189. /*
  3190. * When on_rq && !on_cpu the task is preempted, see if
  3191. * it should preempt the task that is current now.
  3192. */
  3193. wakeup_preempt(rq, p, wake_flags);
  3194. }
  3195. ttwu_do_wakeup(p);
  3196. ret = 1;
  3197. }
  3198. __task_rq_unlock(rq, &rf);
  3199. return ret;
  3200. }
  3201. #ifdef CONFIG_SMP
  3202. void sched_ttwu_pending(void *arg)
  3203. {
  3204. struct llist_node *llist = arg;
  3205. struct rq *rq = this_rq();
  3206. struct task_struct *p, *t;
  3207. struct rq_flags rf;
  3208. if (!llist)
  3209. return;
  3210. rq_lock_irqsave(rq, &rf);
  3211. update_rq_clock(rq);
  3212. llist_for_each_entry_safe(p, t, llist, wake_entry.llist) {
  3213. if (WARN_ON_ONCE(p->on_cpu))
  3214. smp_cond_load_acquire(&p->on_cpu, !VAL);
  3215. if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq)))
  3216. set_task_cpu(p, cpu_of(rq));
  3217. ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
  3218. }
  3219. /*
  3220. * Must be after enqueueing at least once task such that
  3221. * idle_cpu() does not observe a false-negative -- if it does,
  3222. * it is possible for select_idle_siblings() to stack a number
  3223. * of tasks on this CPU during that window.
  3224. *
  3225. * It is OK to clear ttwu_pending when another task pending.
  3226. * We will receive IPI after local IRQ enabled and then enqueue it.
  3227. * Since now nr_running > 0, idle_cpu() will always get correct result.
  3228. */
  3229. WRITE_ONCE(rq->ttwu_pending, 0);
  3230. rq_unlock_irqrestore(rq, &rf);
  3231. }
  3232. /*
  3233. * Prepare the scene for sending an IPI for a remote smp_call
  3234. *
  3235. * Returns true if the caller can proceed with sending the IPI.
  3236. * Returns false otherwise.
  3237. */
  3238. bool call_function_single_prep_ipi(int cpu)
  3239. {
  3240. if (set_nr_if_polling(cpu_rq(cpu)->idle)) {
  3241. trace_sched_wake_idle_without_ipi(cpu);
  3242. return false;
  3243. }
  3244. return true;
  3245. }
  3246. /*
  3247. * Queue a task on the target CPUs wake_list and wake the CPU via IPI if
  3248. * necessary. The wakee CPU on receipt of the IPI will queue the task
  3249. * via sched_ttwu_wakeup() for activation so the wakee incurs the cost
  3250. * of the wakeup instead of the waker.
  3251. */
  3252. static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
  3253. {
  3254. struct rq *rq = cpu_rq(cpu);
  3255. p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
  3256. WRITE_ONCE(rq->ttwu_pending, 1);
  3257. __smp_call_single_queue(cpu, &p->wake_entry.llist);
  3258. }
  3259. void wake_up_if_idle(int cpu)
  3260. {
  3261. struct rq *rq = cpu_rq(cpu);
  3262. guard(rcu)();
  3263. if (is_idle_task(rcu_dereference(rq->curr))) {
  3264. guard(rq_lock_irqsave)(rq);
  3265. if (is_idle_task(rq->curr))
  3266. resched_curr(rq);
  3267. }
  3268. }
  3269. bool cpus_equal_capacity(int this_cpu, int that_cpu)
  3270. {
  3271. if (!sched_asym_cpucap_active())
  3272. return true;
  3273. if (this_cpu == that_cpu)
  3274. return true;
  3275. return arch_scale_cpu_capacity(this_cpu) == arch_scale_cpu_capacity(that_cpu);
  3276. }
  3277. bool cpus_share_cache(int this_cpu, int that_cpu)
  3278. {
  3279. if (this_cpu == that_cpu)
  3280. return true;
  3281. return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
  3282. }
  3283. /*
  3284. * Whether CPUs are share cache resources, which means LLC on non-cluster
  3285. * machines and LLC tag or L2 on machines with clusters.
  3286. */
  3287. bool cpus_share_resources(int this_cpu, int that_cpu)
  3288. {
  3289. if (this_cpu == that_cpu)
  3290. return true;
  3291. return per_cpu(sd_share_id, this_cpu) == per_cpu(sd_share_id, that_cpu);
  3292. }
  3293. static inline bool ttwu_queue_cond(struct task_struct *p, int cpu)
  3294. {
  3295. /*
  3296. * The BPF scheduler may depend on select_task_rq() being invoked during
  3297. * wakeups. In addition, @p may end up executing on a different CPU
  3298. * regardless of what happens in the wakeup path making the ttwu_queue
  3299. * optimization less meaningful. Skip if on SCX.
  3300. */
  3301. if (task_on_scx(p))
  3302. return false;
  3303. /*
  3304. * Do not complicate things with the async wake_list while the CPU is
  3305. * in hotplug state.
  3306. */
  3307. if (!cpu_active(cpu))
  3308. return false;
  3309. /* Ensure the task will still be allowed to run on the CPU. */
  3310. if (!cpumask_test_cpu(cpu, p->cpus_ptr))
  3311. return false;
  3312. /*
  3313. * If the CPU does not share cache, then queue the task on the
  3314. * remote rqs wakelist to avoid accessing remote data.
  3315. */
  3316. if (!cpus_share_cache(smp_processor_id(), cpu))
  3317. return true;
  3318. if (cpu == smp_processor_id())
  3319. return false;
  3320. /*
  3321. * If the wakee cpu is idle, or the task is descheduling and the
  3322. * only running task on the CPU, then use the wakelist to offload
  3323. * the task activation to the idle (or soon-to-be-idle) CPU as
  3324. * the current CPU is likely busy. nr_running is checked to
  3325. * avoid unnecessary task stacking.
  3326. *
  3327. * Note that we can only get here with (wakee) p->on_rq=0,
  3328. * p->on_cpu can be whatever, we've done the dequeue, so
  3329. * the wakee has been accounted out of ->nr_running.
  3330. */
  3331. if (!cpu_rq(cpu)->nr_running)
  3332. return true;
  3333. return false;
  3334. }
  3335. static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
  3336. {
  3337. if (sched_feat(TTWU_QUEUE) && ttwu_queue_cond(p, cpu)) {
  3338. sched_clock_cpu(cpu); /* Sync clocks across CPUs */
  3339. __ttwu_queue_wakelist(p, cpu, wake_flags);
  3340. return true;
  3341. }
  3342. return false;
  3343. }
  3344. #else /* !CONFIG_SMP */
  3345. static inline bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
  3346. {
  3347. return false;
  3348. }
  3349. #endif /* CONFIG_SMP */
  3350. static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
  3351. {
  3352. struct rq *rq = cpu_rq(cpu);
  3353. struct rq_flags rf;
  3354. if (ttwu_queue_wakelist(p, cpu, wake_flags))
  3355. return;
  3356. rq_lock(rq, &rf);
  3357. update_rq_clock(rq);
  3358. ttwu_do_activate(rq, p, wake_flags, &rf);
  3359. rq_unlock(rq, &rf);
  3360. }
  3361. /*
  3362. * Invoked from try_to_wake_up() to check whether the task can be woken up.
  3363. *
  3364. * The caller holds p::pi_lock if p != current or has preemption
  3365. * disabled when p == current.
  3366. *
  3367. * The rules of saved_state:
  3368. *
  3369. * The related locking code always holds p::pi_lock when updating
  3370. * p::saved_state, which means the code is fully serialized in both cases.
  3371. *
  3372. * For PREEMPT_RT, the lock wait and lock wakeups happen via TASK_RTLOCK_WAIT.
  3373. * No other bits set. This allows to distinguish all wakeup scenarios.
  3374. *
  3375. * For FREEZER, the wakeup happens via TASK_FROZEN. No other bits set. This
  3376. * allows us to prevent early wakeup of tasks before they can be run on
  3377. * asymmetric ISA architectures (eg ARMv9).
  3378. */
  3379. static __always_inline
  3380. bool ttwu_state_match(struct task_struct *p, unsigned int state, int *success)
  3381. {
  3382. int match;
  3383. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) {
  3384. WARN_ON_ONCE((state & TASK_RTLOCK_WAIT) &&
  3385. state != TASK_RTLOCK_WAIT);
  3386. }
  3387. *success = !!(match = __task_state_match(p, state));
  3388. /*
  3389. * Saved state preserves the task state across blocking on
  3390. * an RT lock or TASK_FREEZABLE tasks. If the state matches,
  3391. * set p::saved_state to TASK_RUNNING, but do not wake the task
  3392. * because it waits for a lock wakeup or __thaw_task(). Also
  3393. * indicate success because from the regular waker's point of
  3394. * view this has succeeded.
  3395. *
  3396. * After acquiring the lock the task will restore p::__state
  3397. * from p::saved_state which ensures that the regular
  3398. * wakeup is not lost. The restore will also set
  3399. * p::saved_state to TASK_RUNNING so any further tests will
  3400. * not result in false positives vs. @success
  3401. */
  3402. if (match < 0)
  3403. p->saved_state = TASK_RUNNING;
  3404. return match > 0;
  3405. }
  3406. /*
  3407. * Notes on Program-Order guarantees on SMP systems.
  3408. *
  3409. * MIGRATION
  3410. *
  3411. * The basic program-order guarantee on SMP systems is that when a task [t]
  3412. * migrates, all its activity on its old CPU [c0] happens-before any subsequent
  3413. * execution on its new CPU [c1].
  3414. *
  3415. * For migration (of runnable tasks) this is provided by the following means:
  3416. *
  3417. * A) UNLOCK of the rq(c0)->lock scheduling out task t
  3418. * B) migration for t is required to synchronize *both* rq(c0)->lock and
  3419. * rq(c1)->lock (if not at the same time, then in that order).
  3420. * C) LOCK of the rq(c1)->lock scheduling in task
  3421. *
  3422. * Release/acquire chaining guarantees that B happens after A and C after B.
  3423. * Note: the CPU doing B need not be c0 or c1
  3424. *
  3425. * Example:
  3426. *
  3427. * CPU0 CPU1 CPU2
  3428. *
  3429. * LOCK rq(0)->lock
  3430. * sched-out X
  3431. * sched-in Y
  3432. * UNLOCK rq(0)->lock
  3433. *
  3434. * LOCK rq(0)->lock // orders against CPU0
  3435. * dequeue X
  3436. * UNLOCK rq(0)->lock
  3437. *
  3438. * LOCK rq(1)->lock
  3439. * enqueue X
  3440. * UNLOCK rq(1)->lock
  3441. *
  3442. * LOCK rq(1)->lock // orders against CPU2
  3443. * sched-out Z
  3444. * sched-in X
  3445. * UNLOCK rq(1)->lock
  3446. *
  3447. *
  3448. * BLOCKING -- aka. SLEEP + WAKEUP
  3449. *
  3450. * For blocking we (obviously) need to provide the same guarantee as for
  3451. * migration. However the means are completely different as there is no lock
  3452. * chain to provide order. Instead we do:
  3453. *
  3454. * 1) smp_store_release(X->on_cpu, 0) -- finish_task()
  3455. * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up()
  3456. *
  3457. * Example:
  3458. *
  3459. * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
  3460. *
  3461. * LOCK rq(0)->lock LOCK X->pi_lock
  3462. * dequeue X
  3463. * sched-out X
  3464. * smp_store_release(X->on_cpu, 0);
  3465. *
  3466. * smp_cond_load_acquire(&X->on_cpu, !VAL);
  3467. * X->state = WAKING
  3468. * set_task_cpu(X,2)
  3469. *
  3470. * LOCK rq(2)->lock
  3471. * enqueue X
  3472. * X->state = RUNNING
  3473. * UNLOCK rq(2)->lock
  3474. *
  3475. * LOCK rq(2)->lock // orders against CPU1
  3476. * sched-out Z
  3477. * sched-in X
  3478. * UNLOCK rq(2)->lock
  3479. *
  3480. * UNLOCK X->pi_lock
  3481. * UNLOCK rq(0)->lock
  3482. *
  3483. *
  3484. * However, for wakeups there is a second guarantee we must provide, namely we
  3485. * must ensure that CONDITION=1 done by the caller can not be reordered with
  3486. * accesses to the task state; see try_to_wake_up() and set_current_state().
  3487. */
  3488. /**
  3489. * try_to_wake_up - wake up a thread
  3490. * @p: the thread to be awakened
  3491. * @state: the mask of task states that can be woken
  3492. * @wake_flags: wake modifier flags (WF_*)
  3493. *
  3494. * Conceptually does:
  3495. *
  3496. * If (@state & @p->state) @p->state = TASK_RUNNING.
  3497. *
  3498. * If the task was not queued/runnable, also place it back on a runqueue.
  3499. *
  3500. * This function is atomic against schedule() which would dequeue the task.
  3501. *
  3502. * It issues a full memory barrier before accessing @p->state, see the comment
  3503. * with set_current_state().
  3504. *
  3505. * Uses p->pi_lock to serialize against concurrent wake-ups.
  3506. *
  3507. * Relies on p->pi_lock stabilizing:
  3508. * - p->sched_class
  3509. * - p->cpus_ptr
  3510. * - p->sched_task_group
  3511. * in order to do migration, see its use of select_task_rq()/set_task_cpu().
  3512. *
  3513. * Tries really hard to only take one task_rq(p)->lock for performance.
  3514. * Takes rq->lock in:
  3515. * - ttwu_runnable() -- old rq, unavoidable, see comment there;
  3516. * - ttwu_queue() -- new rq, for enqueue of the task;
  3517. * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us.
  3518. *
  3519. * As a consequence we race really badly with just about everything. See the
  3520. * many memory barriers and their comments for details.
  3521. *
  3522. * Return: %true if @p->state changes (an actual wakeup was done),
  3523. * %false otherwise.
  3524. */
  3525. int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
  3526. {
  3527. guard(preempt)();
  3528. int cpu, success = 0;
  3529. wake_flags |= WF_TTWU;
  3530. if (p == current) {
  3531. /*
  3532. * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
  3533. * == smp_processor_id()'. Together this means we can special
  3534. * case the whole 'p->on_rq && ttwu_runnable()' case below
  3535. * without taking any locks.
  3536. *
  3537. * Specifically, given current runs ttwu() we must be before
  3538. * schedule()'s block_task(), as such this must not observe
  3539. * sched_delayed.
  3540. *
  3541. * In particular:
  3542. * - we rely on Program-Order guarantees for all the ordering,
  3543. * - we're serialized against set_special_state() by virtue of
  3544. * it disabling IRQs (this allows not taking ->pi_lock).
  3545. */
  3546. SCHED_WARN_ON(p->se.sched_delayed);
  3547. if (!ttwu_state_match(p, state, &success))
  3548. goto out;
  3549. trace_sched_waking(p);
  3550. ttwu_do_wakeup(p);
  3551. goto out;
  3552. }
  3553. /*
  3554. * If we are going to wake up a thread waiting for CONDITION we
  3555. * need to ensure that CONDITION=1 done by the caller can not be
  3556. * reordered with p->state check below. This pairs with smp_store_mb()
  3557. * in set_current_state() that the waiting thread does.
  3558. */
  3559. scoped_guard (raw_spinlock_irqsave, &p->pi_lock) {
  3560. smp_mb__after_spinlock();
  3561. if (!ttwu_state_match(p, state, &success))
  3562. break;
  3563. trace_sched_waking(p);
  3564. /*
  3565. * Ensure we load p->on_rq _after_ p->state, otherwise it would
  3566. * be possible to, falsely, observe p->on_rq == 0 and get stuck
  3567. * in smp_cond_load_acquire() below.
  3568. *
  3569. * sched_ttwu_pending() try_to_wake_up()
  3570. * STORE p->on_rq = 1 LOAD p->state
  3571. * UNLOCK rq->lock
  3572. *
  3573. * __schedule() (switch to task 'p')
  3574. * LOCK rq->lock smp_rmb();
  3575. * smp_mb__after_spinlock();
  3576. * UNLOCK rq->lock
  3577. *
  3578. * [task p]
  3579. * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq
  3580. *
  3581. * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
  3582. * __schedule(). See the comment for smp_mb__after_spinlock().
  3583. *
  3584. * A similar smp_rmb() lives in __task_needs_rq_lock().
  3585. */
  3586. smp_rmb();
  3587. if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags))
  3588. break;
  3589. #ifdef CONFIG_SMP
  3590. /*
  3591. * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
  3592. * possible to, falsely, observe p->on_cpu == 0.
  3593. *
  3594. * One must be running (->on_cpu == 1) in order to remove oneself
  3595. * from the runqueue.
  3596. *
  3597. * __schedule() (switch to task 'p') try_to_wake_up()
  3598. * STORE p->on_cpu = 1 LOAD p->on_rq
  3599. * UNLOCK rq->lock
  3600. *
  3601. * __schedule() (put 'p' to sleep)
  3602. * LOCK rq->lock smp_rmb();
  3603. * smp_mb__after_spinlock();
  3604. * STORE p->on_rq = 0 LOAD p->on_cpu
  3605. *
  3606. * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
  3607. * __schedule(). See the comment for smp_mb__after_spinlock().
  3608. *
  3609. * Form a control-dep-acquire with p->on_rq == 0 above, to ensure
  3610. * schedule()'s deactivate_task() has 'happened' and p will no longer
  3611. * care about it's own p->state. See the comment in __schedule().
  3612. */
  3613. smp_acquire__after_ctrl_dep();
  3614. /*
  3615. * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq
  3616. * == 0), which means we need to do an enqueue, change p->state to
  3617. * TASK_WAKING such that we can unlock p->pi_lock before doing the
  3618. * enqueue, such as ttwu_queue_wakelist().
  3619. */
  3620. WRITE_ONCE(p->__state, TASK_WAKING);
  3621. /*
  3622. * If the owning (remote) CPU is still in the middle of schedule() with
  3623. * this task as prev, considering queueing p on the remote CPUs wake_list
  3624. * which potentially sends an IPI instead of spinning on p->on_cpu to
  3625. * let the waker make forward progress. This is safe because IRQs are
  3626. * disabled and the IPI will deliver after on_cpu is cleared.
  3627. *
  3628. * Ensure we load task_cpu(p) after p->on_cpu:
  3629. *
  3630. * set_task_cpu(p, cpu);
  3631. * STORE p->cpu = @cpu
  3632. * __schedule() (switch to task 'p')
  3633. * LOCK rq->lock
  3634. * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu)
  3635. * STORE p->on_cpu = 1 LOAD p->cpu
  3636. *
  3637. * to ensure we observe the correct CPU on which the task is currently
  3638. * scheduling.
  3639. */
  3640. if (smp_load_acquire(&p->on_cpu) &&
  3641. ttwu_queue_wakelist(p, task_cpu(p), wake_flags))
  3642. break;
  3643. /*
  3644. * If the owning (remote) CPU is still in the middle of schedule() with
  3645. * this task as prev, wait until it's done referencing the task.
  3646. *
  3647. * Pairs with the smp_store_release() in finish_task().
  3648. *
  3649. * This ensures that tasks getting woken will be fully ordered against
  3650. * their previous state and preserve Program Order.
  3651. */
  3652. smp_cond_load_acquire(&p->on_cpu, !VAL);
  3653. cpu = select_task_rq(p, p->wake_cpu, &wake_flags);
  3654. if (task_cpu(p) != cpu) {
  3655. if (p->in_iowait) {
  3656. delayacct_blkio_end(p);
  3657. atomic_dec(&task_rq(p)->nr_iowait);
  3658. }
  3659. wake_flags |= WF_MIGRATED;
  3660. psi_ttwu_dequeue(p);
  3661. set_task_cpu(p, cpu);
  3662. }
  3663. #else
  3664. cpu = task_cpu(p);
  3665. #endif /* CONFIG_SMP */
  3666. ttwu_queue(p, cpu, wake_flags);
  3667. }
  3668. out:
  3669. if (success)
  3670. ttwu_stat(p, task_cpu(p), wake_flags);
  3671. return success;
  3672. }
  3673. static bool __task_needs_rq_lock(struct task_struct *p)
  3674. {
  3675. unsigned int state = READ_ONCE(p->__state);
  3676. /*
  3677. * Since pi->lock blocks try_to_wake_up(), we don't need rq->lock when
  3678. * the task is blocked. Make sure to check @state since ttwu() can drop
  3679. * locks at the end, see ttwu_queue_wakelist().
  3680. */
  3681. if (state == TASK_RUNNING || state == TASK_WAKING)
  3682. return true;
  3683. /*
  3684. * Ensure we load p->on_rq after p->__state, otherwise it would be
  3685. * possible to, falsely, observe p->on_rq == 0.
  3686. *
  3687. * See try_to_wake_up() for a longer comment.
  3688. */
  3689. smp_rmb();
  3690. if (p->on_rq)
  3691. return true;
  3692. #ifdef CONFIG_SMP
  3693. /*
  3694. * Ensure the task has finished __schedule() and will not be referenced
  3695. * anymore. Again, see try_to_wake_up() for a longer comment.
  3696. */
  3697. smp_rmb();
  3698. smp_cond_load_acquire(&p->on_cpu, !VAL);
  3699. #endif
  3700. return false;
  3701. }
  3702. /**
  3703. * task_call_func - Invoke a function on task in fixed state
  3704. * @p: Process for which the function is to be invoked, can be @current.
  3705. * @func: Function to invoke.
  3706. * @arg: Argument to function.
  3707. *
  3708. * Fix the task in it's current state by avoiding wakeups and or rq operations
  3709. * and call @func(@arg) on it. This function can use task_is_runnable() and
  3710. * task_curr() to work out what the state is, if required. Given that @func
  3711. * can be invoked with a runqueue lock held, it had better be quite
  3712. * lightweight.
  3713. *
  3714. * Returns:
  3715. * Whatever @func returns
  3716. */
  3717. int task_call_func(struct task_struct *p, task_call_f func, void *arg)
  3718. {
  3719. struct rq *rq = NULL;
  3720. struct rq_flags rf;
  3721. int ret;
  3722. raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
  3723. if (__task_needs_rq_lock(p))
  3724. rq = __task_rq_lock(p, &rf);
  3725. /*
  3726. * At this point the task is pinned; either:
  3727. * - blocked and we're holding off wakeups (pi->lock)
  3728. * - woken, and we're holding off enqueue (rq->lock)
  3729. * - queued, and we're holding off schedule (rq->lock)
  3730. * - running, and we're holding off de-schedule (rq->lock)
  3731. *
  3732. * The called function (@func) can use: task_curr(), p->on_rq and
  3733. * p->__state to differentiate between these states.
  3734. */
  3735. ret = func(p, arg);
  3736. if (rq)
  3737. rq_unlock(rq, &rf);
  3738. raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
  3739. return ret;
  3740. }
  3741. /**
  3742. * cpu_curr_snapshot - Return a snapshot of the currently running task
  3743. * @cpu: The CPU on which to snapshot the task.
  3744. *
  3745. * Returns the task_struct pointer of the task "currently" running on
  3746. * the specified CPU.
  3747. *
  3748. * If the specified CPU was offline, the return value is whatever it
  3749. * is, perhaps a pointer to the task_struct structure of that CPU's idle
  3750. * task, but there is no guarantee. Callers wishing a useful return
  3751. * value must take some action to ensure that the specified CPU remains
  3752. * online throughout.
  3753. *
  3754. * This function executes full memory barriers before and after fetching
  3755. * the pointer, which permits the caller to confine this function's fetch
  3756. * with respect to the caller's accesses to other shared variables.
  3757. */
  3758. struct task_struct *cpu_curr_snapshot(int cpu)
  3759. {
  3760. struct rq *rq = cpu_rq(cpu);
  3761. struct task_struct *t;
  3762. struct rq_flags rf;
  3763. rq_lock_irqsave(rq, &rf);
  3764. smp_mb__after_spinlock(); /* Pairing determined by caller's synchronization design. */
  3765. t = rcu_dereference(cpu_curr(cpu));
  3766. rq_unlock_irqrestore(rq, &rf);
  3767. smp_mb(); /* Pairing determined by caller's synchronization design. */
  3768. return t;
  3769. }
  3770. /**
  3771. * wake_up_process - Wake up a specific process
  3772. * @p: The process to be woken up.
  3773. *
  3774. * Attempt to wake up the nominated process and move it to the set of runnable
  3775. * processes.
  3776. *
  3777. * Return: 1 if the process was woken up, 0 if it was already running.
  3778. *
  3779. * This function executes a full memory barrier before accessing the task state.
  3780. */
  3781. int wake_up_process(struct task_struct *p)
  3782. {
  3783. return try_to_wake_up(p, TASK_NORMAL, 0);
  3784. }
  3785. EXPORT_SYMBOL(wake_up_process);
  3786. int wake_up_state(struct task_struct *p, unsigned int state)
  3787. {
  3788. return try_to_wake_up(p, state, 0);
  3789. }
  3790. /*
  3791. * Perform scheduler related setup for a newly forked process p.
  3792. * p is forked by current.
  3793. *
  3794. * __sched_fork() is basic setup which is also used by sched_init() to
  3795. * initialize the boot CPU's idle task.
  3796. */
  3797. static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
  3798. {
  3799. p->on_rq = 0;
  3800. p->se.on_rq = 0;
  3801. p->se.exec_start = 0;
  3802. p->se.sum_exec_runtime = 0;
  3803. p->se.prev_sum_exec_runtime = 0;
  3804. p->se.nr_migrations = 0;
  3805. p->se.vruntime = 0;
  3806. p->se.vlag = 0;
  3807. INIT_LIST_HEAD(&p->se.group_node);
  3808. /* A delayed task cannot be in clone(). */
  3809. SCHED_WARN_ON(p->se.sched_delayed);
  3810. #ifdef CONFIG_FAIR_GROUP_SCHED
  3811. p->se.cfs_rq = NULL;
  3812. #endif
  3813. #ifdef CONFIG_SCHEDSTATS
  3814. /* Even if schedstat is disabled, there should not be garbage */
  3815. memset(&p->stats, 0, sizeof(p->stats));
  3816. #endif
  3817. init_dl_entity(&p->dl);
  3818. INIT_LIST_HEAD(&p->rt.run_list);
  3819. p->rt.timeout = 0;
  3820. p->rt.time_slice = sched_rr_timeslice;
  3821. p->rt.on_rq = 0;
  3822. p->rt.on_list = 0;
  3823. #ifdef CONFIG_SCHED_CLASS_EXT
  3824. init_scx_entity(&p->scx);
  3825. #endif
  3826. #ifdef CONFIG_PREEMPT_NOTIFIERS
  3827. INIT_HLIST_HEAD(&p->preempt_notifiers);
  3828. #endif
  3829. #ifdef CONFIG_COMPACTION
  3830. p->capture_control = NULL;
  3831. #endif
  3832. init_numa_balancing(clone_flags, p);
  3833. #ifdef CONFIG_SMP
  3834. p->wake_entry.u_flags = CSD_TYPE_TTWU;
  3835. p->migration_pending = NULL;
  3836. #endif
  3837. init_sched_mm_cid(p);
  3838. }
  3839. DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
  3840. #ifdef CONFIG_NUMA_BALANCING
  3841. int sysctl_numa_balancing_mode;
  3842. static void __set_numabalancing_state(bool enabled)
  3843. {
  3844. if (enabled)
  3845. static_branch_enable(&sched_numa_balancing);
  3846. else
  3847. static_branch_disable(&sched_numa_balancing);
  3848. }
  3849. void set_numabalancing_state(bool enabled)
  3850. {
  3851. if (enabled)
  3852. sysctl_numa_balancing_mode = NUMA_BALANCING_NORMAL;
  3853. else
  3854. sysctl_numa_balancing_mode = NUMA_BALANCING_DISABLED;
  3855. __set_numabalancing_state(enabled);
  3856. }
  3857. #ifdef CONFIG_PROC_SYSCTL
  3858. static void reset_memory_tiering(void)
  3859. {
  3860. struct pglist_data *pgdat;
  3861. for_each_online_pgdat(pgdat) {
  3862. pgdat->nbp_threshold = 0;
  3863. pgdat->nbp_th_nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
  3864. pgdat->nbp_th_start = jiffies_to_msecs(jiffies);
  3865. }
  3866. }
  3867. static int sysctl_numa_balancing(const struct ctl_table *table, int write,
  3868. void *buffer, size_t *lenp, loff_t *ppos)
  3869. {
  3870. struct ctl_table t;
  3871. int err;
  3872. int state = sysctl_numa_balancing_mode;
  3873. if (write && !capable(CAP_SYS_ADMIN))
  3874. return -EPERM;
  3875. t = *table;
  3876. t.data = &state;
  3877. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  3878. if (err < 0)
  3879. return err;
  3880. if (write) {
  3881. if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
  3882. (state & NUMA_BALANCING_MEMORY_TIERING))
  3883. reset_memory_tiering();
  3884. sysctl_numa_balancing_mode = state;
  3885. __set_numabalancing_state(state);
  3886. }
  3887. return err;
  3888. }
  3889. #endif
  3890. #endif
  3891. #ifdef CONFIG_SCHEDSTATS
  3892. DEFINE_STATIC_KEY_FALSE(sched_schedstats);
  3893. static void set_schedstats(bool enabled)
  3894. {
  3895. if (enabled)
  3896. static_branch_enable(&sched_schedstats);
  3897. else
  3898. static_branch_disable(&sched_schedstats);
  3899. }
  3900. void force_schedstat_enabled(void)
  3901. {
  3902. if (!schedstat_enabled()) {
  3903. pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
  3904. static_branch_enable(&sched_schedstats);
  3905. }
  3906. }
  3907. static int __init setup_schedstats(char *str)
  3908. {
  3909. int ret = 0;
  3910. if (!str)
  3911. goto out;
  3912. if (!strcmp(str, "enable")) {
  3913. set_schedstats(true);
  3914. ret = 1;
  3915. } else if (!strcmp(str, "disable")) {
  3916. set_schedstats(false);
  3917. ret = 1;
  3918. }
  3919. out:
  3920. if (!ret)
  3921. pr_warn("Unable to parse schedstats=\n");
  3922. return ret;
  3923. }
  3924. __setup("schedstats=", setup_schedstats);
  3925. #ifdef CONFIG_PROC_SYSCTL
  3926. static int sysctl_schedstats(const struct ctl_table *table, int write, void *buffer,
  3927. size_t *lenp, loff_t *ppos)
  3928. {
  3929. struct ctl_table t;
  3930. int err;
  3931. int state = static_branch_likely(&sched_schedstats);
  3932. if (write && !capable(CAP_SYS_ADMIN))
  3933. return -EPERM;
  3934. t = *table;
  3935. t.data = &state;
  3936. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  3937. if (err < 0)
  3938. return err;
  3939. if (write)
  3940. set_schedstats(state);
  3941. return err;
  3942. }
  3943. #endif /* CONFIG_PROC_SYSCTL */
  3944. #endif /* CONFIG_SCHEDSTATS */
  3945. #ifdef CONFIG_SYSCTL
  3946. static struct ctl_table sched_core_sysctls[] = {
  3947. #ifdef CONFIG_SCHEDSTATS
  3948. {
  3949. .procname = "sched_schedstats",
  3950. .data = NULL,
  3951. .maxlen = sizeof(unsigned int),
  3952. .mode = 0644,
  3953. .proc_handler = sysctl_schedstats,
  3954. .extra1 = SYSCTL_ZERO,
  3955. .extra2 = SYSCTL_ONE,
  3956. },
  3957. #endif /* CONFIG_SCHEDSTATS */
  3958. #ifdef CONFIG_UCLAMP_TASK
  3959. {
  3960. .procname = "sched_util_clamp_min",
  3961. .data = &sysctl_sched_uclamp_util_min,
  3962. .maxlen = sizeof(unsigned int),
  3963. .mode = 0644,
  3964. .proc_handler = sysctl_sched_uclamp_handler,
  3965. },
  3966. {
  3967. .procname = "sched_util_clamp_max",
  3968. .data = &sysctl_sched_uclamp_util_max,
  3969. .maxlen = sizeof(unsigned int),
  3970. .mode = 0644,
  3971. .proc_handler = sysctl_sched_uclamp_handler,
  3972. },
  3973. {
  3974. .procname = "sched_util_clamp_min_rt_default",
  3975. .data = &sysctl_sched_uclamp_util_min_rt_default,
  3976. .maxlen = sizeof(unsigned int),
  3977. .mode = 0644,
  3978. .proc_handler = sysctl_sched_uclamp_handler,
  3979. },
  3980. #endif /* CONFIG_UCLAMP_TASK */
  3981. #ifdef CONFIG_NUMA_BALANCING
  3982. {
  3983. .procname = "numa_balancing",
  3984. .data = NULL, /* filled in by handler */
  3985. .maxlen = sizeof(unsigned int),
  3986. .mode = 0644,
  3987. .proc_handler = sysctl_numa_balancing,
  3988. .extra1 = SYSCTL_ZERO,
  3989. .extra2 = SYSCTL_FOUR,
  3990. },
  3991. #endif /* CONFIG_NUMA_BALANCING */
  3992. };
  3993. static int __init sched_core_sysctl_init(void)
  3994. {
  3995. register_sysctl_init("kernel", sched_core_sysctls);
  3996. return 0;
  3997. }
  3998. late_initcall(sched_core_sysctl_init);
  3999. #endif /* CONFIG_SYSCTL */
  4000. /*
  4001. * fork()/clone()-time setup:
  4002. */
  4003. int sched_fork(unsigned long clone_flags, struct task_struct *p)
  4004. {
  4005. __sched_fork(clone_flags, p);
  4006. /*
  4007. * We mark the process as NEW here. This guarantees that
  4008. * nobody will actually run it, and a signal or other external
  4009. * event cannot wake it up and insert it on the runqueue either.
  4010. */
  4011. p->__state = TASK_NEW;
  4012. /*
  4013. * Make sure we do not leak PI boosting priority to the child.
  4014. */
  4015. p->prio = current->normal_prio;
  4016. uclamp_fork(p);
  4017. /*
  4018. * Revert to default priority/policy on fork if requested.
  4019. */
  4020. if (unlikely(p->sched_reset_on_fork)) {
  4021. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  4022. p->policy = SCHED_NORMAL;
  4023. p->static_prio = NICE_TO_PRIO(0);
  4024. p->rt_priority = 0;
  4025. } else if (PRIO_TO_NICE(p->static_prio) < 0)
  4026. p->static_prio = NICE_TO_PRIO(0);
  4027. p->prio = p->normal_prio = p->static_prio;
  4028. set_load_weight(p, false);
  4029. p->se.custom_slice = 0;
  4030. p->se.slice = sysctl_sched_base_slice;
  4031. /*
  4032. * We don't need the reset flag anymore after the fork. It has
  4033. * fulfilled its duty:
  4034. */
  4035. p->sched_reset_on_fork = 0;
  4036. }
  4037. if (dl_prio(p->prio))
  4038. return -EAGAIN;
  4039. scx_pre_fork(p);
  4040. if (rt_prio(p->prio)) {
  4041. p->sched_class = &rt_sched_class;
  4042. #ifdef CONFIG_SCHED_CLASS_EXT
  4043. } else if (task_should_scx(p->policy)) {
  4044. p->sched_class = &ext_sched_class;
  4045. #endif
  4046. } else {
  4047. p->sched_class = &fair_sched_class;
  4048. }
  4049. init_entity_runnable_average(&p->se);
  4050. #ifdef CONFIG_SCHED_INFO
  4051. if (likely(sched_info_on()))
  4052. memset(&p->sched_info, 0, sizeof(p->sched_info));
  4053. #endif
  4054. #if defined(CONFIG_SMP)
  4055. p->on_cpu = 0;
  4056. #endif
  4057. init_task_preempt_count(p);
  4058. #ifdef CONFIG_SMP
  4059. plist_node_init(&p->pushable_tasks, MAX_PRIO);
  4060. RB_CLEAR_NODE(&p->pushable_dl_tasks);
  4061. #endif
  4062. return 0;
  4063. }
  4064. int sched_cgroup_fork(struct task_struct *p, struct kernel_clone_args *kargs)
  4065. {
  4066. unsigned long flags;
  4067. /*
  4068. * Because we're not yet on the pid-hash, p->pi_lock isn't strictly
  4069. * required yet, but lockdep gets upset if rules are violated.
  4070. */
  4071. raw_spin_lock_irqsave(&p->pi_lock, flags);
  4072. #ifdef CONFIG_CGROUP_SCHED
  4073. if (1) {
  4074. struct task_group *tg;
  4075. tg = container_of(kargs->cset->subsys[cpu_cgrp_id],
  4076. struct task_group, css);
  4077. tg = autogroup_task_group(p, tg);
  4078. p->sched_task_group = tg;
  4079. }
  4080. #endif
  4081. rseq_migrate(p);
  4082. /*
  4083. * We're setting the CPU for the first time, we don't migrate,
  4084. * so use __set_task_cpu().
  4085. */
  4086. __set_task_cpu(p, smp_processor_id());
  4087. if (p->sched_class->task_fork)
  4088. p->sched_class->task_fork(p);
  4089. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  4090. return scx_fork(p);
  4091. }
  4092. void sched_cancel_fork(struct task_struct *p)
  4093. {
  4094. scx_cancel_fork(p);
  4095. }
  4096. void sched_post_fork(struct task_struct *p)
  4097. {
  4098. uclamp_post_fork(p);
  4099. scx_post_fork(p);
  4100. }
  4101. unsigned long to_ratio(u64 period, u64 runtime)
  4102. {
  4103. if (runtime == RUNTIME_INF)
  4104. return BW_UNIT;
  4105. /*
  4106. * Doing this here saves a lot of checks in all
  4107. * the calling paths, and returning zero seems
  4108. * safe for them anyway.
  4109. */
  4110. if (period == 0)
  4111. return 0;
  4112. return div64_u64(runtime << BW_SHIFT, period);
  4113. }
  4114. /*
  4115. * wake_up_new_task - wake up a newly created task for the first time.
  4116. *
  4117. * This function will do some initial scheduler statistics housekeeping
  4118. * that must be done for every newly created context, then puts the task
  4119. * on the runqueue and wakes it.
  4120. */
  4121. void wake_up_new_task(struct task_struct *p)
  4122. {
  4123. struct rq_flags rf;
  4124. struct rq *rq;
  4125. int wake_flags = WF_FORK;
  4126. raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
  4127. WRITE_ONCE(p->__state, TASK_RUNNING);
  4128. #ifdef CONFIG_SMP
  4129. /*
  4130. * Fork balancing, do it here and not earlier because:
  4131. * - cpus_ptr can change in the fork path
  4132. * - any previously selected CPU might disappear through hotplug
  4133. *
  4134. * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
  4135. * as we're not fully set-up yet.
  4136. */
  4137. p->recent_used_cpu = task_cpu(p);
  4138. rseq_migrate(p);
  4139. __set_task_cpu(p, select_task_rq(p, task_cpu(p), &wake_flags));
  4140. #endif
  4141. rq = __task_rq_lock(p, &rf);
  4142. update_rq_clock(rq);
  4143. post_init_entity_util_avg(p);
  4144. activate_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_INITIAL);
  4145. trace_sched_wakeup_new(p);
  4146. wakeup_preempt(rq, p, wake_flags);
  4147. #ifdef CONFIG_SMP
  4148. if (p->sched_class->task_woken) {
  4149. /*
  4150. * Nothing relies on rq->lock after this, so it's fine to
  4151. * drop it.
  4152. */
  4153. rq_unpin_lock(rq, &rf);
  4154. p->sched_class->task_woken(rq, p);
  4155. rq_repin_lock(rq, &rf);
  4156. }
  4157. #endif
  4158. task_rq_unlock(rq, p, &rf);
  4159. }
  4160. #ifdef CONFIG_PREEMPT_NOTIFIERS
  4161. static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
  4162. void preempt_notifier_inc(void)
  4163. {
  4164. static_branch_inc(&preempt_notifier_key);
  4165. }
  4166. EXPORT_SYMBOL_GPL(preempt_notifier_inc);
  4167. void preempt_notifier_dec(void)
  4168. {
  4169. static_branch_dec(&preempt_notifier_key);
  4170. }
  4171. EXPORT_SYMBOL_GPL(preempt_notifier_dec);
  4172. /**
  4173. * preempt_notifier_register - tell me when current is being preempted & rescheduled
  4174. * @notifier: notifier struct to register
  4175. */
  4176. void preempt_notifier_register(struct preempt_notifier *notifier)
  4177. {
  4178. if (!static_branch_unlikely(&preempt_notifier_key))
  4179. WARN(1, "registering preempt_notifier while notifiers disabled\n");
  4180. hlist_add_head(&notifier->link, &current->preempt_notifiers);
  4181. }
  4182. EXPORT_SYMBOL_GPL(preempt_notifier_register);
  4183. /**
  4184. * preempt_notifier_unregister - no longer interested in preemption notifications
  4185. * @notifier: notifier struct to unregister
  4186. *
  4187. * This is *not* safe to call from within a preemption notifier.
  4188. */
  4189. void preempt_notifier_unregister(struct preempt_notifier *notifier)
  4190. {
  4191. hlist_del(&notifier->link);
  4192. }
  4193. EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
  4194. static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
  4195. {
  4196. struct preempt_notifier *notifier;
  4197. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  4198. notifier->ops->sched_in(notifier, raw_smp_processor_id());
  4199. }
  4200. static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  4201. {
  4202. if (static_branch_unlikely(&preempt_notifier_key))
  4203. __fire_sched_in_preempt_notifiers(curr);
  4204. }
  4205. static void
  4206. __fire_sched_out_preempt_notifiers(struct task_struct *curr,
  4207. struct task_struct *next)
  4208. {
  4209. struct preempt_notifier *notifier;
  4210. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  4211. notifier->ops->sched_out(notifier, next);
  4212. }
  4213. static __always_inline void
  4214. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  4215. struct task_struct *next)
  4216. {
  4217. if (static_branch_unlikely(&preempt_notifier_key))
  4218. __fire_sched_out_preempt_notifiers(curr, next);
  4219. }
  4220. #else /* !CONFIG_PREEMPT_NOTIFIERS */
  4221. static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  4222. {
  4223. }
  4224. static inline void
  4225. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  4226. struct task_struct *next)
  4227. {
  4228. }
  4229. #endif /* CONFIG_PREEMPT_NOTIFIERS */
  4230. static inline void prepare_task(struct task_struct *next)
  4231. {
  4232. #ifdef CONFIG_SMP
  4233. /*
  4234. * Claim the task as running, we do this before switching to it
  4235. * such that any running task will have this set.
  4236. *
  4237. * See the smp_load_acquire(&p->on_cpu) case in ttwu() and
  4238. * its ordering comment.
  4239. */
  4240. WRITE_ONCE(next->on_cpu, 1);
  4241. #endif
  4242. }
  4243. static inline void finish_task(struct task_struct *prev)
  4244. {
  4245. #ifdef CONFIG_SMP
  4246. /*
  4247. * This must be the very last reference to @prev from this CPU. After
  4248. * p->on_cpu is cleared, the task can be moved to a different CPU. We
  4249. * must ensure this doesn't happen until the switch is completely
  4250. * finished.
  4251. *
  4252. * In particular, the load of prev->state in finish_task_switch() must
  4253. * happen before this.
  4254. *
  4255. * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
  4256. */
  4257. smp_store_release(&prev->on_cpu, 0);
  4258. #endif
  4259. }
  4260. #ifdef CONFIG_SMP
  4261. static void do_balance_callbacks(struct rq *rq, struct balance_callback *head)
  4262. {
  4263. void (*func)(struct rq *rq);
  4264. struct balance_callback *next;
  4265. lockdep_assert_rq_held(rq);
  4266. while (head) {
  4267. func = (void (*)(struct rq *))head->func;
  4268. next = head->next;
  4269. head->next = NULL;
  4270. head = next;
  4271. func(rq);
  4272. }
  4273. }
  4274. static void balance_push(struct rq *rq);
  4275. /*
  4276. * balance_push_callback is a right abuse of the callback interface and plays
  4277. * by significantly different rules.
  4278. *
  4279. * Where the normal balance_callback's purpose is to be ran in the same context
  4280. * that queued it (only later, when it's safe to drop rq->lock again),
  4281. * balance_push_callback is specifically targeted at __schedule().
  4282. *
  4283. * This abuse is tolerated because it places all the unlikely/odd cases behind
  4284. * a single test, namely: rq->balance_callback == NULL.
  4285. */
  4286. struct balance_callback balance_push_callback = {
  4287. .next = NULL,
  4288. .func = balance_push,
  4289. };
  4290. static inline struct balance_callback *
  4291. __splice_balance_callbacks(struct rq *rq, bool split)
  4292. {
  4293. struct balance_callback *head = rq->balance_callback;
  4294. if (likely(!head))
  4295. return NULL;
  4296. lockdep_assert_rq_held(rq);
  4297. /*
  4298. * Must not take balance_push_callback off the list when
  4299. * splice_balance_callbacks() and balance_callbacks() are not
  4300. * in the same rq->lock section.
  4301. *
  4302. * In that case it would be possible for __schedule() to interleave
  4303. * and observe the list empty.
  4304. */
  4305. if (split && head == &balance_push_callback)
  4306. head = NULL;
  4307. else
  4308. rq->balance_callback = NULL;
  4309. return head;
  4310. }
  4311. struct balance_callback *splice_balance_callbacks(struct rq *rq)
  4312. {
  4313. return __splice_balance_callbacks(rq, true);
  4314. }
  4315. static void __balance_callbacks(struct rq *rq)
  4316. {
  4317. do_balance_callbacks(rq, __splice_balance_callbacks(rq, false));
  4318. }
  4319. void balance_callbacks(struct rq *rq, struct balance_callback *head)
  4320. {
  4321. unsigned long flags;
  4322. if (unlikely(head)) {
  4323. raw_spin_rq_lock_irqsave(rq, flags);
  4324. do_balance_callbacks(rq, head);
  4325. raw_spin_rq_unlock_irqrestore(rq, flags);
  4326. }
  4327. }
  4328. #else
  4329. static inline void __balance_callbacks(struct rq *rq)
  4330. {
  4331. }
  4332. #endif
  4333. static inline void
  4334. prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
  4335. {
  4336. /*
  4337. * Since the runqueue lock will be released by the next
  4338. * task (which is an invalid locking op but in the case
  4339. * of the scheduler it's an obvious special-case), so we
  4340. * do an early lockdep release here:
  4341. */
  4342. rq_unpin_lock(rq, rf);
  4343. spin_release(&__rq_lockp(rq)->dep_map, _THIS_IP_);
  4344. #ifdef CONFIG_DEBUG_SPINLOCK
  4345. /* this is a valid case when another task releases the spinlock */
  4346. rq_lockp(rq)->owner = next;
  4347. #endif
  4348. }
  4349. static inline void finish_lock_switch(struct rq *rq)
  4350. {
  4351. /*
  4352. * If we are tracking spinlock dependencies then we have to
  4353. * fix up the runqueue lock - which gets 'carried over' from
  4354. * prev into current:
  4355. */
  4356. spin_acquire(&__rq_lockp(rq)->dep_map, 0, 0, _THIS_IP_);
  4357. __balance_callbacks(rq);
  4358. raw_spin_rq_unlock_irq(rq);
  4359. }
  4360. /*
  4361. * NOP if the arch has not defined these:
  4362. */
  4363. #ifndef prepare_arch_switch
  4364. # define prepare_arch_switch(next) do { } while (0)
  4365. #endif
  4366. #ifndef finish_arch_post_lock_switch
  4367. # define finish_arch_post_lock_switch() do { } while (0)
  4368. #endif
  4369. static inline void kmap_local_sched_out(void)
  4370. {
  4371. #ifdef CONFIG_KMAP_LOCAL
  4372. if (unlikely(current->kmap_ctrl.idx))
  4373. __kmap_local_sched_out();
  4374. #endif
  4375. }
  4376. static inline void kmap_local_sched_in(void)
  4377. {
  4378. #ifdef CONFIG_KMAP_LOCAL
  4379. if (unlikely(current->kmap_ctrl.idx))
  4380. __kmap_local_sched_in();
  4381. #endif
  4382. }
  4383. /**
  4384. * prepare_task_switch - prepare to switch tasks
  4385. * @rq: the runqueue preparing to switch
  4386. * @prev: the current task that is being switched out
  4387. * @next: the task we are going to switch to.
  4388. *
  4389. * This is called with the rq lock held and interrupts off. It must
  4390. * be paired with a subsequent finish_task_switch after the context
  4391. * switch.
  4392. *
  4393. * prepare_task_switch sets up locking and calls architecture specific
  4394. * hooks.
  4395. */
  4396. static inline void
  4397. prepare_task_switch(struct rq *rq, struct task_struct *prev,
  4398. struct task_struct *next)
  4399. {
  4400. kcov_prepare_switch(prev);
  4401. sched_info_switch(rq, prev, next);
  4402. perf_event_task_sched_out(prev, next);
  4403. rseq_preempt(prev);
  4404. fire_sched_out_preempt_notifiers(prev, next);
  4405. kmap_local_sched_out();
  4406. prepare_task(next);
  4407. prepare_arch_switch(next);
  4408. }
  4409. /**
  4410. * finish_task_switch - clean up after a task-switch
  4411. * @prev: the thread we just switched away from.
  4412. *
  4413. * finish_task_switch must be called after the context switch, paired
  4414. * with a prepare_task_switch call before the context switch.
  4415. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  4416. * and do any other architecture-specific cleanup actions.
  4417. *
  4418. * Note that we may have delayed dropping an mm in context_switch(). If
  4419. * so, we finish that here outside of the runqueue lock. (Doing it
  4420. * with the lock held can cause deadlocks; see schedule() for
  4421. * details.)
  4422. *
  4423. * The context switch have flipped the stack from under us and restored the
  4424. * local variables which were saved when this task called schedule() in the
  4425. * past. 'prev == current' is still correct but we need to recalculate this_rq
  4426. * because prev may have moved to another CPU.
  4427. */
  4428. static struct rq *finish_task_switch(struct task_struct *prev)
  4429. __releases(rq->lock)
  4430. {
  4431. struct rq *rq = this_rq();
  4432. struct mm_struct *mm = rq->prev_mm;
  4433. unsigned int prev_state;
  4434. /*
  4435. * The previous task will have left us with a preempt_count of 2
  4436. * because it left us after:
  4437. *
  4438. * schedule()
  4439. * preempt_disable(); // 1
  4440. * __schedule()
  4441. * raw_spin_lock_irq(&rq->lock) // 2
  4442. *
  4443. * Also, see FORK_PREEMPT_COUNT.
  4444. */
  4445. if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
  4446. "corrupted preempt_count: %s/%d/0x%x\n",
  4447. current->comm, current->pid, preempt_count()))
  4448. preempt_count_set(FORK_PREEMPT_COUNT);
  4449. rq->prev_mm = NULL;
  4450. /*
  4451. * A task struct has one reference for the use as "current".
  4452. * If a task dies, then it sets TASK_DEAD in tsk->state and calls
  4453. * schedule one last time. The schedule call will never return, and
  4454. * the scheduled task must drop that reference.
  4455. *
  4456. * We must observe prev->state before clearing prev->on_cpu (in
  4457. * finish_task), otherwise a concurrent wakeup can get prev
  4458. * running on another CPU and we could rave with its RUNNING -> DEAD
  4459. * transition, resulting in a double drop.
  4460. */
  4461. prev_state = READ_ONCE(prev->__state);
  4462. vtime_task_switch(prev);
  4463. perf_event_task_sched_in(prev, current);
  4464. finish_task(prev);
  4465. tick_nohz_task_switch();
  4466. finish_lock_switch(rq);
  4467. finish_arch_post_lock_switch();
  4468. kcov_finish_switch(current);
  4469. /*
  4470. * kmap_local_sched_out() is invoked with rq::lock held and
  4471. * interrupts disabled. There is no requirement for that, but the
  4472. * sched out code does not have an interrupt enabled section.
  4473. * Restoring the maps on sched in does not require interrupts being
  4474. * disabled either.
  4475. */
  4476. kmap_local_sched_in();
  4477. fire_sched_in_preempt_notifiers(current);
  4478. /*
  4479. * When switching through a kernel thread, the loop in
  4480. * membarrier_{private,global}_expedited() may have observed that
  4481. * kernel thread and not issued an IPI. It is therefore possible to
  4482. * schedule between user->kernel->user threads without passing though
  4483. * switch_mm(). Membarrier requires a barrier after storing to
  4484. * rq->curr, before returning to userspace, so provide them here:
  4485. *
  4486. * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
  4487. * provided by mmdrop_lazy_tlb(),
  4488. * - a sync_core for SYNC_CORE.
  4489. */
  4490. if (mm) {
  4491. membarrier_mm_sync_core_before_usermode(mm);
  4492. mmdrop_lazy_tlb_sched(mm);
  4493. }
  4494. if (unlikely(prev_state == TASK_DEAD)) {
  4495. if (prev->sched_class->task_dead)
  4496. prev->sched_class->task_dead(prev);
  4497. /* Task is done with its stack. */
  4498. put_task_stack(prev);
  4499. put_task_struct_rcu_user(prev);
  4500. }
  4501. return rq;
  4502. }
  4503. /**
  4504. * schedule_tail - first thing a freshly forked thread must call.
  4505. * @prev: the thread we just switched away from.
  4506. */
  4507. asmlinkage __visible void schedule_tail(struct task_struct *prev)
  4508. __releases(rq->lock)
  4509. {
  4510. /*
  4511. * New tasks start with FORK_PREEMPT_COUNT, see there and
  4512. * finish_task_switch() for details.
  4513. *
  4514. * finish_task_switch() will drop rq->lock() and lower preempt_count
  4515. * and the preempt_enable() will end up enabling preemption (on
  4516. * PREEMPT_COUNT kernels).
  4517. */
  4518. finish_task_switch(prev);
  4519. preempt_enable();
  4520. if (current->set_child_tid)
  4521. put_user(task_pid_vnr(current), current->set_child_tid);
  4522. calculate_sigpending();
  4523. }
  4524. /*
  4525. * context_switch - switch to the new MM and the new thread's register state.
  4526. */
  4527. static __always_inline struct rq *
  4528. context_switch(struct rq *rq, struct task_struct *prev,
  4529. struct task_struct *next, struct rq_flags *rf)
  4530. {
  4531. prepare_task_switch(rq, prev, next);
  4532. /*
  4533. * For paravirt, this is coupled with an exit in switch_to to
  4534. * combine the page table reload and the switch backend into
  4535. * one hypercall.
  4536. */
  4537. arch_start_context_switch(prev);
  4538. /*
  4539. * kernel -> kernel lazy + transfer active
  4540. * user -> kernel lazy + mmgrab_lazy_tlb() active
  4541. *
  4542. * kernel -> user switch + mmdrop_lazy_tlb() active
  4543. * user -> user switch
  4544. *
  4545. * switch_mm_cid() needs to be updated if the barriers provided
  4546. * by context_switch() are modified.
  4547. */
  4548. if (!next->mm) { // to kernel
  4549. enter_lazy_tlb(prev->active_mm, next);
  4550. next->active_mm = prev->active_mm;
  4551. if (prev->mm) // from user
  4552. mmgrab_lazy_tlb(prev->active_mm);
  4553. else
  4554. prev->active_mm = NULL;
  4555. } else { // to user
  4556. membarrier_switch_mm(rq, prev->active_mm, next->mm);
  4557. /*
  4558. * sys_membarrier() requires an smp_mb() between setting
  4559. * rq->curr / membarrier_switch_mm() and returning to userspace.
  4560. *
  4561. * The below provides this either through switch_mm(), or in
  4562. * case 'prev->active_mm == next->mm' through
  4563. * finish_task_switch()'s mmdrop().
  4564. */
  4565. switch_mm_irqs_off(prev->active_mm, next->mm, next);
  4566. lru_gen_use_mm(next->mm);
  4567. if (!prev->mm) { // from kernel
  4568. /* will mmdrop_lazy_tlb() in finish_task_switch(). */
  4569. rq->prev_mm = prev->active_mm;
  4570. prev->active_mm = NULL;
  4571. }
  4572. }
  4573. /* switch_mm_cid() requires the memory barriers above. */
  4574. switch_mm_cid(rq, prev, next);
  4575. prepare_lock_switch(rq, next, rf);
  4576. /* Here we just switch the register state and the stack. */
  4577. switch_to(prev, next, prev);
  4578. barrier();
  4579. return finish_task_switch(prev);
  4580. }
  4581. /*
  4582. * nr_running and nr_context_switches:
  4583. *
  4584. * externally visible scheduler statistics: current number of runnable
  4585. * threads, total number of context switches performed since bootup.
  4586. */
  4587. unsigned int nr_running(void)
  4588. {
  4589. unsigned int i, sum = 0;
  4590. for_each_online_cpu(i)
  4591. sum += cpu_rq(i)->nr_running;
  4592. return sum;
  4593. }
  4594. /*
  4595. * Check if only the current task is running on the CPU.
  4596. *
  4597. * Caution: this function does not check that the caller has disabled
  4598. * preemption, thus the result might have a time-of-check-to-time-of-use
  4599. * race. The caller is responsible to use it correctly, for example:
  4600. *
  4601. * - from a non-preemptible section (of course)
  4602. *
  4603. * - from a thread that is bound to a single CPU
  4604. *
  4605. * - in a loop with very short iterations (e.g. a polling loop)
  4606. */
  4607. bool single_task_running(void)
  4608. {
  4609. return raw_rq()->nr_running == 1;
  4610. }
  4611. EXPORT_SYMBOL(single_task_running);
  4612. unsigned long long nr_context_switches_cpu(int cpu)
  4613. {
  4614. return cpu_rq(cpu)->nr_switches;
  4615. }
  4616. unsigned long long nr_context_switches(void)
  4617. {
  4618. int i;
  4619. unsigned long long sum = 0;
  4620. for_each_possible_cpu(i)
  4621. sum += cpu_rq(i)->nr_switches;
  4622. return sum;
  4623. }
  4624. /*
  4625. * Consumers of these two interfaces, like for example the cpuidle menu
  4626. * governor, are using nonsensical data. Preferring shallow idle state selection
  4627. * for a CPU that has IO-wait which might not even end up running the task when
  4628. * it does become runnable.
  4629. */
  4630. unsigned int nr_iowait_cpu(int cpu)
  4631. {
  4632. return atomic_read(&cpu_rq(cpu)->nr_iowait);
  4633. }
  4634. /*
  4635. * IO-wait accounting, and how it's mostly bollocks (on SMP).
  4636. *
  4637. * The idea behind IO-wait account is to account the idle time that we could
  4638. * have spend running if it were not for IO. That is, if we were to improve the
  4639. * storage performance, we'd have a proportional reduction in IO-wait time.
  4640. *
  4641. * This all works nicely on UP, where, when a task blocks on IO, we account
  4642. * idle time as IO-wait, because if the storage were faster, it could've been
  4643. * running and we'd not be idle.
  4644. *
  4645. * This has been extended to SMP, by doing the same for each CPU. This however
  4646. * is broken.
  4647. *
  4648. * Imagine for instance the case where two tasks block on one CPU, only the one
  4649. * CPU will have IO-wait accounted, while the other has regular idle. Even
  4650. * though, if the storage were faster, both could've ran at the same time,
  4651. * utilising both CPUs.
  4652. *
  4653. * This means, that when looking globally, the current IO-wait accounting on
  4654. * SMP is a lower bound, by reason of under accounting.
  4655. *
  4656. * Worse, since the numbers are provided per CPU, they are sometimes
  4657. * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
  4658. * associated with any one particular CPU, it can wake to another CPU than it
  4659. * blocked on. This means the per CPU IO-wait number is meaningless.
  4660. *
  4661. * Task CPU affinities can make all that even more 'interesting'.
  4662. */
  4663. unsigned int nr_iowait(void)
  4664. {
  4665. unsigned int i, sum = 0;
  4666. for_each_possible_cpu(i)
  4667. sum += nr_iowait_cpu(i);
  4668. return sum;
  4669. }
  4670. #ifdef CONFIG_SMP
  4671. /*
  4672. * sched_exec - execve() is a valuable balancing opportunity, because at
  4673. * this point the task has the smallest effective memory and cache footprint.
  4674. */
  4675. void sched_exec(void)
  4676. {
  4677. struct task_struct *p = current;
  4678. struct migration_arg arg;
  4679. int dest_cpu;
  4680. scoped_guard (raw_spinlock_irqsave, &p->pi_lock) {
  4681. dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), WF_EXEC);
  4682. if (dest_cpu == smp_processor_id())
  4683. return;
  4684. if (unlikely(!cpu_active(dest_cpu)))
  4685. return;
  4686. arg = (struct migration_arg){ p, dest_cpu };
  4687. }
  4688. stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
  4689. }
  4690. #endif
  4691. DEFINE_PER_CPU(struct kernel_stat, kstat);
  4692. DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
  4693. EXPORT_PER_CPU_SYMBOL(kstat);
  4694. EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
  4695. /*
  4696. * The function fair_sched_class.update_curr accesses the struct curr
  4697. * and its field curr->exec_start; when called from task_sched_runtime(),
  4698. * we observe a high rate of cache misses in practice.
  4699. * Prefetching this data results in improved performance.
  4700. */
  4701. static inline void prefetch_curr_exec_start(struct task_struct *p)
  4702. {
  4703. #ifdef CONFIG_FAIR_GROUP_SCHED
  4704. struct sched_entity *curr = p->se.cfs_rq->curr;
  4705. #else
  4706. struct sched_entity *curr = task_rq(p)->cfs.curr;
  4707. #endif
  4708. prefetch(curr);
  4709. prefetch(&curr->exec_start);
  4710. }
  4711. /*
  4712. * Return accounted runtime for the task.
  4713. * In case the task is currently running, return the runtime plus current's
  4714. * pending runtime that have not been accounted yet.
  4715. */
  4716. unsigned long long task_sched_runtime(struct task_struct *p)
  4717. {
  4718. struct rq_flags rf;
  4719. struct rq *rq;
  4720. u64 ns;
  4721. #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
  4722. /*
  4723. * 64-bit doesn't need locks to atomically read a 64-bit value.
  4724. * So we have a optimization chance when the task's delta_exec is 0.
  4725. * Reading ->on_cpu is racy, but this is OK.
  4726. *
  4727. * If we race with it leaving CPU, we'll take a lock. So we're correct.
  4728. * If we race with it entering CPU, unaccounted time is 0. This is
  4729. * indistinguishable from the read occurring a few cycles earlier.
  4730. * If we see ->on_cpu without ->on_rq, the task is leaving, and has
  4731. * been accounted, so we're correct here as well.
  4732. */
  4733. if (!p->on_cpu || !task_on_rq_queued(p))
  4734. return p->se.sum_exec_runtime;
  4735. #endif
  4736. rq = task_rq_lock(p, &rf);
  4737. /*
  4738. * Must be ->curr _and_ ->on_rq. If dequeued, we would
  4739. * project cycles that may never be accounted to this
  4740. * thread, breaking clock_gettime().
  4741. */
  4742. if (task_current(rq, p) && task_on_rq_queued(p)) {
  4743. prefetch_curr_exec_start(p);
  4744. update_rq_clock(rq);
  4745. p->sched_class->update_curr(rq);
  4746. }
  4747. ns = p->se.sum_exec_runtime;
  4748. task_rq_unlock(rq, p, &rf);
  4749. return ns;
  4750. }
  4751. #ifdef CONFIG_SCHED_DEBUG
  4752. static u64 cpu_resched_latency(struct rq *rq)
  4753. {
  4754. int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms);
  4755. u64 resched_latency, now = rq_clock(rq);
  4756. static bool warned_once;
  4757. if (sysctl_resched_latency_warn_once && warned_once)
  4758. return 0;
  4759. if (!need_resched() || !latency_warn_ms)
  4760. return 0;
  4761. if (system_state == SYSTEM_BOOTING)
  4762. return 0;
  4763. if (!rq->last_seen_need_resched_ns) {
  4764. rq->last_seen_need_resched_ns = now;
  4765. rq->ticks_without_resched = 0;
  4766. return 0;
  4767. }
  4768. rq->ticks_without_resched++;
  4769. resched_latency = now - rq->last_seen_need_resched_ns;
  4770. if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC)
  4771. return 0;
  4772. warned_once = true;
  4773. return resched_latency;
  4774. }
  4775. static int __init setup_resched_latency_warn_ms(char *str)
  4776. {
  4777. long val;
  4778. if ((kstrtol(str, 0, &val))) {
  4779. pr_warn("Unable to set resched_latency_warn_ms\n");
  4780. return 1;
  4781. }
  4782. sysctl_resched_latency_warn_ms = val;
  4783. return 1;
  4784. }
  4785. __setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms);
  4786. #else
  4787. static inline u64 cpu_resched_latency(struct rq *rq) { return 0; }
  4788. #endif /* CONFIG_SCHED_DEBUG */
  4789. /*
  4790. * This function gets called by the timer code, with HZ frequency.
  4791. * We call it with interrupts disabled.
  4792. */
  4793. void sched_tick(void)
  4794. {
  4795. int cpu = smp_processor_id();
  4796. struct rq *rq = cpu_rq(cpu);
  4797. struct task_struct *curr;
  4798. struct rq_flags rf;
  4799. unsigned long hw_pressure;
  4800. u64 resched_latency;
  4801. if (housekeeping_cpu(cpu, HK_TYPE_TICK))
  4802. arch_scale_freq_tick();
  4803. sched_clock_tick();
  4804. rq_lock(rq, &rf);
  4805. curr = rq->curr;
  4806. psi_account_irqtime(rq, curr, NULL);
  4807. update_rq_clock(rq);
  4808. hw_pressure = arch_scale_hw_pressure(cpu_of(rq));
  4809. update_hw_load_avg(rq_clock_task(rq), rq, hw_pressure);
  4810. curr->sched_class->task_tick(rq, curr, 0);
  4811. if (sched_feat(LATENCY_WARN))
  4812. resched_latency = cpu_resched_latency(rq);
  4813. calc_global_load_tick(rq);
  4814. sched_core_tick(rq);
  4815. task_tick_mm_cid(rq, curr);
  4816. scx_tick(rq);
  4817. rq_unlock(rq, &rf);
  4818. if (sched_feat(LATENCY_WARN) && resched_latency)
  4819. resched_latency_warn(cpu, resched_latency);
  4820. perf_event_task_tick();
  4821. if (curr->flags & PF_WQ_WORKER)
  4822. wq_worker_tick(curr);
  4823. #ifdef CONFIG_SMP
  4824. if (!scx_switched_all()) {
  4825. rq->idle_balance = idle_cpu(cpu);
  4826. sched_balance_trigger(rq);
  4827. }
  4828. #endif
  4829. }
  4830. #ifdef CONFIG_NO_HZ_FULL
  4831. struct tick_work {
  4832. int cpu;
  4833. atomic_t state;
  4834. struct delayed_work work;
  4835. };
  4836. /* Values for ->state, see diagram below. */
  4837. #define TICK_SCHED_REMOTE_OFFLINE 0
  4838. #define TICK_SCHED_REMOTE_OFFLINING 1
  4839. #define TICK_SCHED_REMOTE_RUNNING 2
  4840. /*
  4841. * State diagram for ->state:
  4842. *
  4843. *
  4844. * TICK_SCHED_REMOTE_OFFLINE
  4845. * | ^
  4846. * | |
  4847. * | | sched_tick_remote()
  4848. * | |
  4849. * | |
  4850. * +--TICK_SCHED_REMOTE_OFFLINING
  4851. * | ^
  4852. * | |
  4853. * sched_tick_start() | | sched_tick_stop()
  4854. * | |
  4855. * V |
  4856. * TICK_SCHED_REMOTE_RUNNING
  4857. *
  4858. *
  4859. * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
  4860. * and sched_tick_start() are happy to leave the state in RUNNING.
  4861. */
  4862. static struct tick_work __percpu *tick_work_cpu;
  4863. static void sched_tick_remote(struct work_struct *work)
  4864. {
  4865. struct delayed_work *dwork = to_delayed_work(work);
  4866. struct tick_work *twork = container_of(dwork, struct tick_work, work);
  4867. int cpu = twork->cpu;
  4868. struct rq *rq = cpu_rq(cpu);
  4869. int os;
  4870. /*
  4871. * Handle the tick only if it appears the remote CPU is running in full
  4872. * dynticks mode. The check is racy by nature, but missing a tick or
  4873. * having one too much is no big deal because the scheduler tick updates
  4874. * statistics and checks timeslices in a time-independent way, regardless
  4875. * of when exactly it is running.
  4876. */
  4877. if (tick_nohz_tick_stopped_cpu(cpu)) {
  4878. guard(rq_lock_irq)(rq);
  4879. struct task_struct *curr = rq->curr;
  4880. if (cpu_online(cpu)) {
  4881. update_rq_clock(rq);
  4882. if (!is_idle_task(curr)) {
  4883. /*
  4884. * Make sure the next tick runs within a
  4885. * reasonable amount of time.
  4886. */
  4887. u64 delta = rq_clock_task(rq) - curr->se.exec_start;
  4888. WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
  4889. }
  4890. curr->sched_class->task_tick(rq, curr, 0);
  4891. calc_load_nohz_remote(rq);
  4892. }
  4893. }
  4894. /*
  4895. * Run the remote tick once per second (1Hz). This arbitrary
  4896. * frequency is large enough to avoid overload but short enough
  4897. * to keep scheduler internal stats reasonably up to date. But
  4898. * first update state to reflect hotplug activity if required.
  4899. */
  4900. os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
  4901. WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
  4902. if (os == TICK_SCHED_REMOTE_RUNNING)
  4903. queue_delayed_work(system_unbound_wq, dwork, HZ);
  4904. }
  4905. static void sched_tick_start(int cpu)
  4906. {
  4907. int os;
  4908. struct tick_work *twork;
  4909. if (housekeeping_cpu(cpu, HK_TYPE_TICK))
  4910. return;
  4911. WARN_ON_ONCE(!tick_work_cpu);
  4912. twork = per_cpu_ptr(tick_work_cpu, cpu);
  4913. os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
  4914. WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
  4915. if (os == TICK_SCHED_REMOTE_OFFLINE) {
  4916. twork->cpu = cpu;
  4917. INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
  4918. queue_delayed_work(system_unbound_wq, &twork->work, HZ);
  4919. }
  4920. }
  4921. #ifdef CONFIG_HOTPLUG_CPU
  4922. static void sched_tick_stop(int cpu)
  4923. {
  4924. struct tick_work *twork;
  4925. int os;
  4926. if (housekeeping_cpu(cpu, HK_TYPE_TICK))
  4927. return;
  4928. WARN_ON_ONCE(!tick_work_cpu);
  4929. twork = per_cpu_ptr(tick_work_cpu, cpu);
  4930. /* There cannot be competing actions, but don't rely on stop-machine. */
  4931. os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
  4932. WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
  4933. /* Don't cancel, as this would mess up the state machine. */
  4934. }
  4935. #endif /* CONFIG_HOTPLUG_CPU */
  4936. int __init sched_tick_offload_init(void)
  4937. {
  4938. tick_work_cpu = alloc_percpu(struct tick_work);
  4939. BUG_ON(!tick_work_cpu);
  4940. return 0;
  4941. }
  4942. #else /* !CONFIG_NO_HZ_FULL */
  4943. static inline void sched_tick_start(int cpu) { }
  4944. static inline void sched_tick_stop(int cpu) { }
  4945. #endif
  4946. #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
  4947. defined(CONFIG_TRACE_PREEMPT_TOGGLE))
  4948. /*
  4949. * If the value passed in is equal to the current preempt count
  4950. * then we just disabled preemption. Start timing the latency.
  4951. */
  4952. static inline void preempt_latency_start(int val)
  4953. {
  4954. if (preempt_count() == val) {
  4955. unsigned long ip = get_lock_parent_ip();
  4956. #ifdef CONFIG_DEBUG_PREEMPT
  4957. current->preempt_disable_ip = ip;
  4958. #endif
  4959. trace_preempt_off(CALLER_ADDR0, ip);
  4960. }
  4961. }
  4962. void preempt_count_add(int val)
  4963. {
  4964. #ifdef CONFIG_DEBUG_PREEMPT
  4965. /*
  4966. * Underflow?
  4967. */
  4968. if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
  4969. return;
  4970. #endif
  4971. __preempt_count_add(val);
  4972. #ifdef CONFIG_DEBUG_PREEMPT
  4973. /*
  4974. * Spinlock count overflowing soon?
  4975. */
  4976. DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
  4977. PREEMPT_MASK - 10);
  4978. #endif
  4979. preempt_latency_start(val);
  4980. }
  4981. EXPORT_SYMBOL(preempt_count_add);
  4982. NOKPROBE_SYMBOL(preempt_count_add);
  4983. /*
  4984. * If the value passed in equals to the current preempt count
  4985. * then we just enabled preemption. Stop timing the latency.
  4986. */
  4987. static inline void preempt_latency_stop(int val)
  4988. {
  4989. if (preempt_count() == val)
  4990. trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
  4991. }
  4992. void preempt_count_sub(int val)
  4993. {
  4994. #ifdef CONFIG_DEBUG_PREEMPT
  4995. /*
  4996. * Underflow?
  4997. */
  4998. if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
  4999. return;
  5000. /*
  5001. * Is the spinlock portion underflowing?
  5002. */
  5003. if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
  5004. !(preempt_count() & PREEMPT_MASK)))
  5005. return;
  5006. #endif
  5007. preempt_latency_stop(val);
  5008. __preempt_count_sub(val);
  5009. }
  5010. EXPORT_SYMBOL(preempt_count_sub);
  5011. NOKPROBE_SYMBOL(preempt_count_sub);
  5012. #else
  5013. static inline void preempt_latency_start(int val) { }
  5014. static inline void preempt_latency_stop(int val) { }
  5015. #endif
  5016. static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
  5017. {
  5018. #ifdef CONFIG_DEBUG_PREEMPT
  5019. return p->preempt_disable_ip;
  5020. #else
  5021. return 0;
  5022. #endif
  5023. }
  5024. /*
  5025. * Print scheduling while atomic bug:
  5026. */
  5027. static noinline void __schedule_bug(struct task_struct *prev)
  5028. {
  5029. /* Save this before calling printk(), since that will clobber it */
  5030. unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
  5031. if (oops_in_progress)
  5032. return;
  5033. printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
  5034. prev->comm, prev->pid, preempt_count());
  5035. debug_show_held_locks(prev);
  5036. print_modules();
  5037. if (irqs_disabled())
  5038. print_irqtrace_events(prev);
  5039. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) {
  5040. pr_err("Preemption disabled at:");
  5041. print_ip_sym(KERN_ERR, preempt_disable_ip);
  5042. }
  5043. check_panic_on_warn("scheduling while atomic");
  5044. dump_stack();
  5045. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  5046. }
  5047. /*
  5048. * Various schedule()-time debugging checks and statistics:
  5049. */
  5050. static inline void schedule_debug(struct task_struct *prev, bool preempt)
  5051. {
  5052. #ifdef CONFIG_SCHED_STACK_END_CHECK
  5053. if (task_stack_end_corrupted(prev))
  5054. panic("corrupted stack end detected inside scheduler\n");
  5055. if (task_scs_end_corrupted(prev))
  5056. panic("corrupted shadow stack detected inside scheduler\n");
  5057. #endif
  5058. #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
  5059. if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) {
  5060. printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n",
  5061. prev->comm, prev->pid, prev->non_block_count);
  5062. dump_stack();
  5063. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  5064. }
  5065. #endif
  5066. if (unlikely(in_atomic_preempt_off())) {
  5067. __schedule_bug(prev);
  5068. preempt_count_set(PREEMPT_DISABLED);
  5069. }
  5070. rcu_sleep_check();
  5071. SCHED_WARN_ON(ct_state() == CT_STATE_USER);
  5072. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  5073. schedstat_inc(this_rq()->sched_count);
  5074. }
  5075. static void prev_balance(struct rq *rq, struct task_struct *prev,
  5076. struct rq_flags *rf)
  5077. {
  5078. const struct sched_class *start_class = prev->sched_class;
  5079. const struct sched_class *class;
  5080. #ifdef CONFIG_SCHED_CLASS_EXT
  5081. /*
  5082. * SCX requires a balance() call before every pick_task() including when
  5083. * waking up from SCHED_IDLE. If @start_class is below SCX, start from
  5084. * SCX instead. Also, set a flag to detect missing balance() call.
  5085. */
  5086. if (scx_enabled()) {
  5087. rq->scx.flags |= SCX_RQ_BAL_PENDING;
  5088. if (sched_class_above(&ext_sched_class, start_class))
  5089. start_class = &ext_sched_class;
  5090. }
  5091. #endif
  5092. /*
  5093. * We must do the balancing pass before put_prev_task(), such
  5094. * that when we release the rq->lock the task is in the same
  5095. * state as before we took rq->lock.
  5096. *
  5097. * We can terminate the balance pass as soon as we know there is
  5098. * a runnable task of @class priority or higher.
  5099. */
  5100. for_active_class_range(class, start_class, &idle_sched_class) {
  5101. if (class->balance && class->balance(rq, prev, rf))
  5102. break;
  5103. }
  5104. }
  5105. /*
  5106. * Pick up the highest-prio task:
  5107. */
  5108. static inline struct task_struct *
  5109. __pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  5110. {
  5111. const struct sched_class *class;
  5112. struct task_struct *p;
  5113. rq->dl_server = NULL;
  5114. if (scx_enabled())
  5115. goto restart;
  5116. /*
  5117. * Optimization: we know that if all tasks are in the fair class we can
  5118. * call that function directly, but only if the @prev task wasn't of a
  5119. * higher scheduling class, because otherwise those lose the
  5120. * opportunity to pull in more work from other CPUs.
  5121. */
  5122. if (likely(!sched_class_above(prev->sched_class, &fair_sched_class) &&
  5123. rq->nr_running == rq->cfs.h_nr_running)) {
  5124. p = pick_next_task_fair(rq, prev, rf);
  5125. if (unlikely(p == RETRY_TASK))
  5126. goto restart;
  5127. /* Assume the next prioritized class is idle_sched_class */
  5128. if (!p) {
  5129. p = pick_task_idle(rq);
  5130. put_prev_set_next_task(rq, prev, p);
  5131. }
  5132. return p;
  5133. }
  5134. restart:
  5135. prev_balance(rq, prev, rf);
  5136. for_each_active_class(class) {
  5137. if (class->pick_next_task) {
  5138. p = class->pick_next_task(rq, prev);
  5139. if (p)
  5140. return p;
  5141. } else {
  5142. p = class->pick_task(rq);
  5143. if (p) {
  5144. put_prev_set_next_task(rq, prev, p);
  5145. return p;
  5146. }
  5147. }
  5148. }
  5149. BUG(); /* The idle class should always have a runnable task. */
  5150. }
  5151. #ifdef CONFIG_SCHED_CORE
  5152. static inline bool is_task_rq_idle(struct task_struct *t)
  5153. {
  5154. return (task_rq(t)->idle == t);
  5155. }
  5156. static inline bool cookie_equals(struct task_struct *a, unsigned long cookie)
  5157. {
  5158. return is_task_rq_idle(a) || (a->core_cookie == cookie);
  5159. }
  5160. static inline bool cookie_match(struct task_struct *a, struct task_struct *b)
  5161. {
  5162. if (is_task_rq_idle(a) || is_task_rq_idle(b))
  5163. return true;
  5164. return a->core_cookie == b->core_cookie;
  5165. }
  5166. static inline struct task_struct *pick_task(struct rq *rq)
  5167. {
  5168. const struct sched_class *class;
  5169. struct task_struct *p;
  5170. rq->dl_server = NULL;
  5171. for_each_active_class(class) {
  5172. p = class->pick_task(rq);
  5173. if (p)
  5174. return p;
  5175. }
  5176. BUG(); /* The idle class should always have a runnable task. */
  5177. }
  5178. extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi);
  5179. static void queue_core_balance(struct rq *rq);
  5180. static struct task_struct *
  5181. pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  5182. {
  5183. struct task_struct *next, *p, *max = NULL;
  5184. const struct cpumask *smt_mask;
  5185. bool fi_before = false;
  5186. bool core_clock_updated = (rq == rq->core);
  5187. unsigned long cookie;
  5188. int i, cpu, occ = 0;
  5189. struct rq *rq_i;
  5190. bool need_sync;
  5191. if (!sched_core_enabled(rq))
  5192. return __pick_next_task(rq, prev, rf);
  5193. cpu = cpu_of(rq);
  5194. /* Stopper task is switching into idle, no need core-wide selection. */
  5195. if (cpu_is_offline(cpu)) {
  5196. /*
  5197. * Reset core_pick so that we don't enter the fastpath when
  5198. * coming online. core_pick would already be migrated to
  5199. * another cpu during offline.
  5200. */
  5201. rq->core_pick = NULL;
  5202. rq->core_dl_server = NULL;
  5203. return __pick_next_task(rq, prev, rf);
  5204. }
  5205. /*
  5206. * If there were no {en,de}queues since we picked (IOW, the task
  5207. * pointers are all still valid), and we haven't scheduled the last
  5208. * pick yet, do so now.
  5209. *
  5210. * rq->core_pick can be NULL if no selection was made for a CPU because
  5211. * it was either offline or went offline during a sibling's core-wide
  5212. * selection. In this case, do a core-wide selection.
  5213. */
  5214. if (rq->core->core_pick_seq == rq->core->core_task_seq &&
  5215. rq->core->core_pick_seq != rq->core_sched_seq &&
  5216. rq->core_pick) {
  5217. WRITE_ONCE(rq->core_sched_seq, rq->core->core_pick_seq);
  5218. next = rq->core_pick;
  5219. rq->dl_server = rq->core_dl_server;
  5220. rq->core_pick = NULL;
  5221. rq->core_dl_server = NULL;
  5222. goto out_set_next;
  5223. }
  5224. prev_balance(rq, prev, rf);
  5225. smt_mask = cpu_smt_mask(cpu);
  5226. need_sync = !!rq->core->core_cookie;
  5227. /* reset state */
  5228. rq->core->core_cookie = 0UL;
  5229. if (rq->core->core_forceidle_count) {
  5230. if (!core_clock_updated) {
  5231. update_rq_clock(rq->core);
  5232. core_clock_updated = true;
  5233. }
  5234. sched_core_account_forceidle(rq);
  5235. /* reset after accounting force idle */
  5236. rq->core->core_forceidle_start = 0;
  5237. rq->core->core_forceidle_count = 0;
  5238. rq->core->core_forceidle_occupation = 0;
  5239. need_sync = true;
  5240. fi_before = true;
  5241. }
  5242. /*
  5243. * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq
  5244. *
  5245. * @task_seq guards the task state ({en,de}queues)
  5246. * @pick_seq is the @task_seq we did a selection on
  5247. * @sched_seq is the @pick_seq we scheduled
  5248. *
  5249. * However, preemptions can cause multiple picks on the same task set.
  5250. * 'Fix' this by also increasing @task_seq for every pick.
  5251. */
  5252. rq->core->core_task_seq++;
  5253. /*
  5254. * Optimize for common case where this CPU has no cookies
  5255. * and there are no cookied tasks running on siblings.
  5256. */
  5257. if (!need_sync) {
  5258. next = pick_task(rq);
  5259. if (!next->core_cookie) {
  5260. rq->core_pick = NULL;
  5261. rq->core_dl_server = NULL;
  5262. /*
  5263. * For robustness, update the min_vruntime_fi for
  5264. * unconstrained picks as well.
  5265. */
  5266. WARN_ON_ONCE(fi_before);
  5267. task_vruntime_update(rq, next, false);
  5268. goto out_set_next;
  5269. }
  5270. }
  5271. /*
  5272. * For each thread: do the regular task pick and find the max prio task
  5273. * amongst them.
  5274. *
  5275. * Tie-break prio towards the current CPU
  5276. */
  5277. for_each_cpu_wrap(i, smt_mask, cpu) {
  5278. rq_i = cpu_rq(i);
  5279. /*
  5280. * Current cpu always has its clock updated on entrance to
  5281. * pick_next_task(). If the current cpu is not the core,
  5282. * the core may also have been updated above.
  5283. */
  5284. if (i != cpu && (rq_i != rq->core || !core_clock_updated))
  5285. update_rq_clock(rq_i);
  5286. rq_i->core_pick = p = pick_task(rq_i);
  5287. rq_i->core_dl_server = rq_i->dl_server;
  5288. if (!max || prio_less(max, p, fi_before))
  5289. max = p;
  5290. }
  5291. cookie = rq->core->core_cookie = max->core_cookie;
  5292. /*
  5293. * For each thread: try and find a runnable task that matches @max or
  5294. * force idle.
  5295. */
  5296. for_each_cpu(i, smt_mask) {
  5297. rq_i = cpu_rq(i);
  5298. p = rq_i->core_pick;
  5299. if (!cookie_equals(p, cookie)) {
  5300. p = NULL;
  5301. if (cookie)
  5302. p = sched_core_find(rq_i, cookie);
  5303. if (!p)
  5304. p = idle_sched_class.pick_task(rq_i);
  5305. }
  5306. rq_i->core_pick = p;
  5307. rq_i->core_dl_server = NULL;
  5308. if (p == rq_i->idle) {
  5309. if (rq_i->nr_running) {
  5310. rq->core->core_forceidle_count++;
  5311. if (!fi_before)
  5312. rq->core->core_forceidle_seq++;
  5313. }
  5314. } else {
  5315. occ++;
  5316. }
  5317. }
  5318. if (schedstat_enabled() && rq->core->core_forceidle_count) {
  5319. rq->core->core_forceidle_start = rq_clock(rq->core);
  5320. rq->core->core_forceidle_occupation = occ;
  5321. }
  5322. rq->core->core_pick_seq = rq->core->core_task_seq;
  5323. next = rq->core_pick;
  5324. rq->core_sched_seq = rq->core->core_pick_seq;
  5325. /* Something should have been selected for current CPU */
  5326. WARN_ON_ONCE(!next);
  5327. /*
  5328. * Reschedule siblings
  5329. *
  5330. * NOTE: L1TF -- at this point we're no longer running the old task and
  5331. * sending an IPI (below) ensures the sibling will no longer be running
  5332. * their task. This ensures there is no inter-sibling overlap between
  5333. * non-matching user state.
  5334. */
  5335. for_each_cpu(i, smt_mask) {
  5336. rq_i = cpu_rq(i);
  5337. /*
  5338. * An online sibling might have gone offline before a task
  5339. * could be picked for it, or it might be offline but later
  5340. * happen to come online, but its too late and nothing was
  5341. * picked for it. That's Ok - it will pick tasks for itself,
  5342. * so ignore it.
  5343. */
  5344. if (!rq_i->core_pick)
  5345. continue;
  5346. /*
  5347. * Update for new !FI->FI transitions, or if continuing to be in !FI:
  5348. * fi_before fi update?
  5349. * 0 0 1
  5350. * 0 1 1
  5351. * 1 0 1
  5352. * 1 1 0
  5353. */
  5354. if (!(fi_before && rq->core->core_forceidle_count))
  5355. task_vruntime_update(rq_i, rq_i->core_pick, !!rq->core->core_forceidle_count);
  5356. rq_i->core_pick->core_occupation = occ;
  5357. if (i == cpu) {
  5358. rq_i->core_pick = NULL;
  5359. rq_i->core_dl_server = NULL;
  5360. continue;
  5361. }
  5362. /* Did we break L1TF mitigation requirements? */
  5363. WARN_ON_ONCE(!cookie_match(next, rq_i->core_pick));
  5364. if (rq_i->curr == rq_i->core_pick) {
  5365. rq_i->core_pick = NULL;
  5366. rq_i->core_dl_server = NULL;
  5367. continue;
  5368. }
  5369. resched_curr(rq_i);
  5370. }
  5371. out_set_next:
  5372. put_prev_set_next_task(rq, prev, next);
  5373. if (rq->core->core_forceidle_count && next == rq->idle)
  5374. queue_core_balance(rq);
  5375. return next;
  5376. }
  5377. static bool try_steal_cookie(int this, int that)
  5378. {
  5379. struct rq *dst = cpu_rq(this), *src = cpu_rq(that);
  5380. struct task_struct *p;
  5381. unsigned long cookie;
  5382. bool success = false;
  5383. guard(irq)();
  5384. guard(double_rq_lock)(dst, src);
  5385. cookie = dst->core->core_cookie;
  5386. if (!cookie)
  5387. return false;
  5388. if (dst->curr != dst->idle)
  5389. return false;
  5390. p = sched_core_find(src, cookie);
  5391. if (!p)
  5392. return false;
  5393. do {
  5394. if (p == src->core_pick || p == src->curr)
  5395. goto next;
  5396. if (!is_cpu_allowed(p, this))
  5397. goto next;
  5398. if (p->core_occupation > dst->idle->core_occupation)
  5399. goto next;
  5400. /*
  5401. * sched_core_find() and sched_core_next() will ensure
  5402. * that task @p is not throttled now, we also need to
  5403. * check whether the runqueue of the destination CPU is
  5404. * being throttled.
  5405. */
  5406. if (sched_task_is_throttled(p, this))
  5407. goto next;
  5408. deactivate_task(src, p, 0);
  5409. set_task_cpu(p, this);
  5410. activate_task(dst, p, 0);
  5411. resched_curr(dst);
  5412. success = true;
  5413. break;
  5414. next:
  5415. p = sched_core_next(p, cookie);
  5416. } while (p);
  5417. return success;
  5418. }
  5419. static bool steal_cookie_task(int cpu, struct sched_domain *sd)
  5420. {
  5421. int i;
  5422. for_each_cpu_wrap(i, sched_domain_span(sd), cpu + 1) {
  5423. if (i == cpu)
  5424. continue;
  5425. if (need_resched())
  5426. break;
  5427. if (try_steal_cookie(cpu, i))
  5428. return true;
  5429. }
  5430. return false;
  5431. }
  5432. static void sched_core_balance(struct rq *rq)
  5433. {
  5434. struct sched_domain *sd;
  5435. int cpu = cpu_of(rq);
  5436. guard(preempt)();
  5437. guard(rcu)();
  5438. raw_spin_rq_unlock_irq(rq);
  5439. for_each_domain(cpu, sd) {
  5440. if (need_resched())
  5441. break;
  5442. if (steal_cookie_task(cpu, sd))
  5443. break;
  5444. }
  5445. raw_spin_rq_lock_irq(rq);
  5446. }
  5447. static DEFINE_PER_CPU(struct balance_callback, core_balance_head);
  5448. static void queue_core_balance(struct rq *rq)
  5449. {
  5450. if (!sched_core_enabled(rq))
  5451. return;
  5452. if (!rq->core->core_cookie)
  5453. return;
  5454. if (!rq->nr_running) /* not forced idle */
  5455. return;
  5456. queue_balance_callback(rq, &per_cpu(core_balance_head, rq->cpu), sched_core_balance);
  5457. }
  5458. DEFINE_LOCK_GUARD_1(core_lock, int,
  5459. sched_core_lock(*_T->lock, &_T->flags),
  5460. sched_core_unlock(*_T->lock, &_T->flags),
  5461. unsigned long flags)
  5462. static void sched_core_cpu_starting(unsigned int cpu)
  5463. {
  5464. const struct cpumask *smt_mask = cpu_smt_mask(cpu);
  5465. struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
  5466. int t;
  5467. guard(core_lock)(&cpu);
  5468. WARN_ON_ONCE(rq->core != rq);
  5469. /* if we're the first, we'll be our own leader */
  5470. if (cpumask_weight(smt_mask) == 1)
  5471. return;
  5472. /* find the leader */
  5473. for_each_cpu(t, smt_mask) {
  5474. if (t == cpu)
  5475. continue;
  5476. rq = cpu_rq(t);
  5477. if (rq->core == rq) {
  5478. core_rq = rq;
  5479. break;
  5480. }
  5481. }
  5482. if (WARN_ON_ONCE(!core_rq)) /* whoopsie */
  5483. return;
  5484. /* install and validate core_rq */
  5485. for_each_cpu(t, smt_mask) {
  5486. rq = cpu_rq(t);
  5487. if (t == cpu)
  5488. rq->core = core_rq;
  5489. WARN_ON_ONCE(rq->core != core_rq);
  5490. }
  5491. }
  5492. static void sched_core_cpu_deactivate(unsigned int cpu)
  5493. {
  5494. const struct cpumask *smt_mask = cpu_smt_mask(cpu);
  5495. struct rq *rq = cpu_rq(cpu), *core_rq = NULL;
  5496. int t;
  5497. guard(core_lock)(&cpu);
  5498. /* if we're the last man standing, nothing to do */
  5499. if (cpumask_weight(smt_mask) == 1) {
  5500. WARN_ON_ONCE(rq->core != rq);
  5501. return;
  5502. }
  5503. /* if we're not the leader, nothing to do */
  5504. if (rq->core != rq)
  5505. return;
  5506. /* find a new leader */
  5507. for_each_cpu(t, smt_mask) {
  5508. if (t == cpu)
  5509. continue;
  5510. core_rq = cpu_rq(t);
  5511. break;
  5512. }
  5513. if (WARN_ON_ONCE(!core_rq)) /* impossible */
  5514. return;
  5515. /* copy the shared state to the new leader */
  5516. core_rq->core_task_seq = rq->core_task_seq;
  5517. core_rq->core_pick_seq = rq->core_pick_seq;
  5518. core_rq->core_cookie = rq->core_cookie;
  5519. core_rq->core_forceidle_count = rq->core_forceidle_count;
  5520. core_rq->core_forceidle_seq = rq->core_forceidle_seq;
  5521. core_rq->core_forceidle_occupation = rq->core_forceidle_occupation;
  5522. /*
  5523. * Accounting edge for forced idle is handled in pick_next_task().
  5524. * Don't need another one here, since the hotplug thread shouldn't
  5525. * have a cookie.
  5526. */
  5527. core_rq->core_forceidle_start = 0;
  5528. /* install new leader */
  5529. for_each_cpu(t, smt_mask) {
  5530. rq = cpu_rq(t);
  5531. rq->core = core_rq;
  5532. }
  5533. }
  5534. static inline void sched_core_cpu_dying(unsigned int cpu)
  5535. {
  5536. struct rq *rq = cpu_rq(cpu);
  5537. if (rq->core != rq)
  5538. rq->core = rq;
  5539. }
  5540. #else /* !CONFIG_SCHED_CORE */
  5541. static inline void sched_core_cpu_starting(unsigned int cpu) {}
  5542. static inline void sched_core_cpu_deactivate(unsigned int cpu) {}
  5543. static inline void sched_core_cpu_dying(unsigned int cpu) {}
  5544. static struct task_struct *
  5545. pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  5546. {
  5547. return __pick_next_task(rq, prev, rf);
  5548. }
  5549. #endif /* CONFIG_SCHED_CORE */
  5550. /*
  5551. * Constants for the sched_mode argument of __schedule().
  5552. *
  5553. * The mode argument allows RT enabled kernels to differentiate a
  5554. * preemption from blocking on an 'sleeping' spin/rwlock.
  5555. */
  5556. #define SM_IDLE (-1)
  5557. #define SM_NONE 0
  5558. #define SM_PREEMPT 1
  5559. #define SM_RTLOCK_WAIT 2
  5560. /*
  5561. * Helper function for __schedule()
  5562. *
  5563. * If a task does not have signals pending, deactivate it
  5564. * Otherwise marks the task's __state as RUNNING
  5565. */
  5566. static bool try_to_block_task(struct rq *rq, struct task_struct *p,
  5567. unsigned long task_state)
  5568. {
  5569. int flags = DEQUEUE_NOCLOCK;
  5570. if (signal_pending_state(task_state, p)) {
  5571. WRITE_ONCE(p->__state, TASK_RUNNING);
  5572. return false;
  5573. }
  5574. p->sched_contributes_to_load =
  5575. (task_state & TASK_UNINTERRUPTIBLE) &&
  5576. !(task_state & TASK_NOLOAD) &&
  5577. !(task_state & TASK_FROZEN);
  5578. if (unlikely(is_special_task_state(task_state)))
  5579. flags |= DEQUEUE_SPECIAL;
  5580. /*
  5581. * __schedule() ttwu()
  5582. * prev_state = prev->state; if (p->on_rq && ...)
  5583. * if (prev_state) goto out;
  5584. * p->on_rq = 0; smp_acquire__after_ctrl_dep();
  5585. * p->state = TASK_WAKING
  5586. *
  5587. * Where __schedule() and ttwu() have matching control dependencies.
  5588. *
  5589. * After this, schedule() must not care about p->state any more.
  5590. */
  5591. block_task(rq, p, flags);
  5592. return true;
  5593. }
  5594. /*
  5595. * __schedule() is the main scheduler function.
  5596. *
  5597. * The main means of driving the scheduler and thus entering this function are:
  5598. *
  5599. * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
  5600. *
  5601. * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
  5602. * paths. For example, see arch/x86/entry_64.S.
  5603. *
  5604. * To drive preemption between tasks, the scheduler sets the flag in timer
  5605. * interrupt handler sched_tick().
  5606. *
  5607. * 3. Wakeups don't really cause entry into schedule(). They add a
  5608. * task to the run-queue and that's it.
  5609. *
  5610. * Now, if the new task added to the run-queue preempts the current
  5611. * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
  5612. * called on the nearest possible occasion:
  5613. *
  5614. * - If the kernel is preemptible (CONFIG_PREEMPTION=y):
  5615. *
  5616. * - in syscall or exception context, at the next outmost
  5617. * preempt_enable(). (this might be as soon as the wake_up()'s
  5618. * spin_unlock()!)
  5619. *
  5620. * - in IRQ context, return from interrupt-handler to
  5621. * preemptible context
  5622. *
  5623. * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
  5624. * then at the next:
  5625. *
  5626. * - cond_resched() call
  5627. * - explicit schedule() call
  5628. * - return from syscall or exception to user-space
  5629. * - return from interrupt-handler to user-space
  5630. *
  5631. * WARNING: must be called with preemption disabled!
  5632. */
  5633. static void __sched notrace __schedule(int sched_mode)
  5634. {
  5635. struct task_struct *prev, *next;
  5636. /*
  5637. * On PREEMPT_RT kernel, SM_RTLOCK_WAIT is noted
  5638. * as a preemption by schedule_debug() and RCU.
  5639. */
  5640. bool preempt = sched_mode > SM_NONE;
  5641. unsigned long *switch_count;
  5642. unsigned long prev_state;
  5643. struct rq_flags rf;
  5644. struct rq *rq;
  5645. int cpu;
  5646. cpu = smp_processor_id();
  5647. rq = cpu_rq(cpu);
  5648. prev = rq->curr;
  5649. schedule_debug(prev, preempt);
  5650. if (sched_feat(HRTICK) || sched_feat(HRTICK_DL))
  5651. hrtick_clear(rq);
  5652. local_irq_disable();
  5653. rcu_note_context_switch(preempt);
  5654. /*
  5655. * Make sure that signal_pending_state()->signal_pending() below
  5656. * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
  5657. * done by the caller to avoid the race with signal_wake_up():
  5658. *
  5659. * __set_current_state(@state) signal_wake_up()
  5660. * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING)
  5661. * wake_up_state(p, state)
  5662. * LOCK rq->lock LOCK p->pi_state
  5663. * smp_mb__after_spinlock() smp_mb__after_spinlock()
  5664. * if (signal_pending_state()) if (p->state & @state)
  5665. *
  5666. * Also, the membarrier system call requires a full memory barrier
  5667. * after coming from user-space, before storing to rq->curr; this
  5668. * barrier matches a full barrier in the proximity of the membarrier
  5669. * system call exit.
  5670. */
  5671. rq_lock(rq, &rf);
  5672. smp_mb__after_spinlock();
  5673. /* Promote REQ to ACT */
  5674. rq->clock_update_flags <<= 1;
  5675. update_rq_clock(rq);
  5676. rq->clock_update_flags = RQCF_UPDATED;
  5677. switch_count = &prev->nivcsw;
  5678. /* Task state changes only considers SM_PREEMPT as preemption */
  5679. preempt = sched_mode == SM_PREEMPT;
  5680. /*
  5681. * We must load prev->state once (task_struct::state is volatile), such
  5682. * that we form a control dependency vs deactivate_task() below.
  5683. */
  5684. prev_state = READ_ONCE(prev->__state);
  5685. if (sched_mode == SM_IDLE) {
  5686. /* SCX must consult the BPF scheduler to tell if rq is empty */
  5687. if (!rq->nr_running && !scx_enabled()) {
  5688. next = prev;
  5689. goto picked;
  5690. }
  5691. } else if (!preempt && prev_state) {
  5692. try_to_block_task(rq, prev, prev_state);
  5693. switch_count = &prev->nvcsw;
  5694. }
  5695. next = pick_next_task(rq, prev, &rf);
  5696. picked:
  5697. clear_tsk_need_resched(prev);
  5698. clear_preempt_need_resched();
  5699. #ifdef CONFIG_SCHED_DEBUG
  5700. rq->last_seen_need_resched_ns = 0;
  5701. #endif
  5702. if (likely(prev != next)) {
  5703. rq->nr_switches++;
  5704. /*
  5705. * RCU users of rcu_dereference(rq->curr) may not see
  5706. * changes to task_struct made by pick_next_task().
  5707. */
  5708. RCU_INIT_POINTER(rq->curr, next);
  5709. /*
  5710. * The membarrier system call requires each architecture
  5711. * to have a full memory barrier after updating
  5712. * rq->curr, before returning to user-space.
  5713. *
  5714. * Here are the schemes providing that barrier on the
  5715. * various architectures:
  5716. * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC,
  5717. * RISC-V. switch_mm() relies on membarrier_arch_switch_mm()
  5718. * on PowerPC and on RISC-V.
  5719. * - finish_lock_switch() for weakly-ordered
  5720. * architectures where spin_unlock is a full barrier,
  5721. * - switch_to() for arm64 (weakly-ordered, spin_unlock
  5722. * is a RELEASE barrier),
  5723. *
  5724. * The barrier matches a full barrier in the proximity of
  5725. * the membarrier system call entry.
  5726. *
  5727. * On RISC-V, this barrier pairing is also needed for the
  5728. * SYNC_CORE command when switching between processes, cf.
  5729. * the inline comments in membarrier_arch_switch_mm().
  5730. */
  5731. ++*switch_count;
  5732. migrate_disable_switch(rq, prev);
  5733. psi_account_irqtime(rq, prev, next);
  5734. psi_sched_switch(prev, next, !task_on_rq_queued(prev) ||
  5735. prev->se.sched_delayed);
  5736. trace_sched_switch(preempt, prev, next, prev_state);
  5737. /* Also unlocks the rq: */
  5738. rq = context_switch(rq, prev, next, &rf);
  5739. } else {
  5740. rq_unpin_lock(rq, &rf);
  5741. __balance_callbacks(rq);
  5742. raw_spin_rq_unlock_irq(rq);
  5743. }
  5744. }
  5745. void __noreturn do_task_dead(void)
  5746. {
  5747. /* Causes final put_task_struct in finish_task_switch(): */
  5748. set_special_state(TASK_DEAD);
  5749. /* Tell freezer to ignore us: */
  5750. current->flags |= PF_NOFREEZE;
  5751. __schedule(SM_NONE);
  5752. BUG();
  5753. /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
  5754. for (;;)
  5755. cpu_relax();
  5756. }
  5757. static inline void sched_submit_work(struct task_struct *tsk)
  5758. {
  5759. static DEFINE_WAIT_OVERRIDE_MAP(sched_map, LD_WAIT_CONFIG);
  5760. unsigned int task_flags;
  5761. /*
  5762. * Establish LD_WAIT_CONFIG context to ensure none of the code called
  5763. * will use a blocking primitive -- which would lead to recursion.
  5764. */
  5765. lock_map_acquire_try(&sched_map);
  5766. task_flags = tsk->flags;
  5767. /*
  5768. * If a worker goes to sleep, notify and ask workqueue whether it
  5769. * wants to wake up a task to maintain concurrency.
  5770. */
  5771. if (task_flags & PF_WQ_WORKER)
  5772. wq_worker_sleeping(tsk);
  5773. else if (task_flags & PF_IO_WORKER)
  5774. io_wq_worker_sleeping(tsk);
  5775. /*
  5776. * spinlock and rwlock must not flush block requests. This will
  5777. * deadlock if the callback attempts to acquire a lock which is
  5778. * already acquired.
  5779. */
  5780. SCHED_WARN_ON(current->__state & TASK_RTLOCK_WAIT);
  5781. /*
  5782. * If we are going to sleep and we have plugged IO queued,
  5783. * make sure to submit it to avoid deadlocks.
  5784. */
  5785. blk_flush_plug(tsk->plug, true);
  5786. lock_map_release(&sched_map);
  5787. }
  5788. static void sched_update_worker(struct task_struct *tsk)
  5789. {
  5790. if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER | PF_BLOCK_TS)) {
  5791. if (tsk->flags & PF_BLOCK_TS)
  5792. blk_plug_invalidate_ts(tsk);
  5793. if (tsk->flags & PF_WQ_WORKER)
  5794. wq_worker_running(tsk);
  5795. else if (tsk->flags & PF_IO_WORKER)
  5796. io_wq_worker_running(tsk);
  5797. }
  5798. }
  5799. static __always_inline void __schedule_loop(int sched_mode)
  5800. {
  5801. do {
  5802. preempt_disable();
  5803. __schedule(sched_mode);
  5804. sched_preempt_enable_no_resched();
  5805. } while (need_resched());
  5806. }
  5807. asmlinkage __visible void __sched schedule(void)
  5808. {
  5809. struct task_struct *tsk = current;
  5810. #ifdef CONFIG_RT_MUTEXES
  5811. lockdep_assert(!tsk->sched_rt_mutex);
  5812. #endif
  5813. if (!task_is_running(tsk))
  5814. sched_submit_work(tsk);
  5815. __schedule_loop(SM_NONE);
  5816. sched_update_worker(tsk);
  5817. }
  5818. EXPORT_SYMBOL(schedule);
  5819. /*
  5820. * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
  5821. * state (have scheduled out non-voluntarily) by making sure that all
  5822. * tasks have either left the run queue or have gone into user space.
  5823. * As idle tasks do not do either, they must not ever be preempted
  5824. * (schedule out non-voluntarily).
  5825. *
  5826. * schedule_idle() is similar to schedule_preempt_disable() except that it
  5827. * never enables preemption because it does not call sched_submit_work().
  5828. */
  5829. void __sched schedule_idle(void)
  5830. {
  5831. /*
  5832. * As this skips calling sched_submit_work(), which the idle task does
  5833. * regardless because that function is a NOP when the task is in a
  5834. * TASK_RUNNING state, make sure this isn't used someplace that the
  5835. * current task can be in any other state. Note, idle is always in the
  5836. * TASK_RUNNING state.
  5837. */
  5838. WARN_ON_ONCE(current->__state);
  5839. do {
  5840. __schedule(SM_IDLE);
  5841. } while (need_resched());
  5842. }
  5843. #if defined(CONFIG_CONTEXT_TRACKING_USER) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK)
  5844. asmlinkage __visible void __sched schedule_user(void)
  5845. {
  5846. /*
  5847. * If we come here after a random call to set_need_resched(),
  5848. * or we have been woken up remotely but the IPI has not yet arrived,
  5849. * we haven't yet exited the RCU idle mode. Do it here manually until
  5850. * we find a better solution.
  5851. *
  5852. * NB: There are buggy callers of this function. Ideally we
  5853. * should warn if prev_state != CT_STATE_USER, but that will trigger
  5854. * too frequently to make sense yet.
  5855. */
  5856. enum ctx_state prev_state = exception_enter();
  5857. schedule();
  5858. exception_exit(prev_state);
  5859. }
  5860. #endif
  5861. /**
  5862. * schedule_preempt_disabled - called with preemption disabled
  5863. *
  5864. * Returns with preemption disabled. Note: preempt_count must be 1
  5865. */
  5866. void __sched schedule_preempt_disabled(void)
  5867. {
  5868. sched_preempt_enable_no_resched();
  5869. schedule();
  5870. preempt_disable();
  5871. }
  5872. #ifdef CONFIG_PREEMPT_RT
  5873. void __sched notrace schedule_rtlock(void)
  5874. {
  5875. __schedule_loop(SM_RTLOCK_WAIT);
  5876. }
  5877. NOKPROBE_SYMBOL(schedule_rtlock);
  5878. #endif
  5879. static void __sched notrace preempt_schedule_common(void)
  5880. {
  5881. do {
  5882. /*
  5883. * Because the function tracer can trace preempt_count_sub()
  5884. * and it also uses preempt_enable/disable_notrace(), if
  5885. * NEED_RESCHED is set, the preempt_enable_notrace() called
  5886. * by the function tracer will call this function again and
  5887. * cause infinite recursion.
  5888. *
  5889. * Preemption must be disabled here before the function
  5890. * tracer can trace. Break up preempt_disable() into two
  5891. * calls. One to disable preemption without fear of being
  5892. * traced. The other to still record the preemption latency,
  5893. * which can also be traced by the function tracer.
  5894. */
  5895. preempt_disable_notrace();
  5896. preempt_latency_start(1);
  5897. __schedule(SM_PREEMPT);
  5898. preempt_latency_stop(1);
  5899. preempt_enable_no_resched_notrace();
  5900. /*
  5901. * Check again in case we missed a preemption opportunity
  5902. * between schedule and now.
  5903. */
  5904. } while (need_resched());
  5905. }
  5906. #ifdef CONFIG_PREEMPTION
  5907. /*
  5908. * This is the entry point to schedule() from in-kernel preemption
  5909. * off of preempt_enable.
  5910. */
  5911. asmlinkage __visible void __sched notrace preempt_schedule(void)
  5912. {
  5913. /*
  5914. * If there is a non-zero preempt_count or interrupts are disabled,
  5915. * we do not want to preempt the current task. Just return..
  5916. */
  5917. if (likely(!preemptible()))
  5918. return;
  5919. preempt_schedule_common();
  5920. }
  5921. NOKPROBE_SYMBOL(preempt_schedule);
  5922. EXPORT_SYMBOL(preempt_schedule);
  5923. #ifdef CONFIG_PREEMPT_DYNAMIC
  5924. #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
  5925. #ifndef preempt_schedule_dynamic_enabled
  5926. #define preempt_schedule_dynamic_enabled preempt_schedule
  5927. #define preempt_schedule_dynamic_disabled NULL
  5928. #endif
  5929. DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled);
  5930. EXPORT_STATIC_CALL_TRAMP(preempt_schedule);
  5931. #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
  5932. static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule);
  5933. void __sched notrace dynamic_preempt_schedule(void)
  5934. {
  5935. if (!static_branch_unlikely(&sk_dynamic_preempt_schedule))
  5936. return;
  5937. preempt_schedule();
  5938. }
  5939. NOKPROBE_SYMBOL(dynamic_preempt_schedule);
  5940. EXPORT_SYMBOL(dynamic_preempt_schedule);
  5941. #endif
  5942. #endif
  5943. /**
  5944. * preempt_schedule_notrace - preempt_schedule called by tracing
  5945. *
  5946. * The tracing infrastructure uses preempt_enable_notrace to prevent
  5947. * recursion and tracing preempt enabling caused by the tracing
  5948. * infrastructure itself. But as tracing can happen in areas coming
  5949. * from userspace or just about to enter userspace, a preempt enable
  5950. * can occur before user_exit() is called. This will cause the scheduler
  5951. * to be called when the system is still in usermode.
  5952. *
  5953. * To prevent this, the preempt_enable_notrace will use this function
  5954. * instead of preempt_schedule() to exit user context if needed before
  5955. * calling the scheduler.
  5956. */
  5957. asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
  5958. {
  5959. enum ctx_state prev_ctx;
  5960. if (likely(!preemptible()))
  5961. return;
  5962. do {
  5963. /*
  5964. * Because the function tracer can trace preempt_count_sub()
  5965. * and it also uses preempt_enable/disable_notrace(), if
  5966. * NEED_RESCHED is set, the preempt_enable_notrace() called
  5967. * by the function tracer will call this function again and
  5968. * cause infinite recursion.
  5969. *
  5970. * Preemption must be disabled here before the function
  5971. * tracer can trace. Break up preempt_disable() into two
  5972. * calls. One to disable preemption without fear of being
  5973. * traced. The other to still record the preemption latency,
  5974. * which can also be traced by the function tracer.
  5975. */
  5976. preempt_disable_notrace();
  5977. preempt_latency_start(1);
  5978. /*
  5979. * Needs preempt disabled in case user_exit() is traced
  5980. * and the tracer calls preempt_enable_notrace() causing
  5981. * an infinite recursion.
  5982. */
  5983. prev_ctx = exception_enter();
  5984. __schedule(SM_PREEMPT);
  5985. exception_exit(prev_ctx);
  5986. preempt_latency_stop(1);
  5987. preempt_enable_no_resched_notrace();
  5988. } while (need_resched());
  5989. }
  5990. EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
  5991. #ifdef CONFIG_PREEMPT_DYNAMIC
  5992. #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
  5993. #ifndef preempt_schedule_notrace_dynamic_enabled
  5994. #define preempt_schedule_notrace_dynamic_enabled preempt_schedule_notrace
  5995. #define preempt_schedule_notrace_dynamic_disabled NULL
  5996. #endif
  5997. DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled);
  5998. EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace);
  5999. #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
  6000. static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace);
  6001. void __sched notrace dynamic_preempt_schedule_notrace(void)
  6002. {
  6003. if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace))
  6004. return;
  6005. preempt_schedule_notrace();
  6006. }
  6007. NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace);
  6008. EXPORT_SYMBOL(dynamic_preempt_schedule_notrace);
  6009. #endif
  6010. #endif
  6011. #endif /* CONFIG_PREEMPTION */
  6012. /*
  6013. * This is the entry point to schedule() from kernel preemption
  6014. * off of IRQ context.
  6015. * Note, that this is called and return with IRQs disabled. This will
  6016. * protect us against recursive calling from IRQ contexts.
  6017. */
  6018. asmlinkage __visible void __sched preempt_schedule_irq(void)
  6019. {
  6020. enum ctx_state prev_state;
  6021. /* Catch callers which need to be fixed */
  6022. BUG_ON(preempt_count() || !irqs_disabled());
  6023. prev_state = exception_enter();
  6024. do {
  6025. preempt_disable();
  6026. local_irq_enable();
  6027. __schedule(SM_PREEMPT);
  6028. local_irq_disable();
  6029. sched_preempt_enable_no_resched();
  6030. } while (need_resched());
  6031. exception_exit(prev_state);
  6032. }
  6033. int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
  6034. void *key)
  6035. {
  6036. WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG) && wake_flags & ~(WF_SYNC|WF_CURRENT_CPU));
  6037. return try_to_wake_up(curr->private, mode, wake_flags);
  6038. }
  6039. EXPORT_SYMBOL(default_wake_function);
  6040. const struct sched_class *__setscheduler_class(int policy, int prio)
  6041. {
  6042. if (dl_prio(prio))
  6043. return &dl_sched_class;
  6044. if (rt_prio(prio))
  6045. return &rt_sched_class;
  6046. #ifdef CONFIG_SCHED_CLASS_EXT
  6047. if (task_should_scx(policy))
  6048. return &ext_sched_class;
  6049. #endif
  6050. return &fair_sched_class;
  6051. }
  6052. #ifdef CONFIG_RT_MUTEXES
  6053. /*
  6054. * Would be more useful with typeof()/auto_type but they don't mix with
  6055. * bit-fields. Since it's a local thing, use int. Keep the generic sounding
  6056. * name such that if someone were to implement this function we get to compare
  6057. * notes.
  6058. */
  6059. #define fetch_and_set(x, v) ({ int _x = (x); (x) = (v); _x; })
  6060. void rt_mutex_pre_schedule(void)
  6061. {
  6062. lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1));
  6063. sched_submit_work(current);
  6064. }
  6065. void rt_mutex_schedule(void)
  6066. {
  6067. lockdep_assert(current->sched_rt_mutex);
  6068. __schedule_loop(SM_NONE);
  6069. }
  6070. void rt_mutex_post_schedule(void)
  6071. {
  6072. sched_update_worker(current);
  6073. lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0));
  6074. }
  6075. /*
  6076. * rt_mutex_setprio - set the current priority of a task
  6077. * @p: task to boost
  6078. * @pi_task: donor task
  6079. *
  6080. * This function changes the 'effective' priority of a task. It does
  6081. * not touch ->normal_prio like __setscheduler().
  6082. *
  6083. * Used by the rt_mutex code to implement priority inheritance
  6084. * logic. Call site only calls if the priority of the task changed.
  6085. */
  6086. void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
  6087. {
  6088. int prio, oldprio, queued, running, queue_flag =
  6089. DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  6090. const struct sched_class *prev_class, *next_class;
  6091. struct rq_flags rf;
  6092. struct rq *rq;
  6093. /* XXX used to be waiter->prio, not waiter->task->prio */
  6094. prio = __rt_effective_prio(pi_task, p->normal_prio);
  6095. /*
  6096. * If nothing changed; bail early.
  6097. */
  6098. if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
  6099. return;
  6100. rq = __task_rq_lock(p, &rf);
  6101. update_rq_clock(rq);
  6102. /*
  6103. * Set under pi_lock && rq->lock, such that the value can be used under
  6104. * either lock.
  6105. *
  6106. * Note that there is loads of tricky to make this pointer cache work
  6107. * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
  6108. * ensure a task is de-boosted (pi_task is set to NULL) before the
  6109. * task is allowed to run again (and can exit). This ensures the pointer
  6110. * points to a blocked task -- which guarantees the task is present.
  6111. */
  6112. p->pi_top_task = pi_task;
  6113. /*
  6114. * For FIFO/RR we only need to set prio, if that matches we're done.
  6115. */
  6116. if (prio == p->prio && !dl_prio(prio))
  6117. goto out_unlock;
  6118. /*
  6119. * Idle task boosting is a no-no in general. There is one
  6120. * exception, when PREEMPT_RT and NOHZ is active:
  6121. *
  6122. * The idle task calls get_next_timer_interrupt() and holds
  6123. * the timer wheel base->lock on the CPU and another CPU wants
  6124. * to access the timer (probably to cancel it). We can safely
  6125. * ignore the boosting request, as the idle CPU runs this code
  6126. * with interrupts disabled and will complete the lock
  6127. * protected section without being interrupted. So there is no
  6128. * real need to boost.
  6129. */
  6130. if (unlikely(p == rq->idle)) {
  6131. WARN_ON(p != rq->curr);
  6132. WARN_ON(p->pi_blocked_on);
  6133. goto out_unlock;
  6134. }
  6135. trace_sched_pi_setprio(p, pi_task);
  6136. oldprio = p->prio;
  6137. if (oldprio == prio)
  6138. queue_flag &= ~DEQUEUE_MOVE;
  6139. prev_class = p->sched_class;
  6140. next_class = __setscheduler_class(p->policy, prio);
  6141. if (prev_class != next_class && p->se.sched_delayed)
  6142. dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK);
  6143. queued = task_on_rq_queued(p);
  6144. running = task_current(rq, p);
  6145. if (queued)
  6146. dequeue_task(rq, p, queue_flag);
  6147. if (running)
  6148. put_prev_task(rq, p);
  6149. /*
  6150. * Boosting condition are:
  6151. * 1. -rt task is running and holds mutex A
  6152. * --> -dl task blocks on mutex A
  6153. *
  6154. * 2. -dl task is running and holds mutex A
  6155. * --> -dl task blocks on mutex A and could preempt the
  6156. * running task
  6157. */
  6158. if (dl_prio(prio)) {
  6159. if (!dl_prio(p->normal_prio) ||
  6160. (pi_task && dl_prio(pi_task->prio) &&
  6161. dl_entity_preempt(&pi_task->dl, &p->dl))) {
  6162. p->dl.pi_se = pi_task->dl.pi_se;
  6163. queue_flag |= ENQUEUE_REPLENISH;
  6164. } else {
  6165. p->dl.pi_se = &p->dl;
  6166. }
  6167. } else if (rt_prio(prio)) {
  6168. if (dl_prio(oldprio))
  6169. p->dl.pi_se = &p->dl;
  6170. if (oldprio < prio)
  6171. queue_flag |= ENQUEUE_HEAD;
  6172. } else {
  6173. if (dl_prio(oldprio))
  6174. p->dl.pi_se = &p->dl;
  6175. if (rt_prio(oldprio))
  6176. p->rt.timeout = 0;
  6177. }
  6178. p->sched_class = next_class;
  6179. p->prio = prio;
  6180. check_class_changing(rq, p, prev_class);
  6181. if (queued)
  6182. enqueue_task(rq, p, queue_flag);
  6183. if (running)
  6184. set_next_task(rq, p);
  6185. check_class_changed(rq, p, prev_class, oldprio);
  6186. out_unlock:
  6187. /* Avoid rq from going away on us: */
  6188. preempt_disable();
  6189. rq_unpin_lock(rq, &rf);
  6190. __balance_callbacks(rq);
  6191. raw_spin_rq_unlock(rq);
  6192. preempt_enable();
  6193. }
  6194. #endif
  6195. #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC)
  6196. int __sched __cond_resched(void)
  6197. {
  6198. if (should_resched(0)) {
  6199. preempt_schedule_common();
  6200. return 1;
  6201. }
  6202. /*
  6203. * In preemptible kernels, ->rcu_read_lock_nesting tells the tick
  6204. * whether the current CPU is in an RCU read-side critical section,
  6205. * so the tick can report quiescent states even for CPUs looping
  6206. * in kernel context. In contrast, in non-preemptible kernels,
  6207. * RCU readers leave no in-memory hints, which means that CPU-bound
  6208. * processes executing in kernel context might never report an
  6209. * RCU quiescent state. Therefore, the following code causes
  6210. * cond_resched() to report a quiescent state, but only when RCU
  6211. * is in urgent need of one.
  6212. */
  6213. #ifndef CONFIG_PREEMPT_RCU
  6214. rcu_all_qs();
  6215. #endif
  6216. return 0;
  6217. }
  6218. EXPORT_SYMBOL(__cond_resched);
  6219. #endif
  6220. #ifdef CONFIG_PREEMPT_DYNAMIC
  6221. #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
  6222. #define cond_resched_dynamic_enabled __cond_resched
  6223. #define cond_resched_dynamic_disabled ((void *)&__static_call_return0)
  6224. DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched);
  6225. EXPORT_STATIC_CALL_TRAMP(cond_resched);
  6226. #define might_resched_dynamic_enabled __cond_resched
  6227. #define might_resched_dynamic_disabled ((void *)&__static_call_return0)
  6228. DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched);
  6229. EXPORT_STATIC_CALL_TRAMP(might_resched);
  6230. #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
  6231. static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched);
  6232. int __sched dynamic_cond_resched(void)
  6233. {
  6234. klp_sched_try_switch();
  6235. if (!static_branch_unlikely(&sk_dynamic_cond_resched))
  6236. return 0;
  6237. return __cond_resched();
  6238. }
  6239. EXPORT_SYMBOL(dynamic_cond_resched);
  6240. static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched);
  6241. int __sched dynamic_might_resched(void)
  6242. {
  6243. if (!static_branch_unlikely(&sk_dynamic_might_resched))
  6244. return 0;
  6245. return __cond_resched();
  6246. }
  6247. EXPORT_SYMBOL(dynamic_might_resched);
  6248. #endif
  6249. #endif
  6250. /*
  6251. * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
  6252. * call schedule, and on return reacquire the lock.
  6253. *
  6254. * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
  6255. * operations here to prevent schedule() from being called twice (once via
  6256. * spin_unlock(), once by hand).
  6257. */
  6258. int __cond_resched_lock(spinlock_t *lock)
  6259. {
  6260. int resched = should_resched(PREEMPT_LOCK_OFFSET);
  6261. int ret = 0;
  6262. lockdep_assert_held(lock);
  6263. if (spin_needbreak(lock) || resched) {
  6264. spin_unlock(lock);
  6265. if (!_cond_resched())
  6266. cpu_relax();
  6267. ret = 1;
  6268. spin_lock(lock);
  6269. }
  6270. return ret;
  6271. }
  6272. EXPORT_SYMBOL(__cond_resched_lock);
  6273. int __cond_resched_rwlock_read(rwlock_t *lock)
  6274. {
  6275. int resched = should_resched(PREEMPT_LOCK_OFFSET);
  6276. int ret = 0;
  6277. lockdep_assert_held_read(lock);
  6278. if (rwlock_needbreak(lock) || resched) {
  6279. read_unlock(lock);
  6280. if (!_cond_resched())
  6281. cpu_relax();
  6282. ret = 1;
  6283. read_lock(lock);
  6284. }
  6285. return ret;
  6286. }
  6287. EXPORT_SYMBOL(__cond_resched_rwlock_read);
  6288. int __cond_resched_rwlock_write(rwlock_t *lock)
  6289. {
  6290. int resched = should_resched(PREEMPT_LOCK_OFFSET);
  6291. int ret = 0;
  6292. lockdep_assert_held_write(lock);
  6293. if (rwlock_needbreak(lock) || resched) {
  6294. write_unlock(lock);
  6295. if (!_cond_resched())
  6296. cpu_relax();
  6297. ret = 1;
  6298. write_lock(lock);
  6299. }
  6300. return ret;
  6301. }
  6302. EXPORT_SYMBOL(__cond_resched_rwlock_write);
  6303. #ifdef CONFIG_PREEMPT_DYNAMIC
  6304. #ifdef CONFIG_GENERIC_ENTRY
  6305. #include <linux/entry-common.h>
  6306. #endif
  6307. /*
  6308. * SC:cond_resched
  6309. * SC:might_resched
  6310. * SC:preempt_schedule
  6311. * SC:preempt_schedule_notrace
  6312. * SC:irqentry_exit_cond_resched
  6313. *
  6314. *
  6315. * NONE:
  6316. * cond_resched <- __cond_resched
  6317. * might_resched <- RET0
  6318. * preempt_schedule <- NOP
  6319. * preempt_schedule_notrace <- NOP
  6320. * irqentry_exit_cond_resched <- NOP
  6321. *
  6322. * VOLUNTARY:
  6323. * cond_resched <- __cond_resched
  6324. * might_resched <- __cond_resched
  6325. * preempt_schedule <- NOP
  6326. * preempt_schedule_notrace <- NOP
  6327. * irqentry_exit_cond_resched <- NOP
  6328. *
  6329. * FULL:
  6330. * cond_resched <- RET0
  6331. * might_resched <- RET0
  6332. * preempt_schedule <- preempt_schedule
  6333. * preempt_schedule_notrace <- preempt_schedule_notrace
  6334. * irqentry_exit_cond_resched <- irqentry_exit_cond_resched
  6335. */
  6336. enum {
  6337. preempt_dynamic_undefined = -1,
  6338. preempt_dynamic_none,
  6339. preempt_dynamic_voluntary,
  6340. preempt_dynamic_full,
  6341. };
  6342. int preempt_dynamic_mode = preempt_dynamic_undefined;
  6343. int sched_dynamic_mode(const char *str)
  6344. {
  6345. if (!strcmp(str, "none"))
  6346. return preempt_dynamic_none;
  6347. if (!strcmp(str, "voluntary"))
  6348. return preempt_dynamic_voluntary;
  6349. if (!strcmp(str, "full"))
  6350. return preempt_dynamic_full;
  6351. return -EINVAL;
  6352. }
  6353. #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
  6354. #define preempt_dynamic_enable(f) static_call_update(f, f##_dynamic_enabled)
  6355. #define preempt_dynamic_disable(f) static_call_update(f, f##_dynamic_disabled)
  6356. #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
  6357. #define preempt_dynamic_enable(f) static_key_enable(&sk_dynamic_##f.key)
  6358. #define preempt_dynamic_disable(f) static_key_disable(&sk_dynamic_##f.key)
  6359. #else
  6360. #error "Unsupported PREEMPT_DYNAMIC mechanism"
  6361. #endif
  6362. static DEFINE_MUTEX(sched_dynamic_mutex);
  6363. static bool klp_override;
  6364. static void __sched_dynamic_update(int mode)
  6365. {
  6366. /*
  6367. * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in
  6368. * the ZERO state, which is invalid.
  6369. */
  6370. if (!klp_override)
  6371. preempt_dynamic_enable(cond_resched);
  6372. preempt_dynamic_enable(might_resched);
  6373. preempt_dynamic_enable(preempt_schedule);
  6374. preempt_dynamic_enable(preempt_schedule_notrace);
  6375. preempt_dynamic_enable(irqentry_exit_cond_resched);
  6376. switch (mode) {
  6377. case preempt_dynamic_none:
  6378. if (!klp_override)
  6379. preempt_dynamic_enable(cond_resched);
  6380. preempt_dynamic_disable(might_resched);
  6381. preempt_dynamic_disable(preempt_schedule);
  6382. preempt_dynamic_disable(preempt_schedule_notrace);
  6383. preempt_dynamic_disable(irqentry_exit_cond_resched);
  6384. if (mode != preempt_dynamic_mode)
  6385. pr_info("Dynamic Preempt: none\n");
  6386. break;
  6387. case preempt_dynamic_voluntary:
  6388. if (!klp_override)
  6389. preempt_dynamic_enable(cond_resched);
  6390. preempt_dynamic_enable(might_resched);
  6391. preempt_dynamic_disable(preempt_schedule);
  6392. preempt_dynamic_disable(preempt_schedule_notrace);
  6393. preempt_dynamic_disable(irqentry_exit_cond_resched);
  6394. if (mode != preempt_dynamic_mode)
  6395. pr_info("Dynamic Preempt: voluntary\n");
  6396. break;
  6397. case preempt_dynamic_full:
  6398. if (!klp_override)
  6399. preempt_dynamic_disable(cond_resched);
  6400. preempt_dynamic_disable(might_resched);
  6401. preempt_dynamic_enable(preempt_schedule);
  6402. preempt_dynamic_enable(preempt_schedule_notrace);
  6403. preempt_dynamic_enable(irqentry_exit_cond_resched);
  6404. if (mode != preempt_dynamic_mode)
  6405. pr_info("Dynamic Preempt: full\n");
  6406. break;
  6407. }
  6408. preempt_dynamic_mode = mode;
  6409. }
  6410. void sched_dynamic_update(int mode)
  6411. {
  6412. mutex_lock(&sched_dynamic_mutex);
  6413. __sched_dynamic_update(mode);
  6414. mutex_unlock(&sched_dynamic_mutex);
  6415. }
  6416. #ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL
  6417. static int klp_cond_resched(void)
  6418. {
  6419. __klp_sched_try_switch();
  6420. return __cond_resched();
  6421. }
  6422. void sched_dynamic_klp_enable(void)
  6423. {
  6424. mutex_lock(&sched_dynamic_mutex);
  6425. klp_override = true;
  6426. static_call_update(cond_resched, klp_cond_resched);
  6427. mutex_unlock(&sched_dynamic_mutex);
  6428. }
  6429. void sched_dynamic_klp_disable(void)
  6430. {
  6431. mutex_lock(&sched_dynamic_mutex);
  6432. klp_override = false;
  6433. __sched_dynamic_update(preempt_dynamic_mode);
  6434. mutex_unlock(&sched_dynamic_mutex);
  6435. }
  6436. #endif /* CONFIG_HAVE_PREEMPT_DYNAMIC_CALL */
  6437. static int __init setup_preempt_mode(char *str)
  6438. {
  6439. int mode = sched_dynamic_mode(str);
  6440. if (mode < 0) {
  6441. pr_warn("Dynamic Preempt: unsupported mode: %s\n", str);
  6442. return 0;
  6443. }
  6444. sched_dynamic_update(mode);
  6445. return 1;
  6446. }
  6447. __setup("preempt=", setup_preempt_mode);
  6448. static void __init preempt_dynamic_init(void)
  6449. {
  6450. if (preempt_dynamic_mode == preempt_dynamic_undefined) {
  6451. if (IS_ENABLED(CONFIG_PREEMPT_NONE)) {
  6452. sched_dynamic_update(preempt_dynamic_none);
  6453. } else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) {
  6454. sched_dynamic_update(preempt_dynamic_voluntary);
  6455. } else {
  6456. /* Default static call setting, nothing to do */
  6457. WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT));
  6458. preempt_dynamic_mode = preempt_dynamic_full;
  6459. pr_info("Dynamic Preempt: full\n");
  6460. }
  6461. }
  6462. }
  6463. #define PREEMPT_MODEL_ACCESSOR(mode) \
  6464. bool preempt_model_##mode(void) \
  6465. { \
  6466. WARN_ON_ONCE(preempt_dynamic_mode == preempt_dynamic_undefined); \
  6467. return preempt_dynamic_mode == preempt_dynamic_##mode; \
  6468. } \
  6469. EXPORT_SYMBOL_GPL(preempt_model_##mode)
  6470. PREEMPT_MODEL_ACCESSOR(none);
  6471. PREEMPT_MODEL_ACCESSOR(voluntary);
  6472. PREEMPT_MODEL_ACCESSOR(full);
  6473. #else /* !CONFIG_PREEMPT_DYNAMIC: */
  6474. static inline void preempt_dynamic_init(void) { }
  6475. #endif /* CONFIG_PREEMPT_DYNAMIC */
  6476. int io_schedule_prepare(void)
  6477. {
  6478. int old_iowait = current->in_iowait;
  6479. current->in_iowait = 1;
  6480. blk_flush_plug(current->plug, true);
  6481. return old_iowait;
  6482. }
  6483. void io_schedule_finish(int token)
  6484. {
  6485. current->in_iowait = token;
  6486. }
  6487. /*
  6488. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  6489. * that process accounting knows that this is a task in IO wait state.
  6490. */
  6491. long __sched io_schedule_timeout(long timeout)
  6492. {
  6493. int token;
  6494. long ret;
  6495. token = io_schedule_prepare();
  6496. ret = schedule_timeout(timeout);
  6497. io_schedule_finish(token);
  6498. return ret;
  6499. }
  6500. EXPORT_SYMBOL(io_schedule_timeout);
  6501. void __sched io_schedule(void)
  6502. {
  6503. int token;
  6504. token = io_schedule_prepare();
  6505. schedule();
  6506. io_schedule_finish(token);
  6507. }
  6508. EXPORT_SYMBOL(io_schedule);
  6509. void sched_show_task(struct task_struct *p)
  6510. {
  6511. unsigned long free;
  6512. int ppid;
  6513. if (!try_get_task_stack(p))
  6514. return;
  6515. pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p));
  6516. if (task_is_running(p))
  6517. pr_cont(" running task ");
  6518. free = stack_not_used(p);
  6519. ppid = 0;
  6520. rcu_read_lock();
  6521. if (pid_alive(p))
  6522. ppid = task_pid_nr(rcu_dereference(p->real_parent));
  6523. rcu_read_unlock();
  6524. pr_cont(" stack:%-5lu pid:%-5d tgid:%-5d ppid:%-6d flags:0x%08lx\n",
  6525. free, task_pid_nr(p), task_tgid_nr(p),
  6526. ppid, read_task_thread_flags(p));
  6527. print_worker_info(KERN_INFO, p);
  6528. print_stop_info(KERN_INFO, p);
  6529. print_scx_info(KERN_INFO, p);
  6530. show_stack(p, NULL, KERN_INFO);
  6531. put_task_stack(p);
  6532. }
  6533. EXPORT_SYMBOL_GPL(sched_show_task);
  6534. static inline bool
  6535. state_filter_match(unsigned long state_filter, struct task_struct *p)
  6536. {
  6537. unsigned int state = READ_ONCE(p->__state);
  6538. /* no filter, everything matches */
  6539. if (!state_filter)
  6540. return true;
  6541. /* filter, but doesn't match */
  6542. if (!(state & state_filter))
  6543. return false;
  6544. /*
  6545. * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
  6546. * TASK_KILLABLE).
  6547. */
  6548. if (state_filter == TASK_UNINTERRUPTIBLE && (state & TASK_NOLOAD))
  6549. return false;
  6550. return true;
  6551. }
  6552. void show_state_filter(unsigned int state_filter)
  6553. {
  6554. struct task_struct *g, *p;
  6555. rcu_read_lock();
  6556. for_each_process_thread(g, p) {
  6557. /*
  6558. * reset the NMI-timeout, listing all files on a slow
  6559. * console might take a lot of time:
  6560. * Also, reset softlockup watchdogs on all CPUs, because
  6561. * another CPU might be blocked waiting for us to process
  6562. * an IPI.
  6563. */
  6564. touch_nmi_watchdog();
  6565. touch_all_softlockup_watchdogs();
  6566. if (state_filter_match(state_filter, p))
  6567. sched_show_task(p);
  6568. }
  6569. #ifdef CONFIG_SCHED_DEBUG
  6570. if (!state_filter)
  6571. sysrq_sched_debug_show();
  6572. #endif
  6573. rcu_read_unlock();
  6574. /*
  6575. * Only show locks if all tasks are dumped:
  6576. */
  6577. if (!state_filter)
  6578. debug_show_all_locks();
  6579. }
  6580. /**
  6581. * init_idle - set up an idle thread for a given CPU
  6582. * @idle: task in question
  6583. * @cpu: CPU the idle task belongs to
  6584. *
  6585. * NOTE: this function does not set the idle thread's NEED_RESCHED
  6586. * flag, to make booting more robust.
  6587. */
  6588. void __init init_idle(struct task_struct *idle, int cpu)
  6589. {
  6590. #ifdef CONFIG_SMP
  6591. struct affinity_context ac = (struct affinity_context) {
  6592. .new_mask = cpumask_of(cpu),
  6593. .flags = 0,
  6594. };
  6595. #endif
  6596. struct rq *rq = cpu_rq(cpu);
  6597. unsigned long flags;
  6598. raw_spin_lock_irqsave(&idle->pi_lock, flags);
  6599. raw_spin_rq_lock(rq);
  6600. idle->__state = TASK_RUNNING;
  6601. idle->se.exec_start = sched_clock();
  6602. /*
  6603. * PF_KTHREAD should already be set at this point; regardless, make it
  6604. * look like a proper per-CPU kthread.
  6605. */
  6606. idle->flags |= PF_KTHREAD | PF_NO_SETAFFINITY;
  6607. kthread_set_per_cpu(idle, cpu);
  6608. #ifdef CONFIG_SMP
  6609. /*
  6610. * No validation and serialization required at boot time and for
  6611. * setting up the idle tasks of not yet online CPUs.
  6612. */
  6613. set_cpus_allowed_common(idle, &ac);
  6614. #endif
  6615. /*
  6616. * We're having a chicken and egg problem, even though we are
  6617. * holding rq->lock, the CPU isn't yet set to this CPU so the
  6618. * lockdep check in task_group() will fail.
  6619. *
  6620. * Similar case to sched_fork(). / Alternatively we could
  6621. * use task_rq_lock() here and obtain the other rq->lock.
  6622. *
  6623. * Silence PROVE_RCU
  6624. */
  6625. rcu_read_lock();
  6626. __set_task_cpu(idle, cpu);
  6627. rcu_read_unlock();
  6628. rq->idle = idle;
  6629. rcu_assign_pointer(rq->curr, idle);
  6630. idle->on_rq = TASK_ON_RQ_QUEUED;
  6631. #ifdef CONFIG_SMP
  6632. idle->on_cpu = 1;
  6633. #endif
  6634. raw_spin_rq_unlock(rq);
  6635. raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
  6636. /* Set the preempt count _outside_ the spinlocks! */
  6637. init_idle_preempt_count(idle, cpu);
  6638. /*
  6639. * The idle tasks have their own, simple scheduling class:
  6640. */
  6641. idle->sched_class = &idle_sched_class;
  6642. ftrace_graph_init_idle_task(idle, cpu);
  6643. vtime_init_idle(idle, cpu);
  6644. #ifdef CONFIG_SMP
  6645. sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
  6646. #endif
  6647. }
  6648. #ifdef CONFIG_SMP
  6649. int cpuset_cpumask_can_shrink(const struct cpumask *cur,
  6650. const struct cpumask *trial)
  6651. {
  6652. int ret = 1;
  6653. if (cpumask_empty(cur))
  6654. return ret;
  6655. ret = dl_cpuset_cpumask_can_shrink(cur, trial);
  6656. return ret;
  6657. }
  6658. int task_can_attach(struct task_struct *p)
  6659. {
  6660. int ret = 0;
  6661. /*
  6662. * Kthreads which disallow setaffinity shouldn't be moved
  6663. * to a new cpuset; we don't want to change their CPU
  6664. * affinity and isolating such threads by their set of
  6665. * allowed nodes is unnecessary. Thus, cpusets are not
  6666. * applicable for such threads. This prevents checking for
  6667. * success of set_cpus_allowed_ptr() on all attached tasks
  6668. * before cpus_mask may be changed.
  6669. */
  6670. if (p->flags & PF_NO_SETAFFINITY)
  6671. ret = -EINVAL;
  6672. return ret;
  6673. }
  6674. bool sched_smp_initialized __read_mostly;
  6675. #ifdef CONFIG_NUMA_BALANCING
  6676. /* Migrate current task p to target_cpu */
  6677. int migrate_task_to(struct task_struct *p, int target_cpu)
  6678. {
  6679. struct migration_arg arg = { p, target_cpu };
  6680. int curr_cpu = task_cpu(p);
  6681. if (curr_cpu == target_cpu)
  6682. return 0;
  6683. if (!cpumask_test_cpu(target_cpu, p->cpus_ptr))
  6684. return -EINVAL;
  6685. /* TODO: This is not properly updating schedstats */
  6686. trace_sched_move_numa(p, curr_cpu, target_cpu);
  6687. return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
  6688. }
  6689. /*
  6690. * Requeue a task on a given node and accurately track the number of NUMA
  6691. * tasks on the runqueues
  6692. */
  6693. void sched_setnuma(struct task_struct *p, int nid)
  6694. {
  6695. bool queued, running;
  6696. struct rq_flags rf;
  6697. struct rq *rq;
  6698. rq = task_rq_lock(p, &rf);
  6699. queued = task_on_rq_queued(p);
  6700. running = task_current(rq, p);
  6701. if (queued)
  6702. dequeue_task(rq, p, DEQUEUE_SAVE);
  6703. if (running)
  6704. put_prev_task(rq, p);
  6705. p->numa_preferred_nid = nid;
  6706. if (queued)
  6707. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  6708. if (running)
  6709. set_next_task(rq, p);
  6710. task_rq_unlock(rq, p, &rf);
  6711. }
  6712. #endif /* CONFIG_NUMA_BALANCING */
  6713. #ifdef CONFIG_HOTPLUG_CPU
  6714. /*
  6715. * Ensure that the idle task is using init_mm right before its CPU goes
  6716. * offline.
  6717. */
  6718. void idle_task_exit(void)
  6719. {
  6720. struct mm_struct *mm = current->active_mm;
  6721. BUG_ON(cpu_online(smp_processor_id()));
  6722. BUG_ON(current != this_rq()->idle);
  6723. if (mm != &init_mm) {
  6724. switch_mm(mm, &init_mm, current);
  6725. finish_arch_post_lock_switch();
  6726. }
  6727. /* finish_cpu(), as ran on the BP, will clean up the active_mm state */
  6728. }
  6729. static int __balance_push_cpu_stop(void *arg)
  6730. {
  6731. struct task_struct *p = arg;
  6732. struct rq *rq = this_rq();
  6733. struct rq_flags rf;
  6734. int cpu;
  6735. raw_spin_lock_irq(&p->pi_lock);
  6736. rq_lock(rq, &rf);
  6737. update_rq_clock(rq);
  6738. if (task_rq(p) == rq && task_on_rq_queued(p)) {
  6739. cpu = select_fallback_rq(rq->cpu, p);
  6740. rq = __migrate_task(rq, &rf, p, cpu);
  6741. }
  6742. rq_unlock(rq, &rf);
  6743. raw_spin_unlock_irq(&p->pi_lock);
  6744. put_task_struct(p);
  6745. return 0;
  6746. }
  6747. static DEFINE_PER_CPU(struct cpu_stop_work, push_work);
  6748. /*
  6749. * Ensure we only run per-cpu kthreads once the CPU goes !active.
  6750. *
  6751. * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only
  6752. * effective when the hotplug motion is down.
  6753. */
  6754. static void balance_push(struct rq *rq)
  6755. {
  6756. struct task_struct *push_task = rq->curr;
  6757. lockdep_assert_rq_held(rq);
  6758. /*
  6759. * Ensure the thing is persistent until balance_push_set(.on = false);
  6760. */
  6761. rq->balance_callback = &balance_push_callback;
  6762. /*
  6763. * Only active while going offline and when invoked on the outgoing
  6764. * CPU.
  6765. */
  6766. if (!cpu_dying(rq->cpu) || rq != this_rq())
  6767. return;
  6768. /*
  6769. * Both the cpu-hotplug and stop task are in this case and are
  6770. * required to complete the hotplug process.
  6771. */
  6772. if (kthread_is_per_cpu(push_task) ||
  6773. is_migration_disabled(push_task)) {
  6774. /*
  6775. * If this is the idle task on the outgoing CPU try to wake
  6776. * up the hotplug control thread which might wait for the
  6777. * last task to vanish. The rcuwait_active() check is
  6778. * accurate here because the waiter is pinned on this CPU
  6779. * and can't obviously be running in parallel.
  6780. *
  6781. * On RT kernels this also has to check whether there are
  6782. * pinned and scheduled out tasks on the runqueue. They
  6783. * need to leave the migrate disabled section first.
  6784. */
  6785. if (!rq->nr_running && !rq_has_pinned_tasks(rq) &&
  6786. rcuwait_active(&rq->hotplug_wait)) {
  6787. raw_spin_rq_unlock(rq);
  6788. rcuwait_wake_up(&rq->hotplug_wait);
  6789. raw_spin_rq_lock(rq);
  6790. }
  6791. return;
  6792. }
  6793. get_task_struct(push_task);
  6794. /*
  6795. * Temporarily drop rq->lock such that we can wake-up the stop task.
  6796. * Both preemption and IRQs are still disabled.
  6797. */
  6798. preempt_disable();
  6799. raw_spin_rq_unlock(rq);
  6800. stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task,
  6801. this_cpu_ptr(&push_work));
  6802. preempt_enable();
  6803. /*
  6804. * At this point need_resched() is true and we'll take the loop in
  6805. * schedule(). The next pick is obviously going to be the stop task
  6806. * which kthread_is_per_cpu() and will push this task away.
  6807. */
  6808. raw_spin_rq_lock(rq);
  6809. }
  6810. static void balance_push_set(int cpu, bool on)
  6811. {
  6812. struct rq *rq = cpu_rq(cpu);
  6813. struct rq_flags rf;
  6814. rq_lock_irqsave(rq, &rf);
  6815. if (on) {
  6816. WARN_ON_ONCE(rq->balance_callback);
  6817. rq->balance_callback = &balance_push_callback;
  6818. } else if (rq->balance_callback == &balance_push_callback) {
  6819. rq->balance_callback = NULL;
  6820. }
  6821. rq_unlock_irqrestore(rq, &rf);
  6822. }
  6823. /*
  6824. * Invoked from a CPUs hotplug control thread after the CPU has been marked
  6825. * inactive. All tasks which are not per CPU kernel threads are either
  6826. * pushed off this CPU now via balance_push() or placed on a different CPU
  6827. * during wakeup. Wait until the CPU is quiescent.
  6828. */
  6829. static void balance_hotplug_wait(void)
  6830. {
  6831. struct rq *rq = this_rq();
  6832. rcuwait_wait_event(&rq->hotplug_wait,
  6833. rq->nr_running == 1 && !rq_has_pinned_tasks(rq),
  6834. TASK_UNINTERRUPTIBLE);
  6835. }
  6836. #else
  6837. static inline void balance_push(struct rq *rq)
  6838. {
  6839. }
  6840. static inline void balance_push_set(int cpu, bool on)
  6841. {
  6842. }
  6843. static inline void balance_hotplug_wait(void)
  6844. {
  6845. }
  6846. #endif /* CONFIG_HOTPLUG_CPU */
  6847. void set_rq_online(struct rq *rq)
  6848. {
  6849. if (!rq->online) {
  6850. const struct sched_class *class;
  6851. cpumask_set_cpu(rq->cpu, rq->rd->online);
  6852. rq->online = 1;
  6853. for_each_class(class) {
  6854. if (class->rq_online)
  6855. class->rq_online(rq);
  6856. }
  6857. }
  6858. }
  6859. void set_rq_offline(struct rq *rq)
  6860. {
  6861. if (rq->online) {
  6862. const struct sched_class *class;
  6863. update_rq_clock(rq);
  6864. for_each_class(class) {
  6865. if (class->rq_offline)
  6866. class->rq_offline(rq);
  6867. }
  6868. cpumask_clear_cpu(rq->cpu, rq->rd->online);
  6869. rq->online = 0;
  6870. }
  6871. }
  6872. static inline void sched_set_rq_online(struct rq *rq, int cpu)
  6873. {
  6874. struct rq_flags rf;
  6875. rq_lock_irqsave(rq, &rf);
  6876. if (rq->rd) {
  6877. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  6878. set_rq_online(rq);
  6879. }
  6880. rq_unlock_irqrestore(rq, &rf);
  6881. }
  6882. static inline void sched_set_rq_offline(struct rq *rq, int cpu)
  6883. {
  6884. struct rq_flags rf;
  6885. rq_lock_irqsave(rq, &rf);
  6886. if (rq->rd) {
  6887. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  6888. set_rq_offline(rq);
  6889. }
  6890. rq_unlock_irqrestore(rq, &rf);
  6891. }
  6892. /*
  6893. * used to mark begin/end of suspend/resume:
  6894. */
  6895. static int num_cpus_frozen;
  6896. /*
  6897. * Update cpusets according to cpu_active mask. If cpusets are
  6898. * disabled, cpuset_update_active_cpus() becomes a simple wrapper
  6899. * around partition_sched_domains().
  6900. *
  6901. * If we come here as part of a suspend/resume, don't touch cpusets because we
  6902. * want to restore it back to its original state upon resume anyway.
  6903. */
  6904. static void cpuset_cpu_active(void)
  6905. {
  6906. if (cpuhp_tasks_frozen) {
  6907. /*
  6908. * num_cpus_frozen tracks how many CPUs are involved in suspend
  6909. * resume sequence. As long as this is not the last online
  6910. * operation in the resume sequence, just build a single sched
  6911. * domain, ignoring cpusets.
  6912. */
  6913. partition_sched_domains(1, NULL, NULL);
  6914. if (--num_cpus_frozen)
  6915. return;
  6916. /*
  6917. * This is the last CPU online operation. So fall through and
  6918. * restore the original sched domains by considering the
  6919. * cpuset configurations.
  6920. */
  6921. cpuset_force_rebuild();
  6922. }
  6923. cpuset_update_active_cpus();
  6924. }
  6925. static int cpuset_cpu_inactive(unsigned int cpu)
  6926. {
  6927. if (!cpuhp_tasks_frozen) {
  6928. int ret = dl_bw_check_overflow(cpu);
  6929. if (ret)
  6930. return ret;
  6931. cpuset_update_active_cpus();
  6932. } else {
  6933. num_cpus_frozen++;
  6934. partition_sched_domains(1, NULL, NULL);
  6935. }
  6936. return 0;
  6937. }
  6938. static inline void sched_smt_present_inc(int cpu)
  6939. {
  6940. #ifdef CONFIG_SCHED_SMT
  6941. if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
  6942. static_branch_inc_cpuslocked(&sched_smt_present);
  6943. #endif
  6944. }
  6945. static inline void sched_smt_present_dec(int cpu)
  6946. {
  6947. #ifdef CONFIG_SCHED_SMT
  6948. if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
  6949. static_branch_dec_cpuslocked(&sched_smt_present);
  6950. #endif
  6951. }
  6952. int sched_cpu_activate(unsigned int cpu)
  6953. {
  6954. struct rq *rq = cpu_rq(cpu);
  6955. /*
  6956. * Clear the balance_push callback and prepare to schedule
  6957. * regular tasks.
  6958. */
  6959. balance_push_set(cpu, false);
  6960. /*
  6961. * When going up, increment the number of cores with SMT present.
  6962. */
  6963. sched_smt_present_inc(cpu);
  6964. set_cpu_active(cpu, true);
  6965. if (sched_smp_initialized) {
  6966. sched_update_numa(cpu, true);
  6967. sched_domains_numa_masks_set(cpu);
  6968. cpuset_cpu_active();
  6969. }
  6970. scx_rq_activate(rq);
  6971. /*
  6972. * Put the rq online, if not already. This happens:
  6973. *
  6974. * 1) In the early boot process, because we build the real domains
  6975. * after all CPUs have been brought up.
  6976. *
  6977. * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
  6978. * domains.
  6979. */
  6980. sched_set_rq_online(rq, cpu);
  6981. return 0;
  6982. }
  6983. int sched_cpu_deactivate(unsigned int cpu)
  6984. {
  6985. struct rq *rq = cpu_rq(cpu);
  6986. int ret;
  6987. /*
  6988. * Remove CPU from nohz.idle_cpus_mask to prevent participating in
  6989. * load balancing when not active
  6990. */
  6991. nohz_balance_exit_idle(rq);
  6992. set_cpu_active(cpu, false);
  6993. /*
  6994. * From this point forward, this CPU will refuse to run any task that
  6995. * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively
  6996. * push those tasks away until this gets cleared, see
  6997. * sched_cpu_dying().
  6998. */
  6999. balance_push_set(cpu, true);
  7000. /*
  7001. * We've cleared cpu_active_mask / set balance_push, wait for all
  7002. * preempt-disabled and RCU users of this state to go away such that
  7003. * all new such users will observe it.
  7004. *
  7005. * Specifically, we rely on ttwu to no longer target this CPU, see
  7006. * ttwu_queue_cond() and is_cpu_allowed().
  7007. *
  7008. * Do sync before park smpboot threads to take care the RCU boost case.
  7009. */
  7010. synchronize_rcu();
  7011. sched_set_rq_offline(rq, cpu);
  7012. scx_rq_deactivate(rq);
  7013. /*
  7014. * When going down, decrement the number of cores with SMT present.
  7015. */
  7016. sched_smt_present_dec(cpu);
  7017. #ifdef CONFIG_SCHED_SMT
  7018. sched_core_cpu_deactivate(cpu);
  7019. #endif
  7020. if (!sched_smp_initialized)
  7021. return 0;
  7022. sched_update_numa(cpu, false);
  7023. ret = cpuset_cpu_inactive(cpu);
  7024. if (ret) {
  7025. sched_smt_present_inc(cpu);
  7026. sched_set_rq_online(rq, cpu);
  7027. balance_push_set(cpu, false);
  7028. set_cpu_active(cpu, true);
  7029. sched_update_numa(cpu, true);
  7030. return ret;
  7031. }
  7032. sched_domains_numa_masks_clear(cpu);
  7033. return 0;
  7034. }
  7035. static void sched_rq_cpu_starting(unsigned int cpu)
  7036. {
  7037. struct rq *rq = cpu_rq(cpu);
  7038. rq->calc_load_update = calc_load_update;
  7039. update_max_interval();
  7040. }
  7041. int sched_cpu_starting(unsigned int cpu)
  7042. {
  7043. sched_core_cpu_starting(cpu);
  7044. sched_rq_cpu_starting(cpu);
  7045. sched_tick_start(cpu);
  7046. return 0;
  7047. }
  7048. #ifdef CONFIG_HOTPLUG_CPU
  7049. /*
  7050. * Invoked immediately before the stopper thread is invoked to bring the
  7051. * CPU down completely. At this point all per CPU kthreads except the
  7052. * hotplug thread (current) and the stopper thread (inactive) have been
  7053. * either parked or have been unbound from the outgoing CPU. Ensure that
  7054. * any of those which might be on the way out are gone.
  7055. *
  7056. * If after this point a bound task is being woken on this CPU then the
  7057. * responsible hotplug callback has failed to do it's job.
  7058. * sched_cpu_dying() will catch it with the appropriate fireworks.
  7059. */
  7060. int sched_cpu_wait_empty(unsigned int cpu)
  7061. {
  7062. balance_hotplug_wait();
  7063. return 0;
  7064. }
  7065. /*
  7066. * Since this CPU is going 'away' for a while, fold any nr_active delta we
  7067. * might have. Called from the CPU stopper task after ensuring that the
  7068. * stopper is the last running task on the CPU, so nr_active count is
  7069. * stable. We need to take the tear-down thread which is calling this into
  7070. * account, so we hand in adjust = 1 to the load calculation.
  7071. *
  7072. * Also see the comment "Global load-average calculations".
  7073. */
  7074. static void calc_load_migrate(struct rq *rq)
  7075. {
  7076. long delta = calc_load_fold_active(rq, 1);
  7077. if (delta)
  7078. atomic_long_add(delta, &calc_load_tasks);
  7079. }
  7080. static void dump_rq_tasks(struct rq *rq, const char *loglvl)
  7081. {
  7082. struct task_struct *g, *p;
  7083. int cpu = cpu_of(rq);
  7084. lockdep_assert_rq_held(rq);
  7085. printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running);
  7086. for_each_process_thread(g, p) {
  7087. if (task_cpu(p) != cpu)
  7088. continue;
  7089. if (!task_on_rq_queued(p))
  7090. continue;
  7091. printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm);
  7092. }
  7093. }
  7094. int sched_cpu_dying(unsigned int cpu)
  7095. {
  7096. struct rq *rq = cpu_rq(cpu);
  7097. struct rq_flags rf;
  7098. /* Handle pending wakeups and then migrate everything off */
  7099. sched_tick_stop(cpu);
  7100. rq_lock_irqsave(rq, &rf);
  7101. if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) {
  7102. WARN(true, "Dying CPU not properly vacated!");
  7103. dump_rq_tasks(rq, KERN_WARNING);
  7104. }
  7105. rq_unlock_irqrestore(rq, &rf);
  7106. calc_load_migrate(rq);
  7107. update_max_interval();
  7108. hrtick_clear(rq);
  7109. sched_core_cpu_dying(cpu);
  7110. return 0;
  7111. }
  7112. #endif
  7113. void __init sched_init_smp(void)
  7114. {
  7115. sched_init_numa(NUMA_NO_NODE);
  7116. /*
  7117. * There's no userspace yet to cause hotplug operations; hence all the
  7118. * CPU masks are stable and all blatant races in the below code cannot
  7119. * happen.
  7120. */
  7121. mutex_lock(&sched_domains_mutex);
  7122. sched_init_domains(cpu_active_mask);
  7123. mutex_unlock(&sched_domains_mutex);
  7124. /* Move init over to a non-isolated CPU */
  7125. if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0)
  7126. BUG();
  7127. current->flags &= ~PF_NO_SETAFFINITY;
  7128. sched_init_granularity();
  7129. init_sched_rt_class();
  7130. init_sched_dl_class();
  7131. sched_smp_initialized = true;
  7132. }
  7133. static int __init migration_init(void)
  7134. {
  7135. sched_cpu_starting(smp_processor_id());
  7136. return 0;
  7137. }
  7138. early_initcall(migration_init);
  7139. #else
  7140. void __init sched_init_smp(void)
  7141. {
  7142. sched_init_granularity();
  7143. }
  7144. #endif /* CONFIG_SMP */
  7145. int in_sched_functions(unsigned long addr)
  7146. {
  7147. return in_lock_functions(addr) ||
  7148. (addr >= (unsigned long)__sched_text_start
  7149. && addr < (unsigned long)__sched_text_end);
  7150. }
  7151. #ifdef CONFIG_CGROUP_SCHED
  7152. /*
  7153. * Default task group.
  7154. * Every task in system belongs to this group at bootup.
  7155. */
  7156. struct task_group root_task_group;
  7157. LIST_HEAD(task_groups);
  7158. /* Cacheline aligned slab cache for task_group */
  7159. static struct kmem_cache *task_group_cache __ro_after_init;
  7160. #endif
  7161. void __init sched_init(void)
  7162. {
  7163. unsigned long ptr = 0;
  7164. int i;
  7165. /* Make sure the linker didn't screw up */
  7166. #ifdef CONFIG_SMP
  7167. BUG_ON(!sched_class_above(&stop_sched_class, &dl_sched_class));
  7168. #endif
  7169. BUG_ON(!sched_class_above(&dl_sched_class, &rt_sched_class));
  7170. BUG_ON(!sched_class_above(&rt_sched_class, &fair_sched_class));
  7171. BUG_ON(!sched_class_above(&fair_sched_class, &idle_sched_class));
  7172. #ifdef CONFIG_SCHED_CLASS_EXT
  7173. BUG_ON(!sched_class_above(&fair_sched_class, &ext_sched_class));
  7174. BUG_ON(!sched_class_above(&ext_sched_class, &idle_sched_class));
  7175. #endif
  7176. wait_bit_init();
  7177. #ifdef CONFIG_FAIR_GROUP_SCHED
  7178. ptr += 2 * nr_cpu_ids * sizeof(void **);
  7179. #endif
  7180. #ifdef CONFIG_RT_GROUP_SCHED
  7181. ptr += 2 * nr_cpu_ids * sizeof(void **);
  7182. #endif
  7183. if (ptr) {
  7184. ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT);
  7185. #ifdef CONFIG_FAIR_GROUP_SCHED
  7186. root_task_group.se = (struct sched_entity **)ptr;
  7187. ptr += nr_cpu_ids * sizeof(void **);
  7188. root_task_group.cfs_rq = (struct cfs_rq **)ptr;
  7189. ptr += nr_cpu_ids * sizeof(void **);
  7190. root_task_group.shares = ROOT_TASK_GROUP_LOAD;
  7191. init_cfs_bandwidth(&root_task_group.cfs_bandwidth, NULL);
  7192. #endif /* CONFIG_FAIR_GROUP_SCHED */
  7193. #ifdef CONFIG_EXT_GROUP_SCHED
  7194. root_task_group.scx_weight = CGROUP_WEIGHT_DFL;
  7195. #endif /* CONFIG_EXT_GROUP_SCHED */
  7196. #ifdef CONFIG_RT_GROUP_SCHED
  7197. root_task_group.rt_se = (struct sched_rt_entity **)ptr;
  7198. ptr += nr_cpu_ids * sizeof(void **);
  7199. root_task_group.rt_rq = (struct rt_rq **)ptr;
  7200. ptr += nr_cpu_ids * sizeof(void **);
  7201. #endif /* CONFIG_RT_GROUP_SCHED */
  7202. }
  7203. #ifdef CONFIG_SMP
  7204. init_defrootdomain();
  7205. #endif
  7206. #ifdef CONFIG_RT_GROUP_SCHED
  7207. init_rt_bandwidth(&root_task_group.rt_bandwidth,
  7208. global_rt_period(), global_rt_runtime());
  7209. #endif /* CONFIG_RT_GROUP_SCHED */
  7210. #ifdef CONFIG_CGROUP_SCHED
  7211. task_group_cache = KMEM_CACHE(task_group, 0);
  7212. list_add(&root_task_group.list, &task_groups);
  7213. INIT_LIST_HEAD(&root_task_group.children);
  7214. INIT_LIST_HEAD(&root_task_group.siblings);
  7215. autogroup_init(&init_task);
  7216. #endif /* CONFIG_CGROUP_SCHED */
  7217. for_each_possible_cpu(i) {
  7218. struct rq *rq;
  7219. rq = cpu_rq(i);
  7220. raw_spin_lock_init(&rq->__lock);
  7221. rq->nr_running = 0;
  7222. rq->calc_load_active = 0;
  7223. rq->calc_load_update = jiffies + LOAD_FREQ;
  7224. init_cfs_rq(&rq->cfs);
  7225. init_rt_rq(&rq->rt);
  7226. init_dl_rq(&rq->dl);
  7227. #ifdef CONFIG_FAIR_GROUP_SCHED
  7228. INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
  7229. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  7230. /*
  7231. * How much CPU bandwidth does root_task_group get?
  7232. *
  7233. * In case of task-groups formed through the cgroup filesystem, it
  7234. * gets 100% of the CPU resources in the system. This overall
  7235. * system CPU resource is divided among the tasks of
  7236. * root_task_group and its child task-groups in a fair manner,
  7237. * based on each entity's (task or task-group's) weight
  7238. * (se->load.weight).
  7239. *
  7240. * In other words, if root_task_group has 10 tasks of weight
  7241. * 1024) and two child groups A0 and A1 (of weight 1024 each),
  7242. * then A0's share of the CPU resource is:
  7243. *
  7244. * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
  7245. *
  7246. * We achieve this by letting root_task_group's tasks sit
  7247. * directly in rq->cfs (i.e root_task_group->se[] = NULL).
  7248. */
  7249. init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
  7250. #endif /* CONFIG_FAIR_GROUP_SCHED */
  7251. #ifdef CONFIG_RT_GROUP_SCHED
  7252. /*
  7253. * This is required for init cpu because rt.c:__enable_runtime()
  7254. * starts working after scheduler_running, which is not the case
  7255. * yet.
  7256. */
  7257. rq->rt.rt_runtime = global_rt_runtime();
  7258. init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
  7259. #endif
  7260. #ifdef CONFIG_SMP
  7261. rq->sd = NULL;
  7262. rq->rd = NULL;
  7263. rq->cpu_capacity = SCHED_CAPACITY_SCALE;
  7264. rq->balance_callback = &balance_push_callback;
  7265. rq->active_balance = 0;
  7266. rq->next_balance = jiffies;
  7267. rq->push_cpu = 0;
  7268. rq->cpu = i;
  7269. rq->online = 0;
  7270. rq->idle_stamp = 0;
  7271. rq->avg_idle = 2*sysctl_sched_migration_cost;
  7272. rq->max_idle_balance_cost = sysctl_sched_migration_cost;
  7273. INIT_LIST_HEAD(&rq->cfs_tasks);
  7274. rq_attach_root(rq, &def_root_domain);
  7275. #ifdef CONFIG_NO_HZ_COMMON
  7276. rq->last_blocked_load_update_tick = jiffies;
  7277. atomic_set(&rq->nohz_flags, 0);
  7278. INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq);
  7279. #endif
  7280. #ifdef CONFIG_HOTPLUG_CPU
  7281. rcuwait_init(&rq->hotplug_wait);
  7282. #endif
  7283. #endif /* CONFIG_SMP */
  7284. hrtick_rq_init(rq);
  7285. atomic_set(&rq->nr_iowait, 0);
  7286. fair_server_init(rq);
  7287. #ifdef CONFIG_SCHED_CORE
  7288. rq->core = rq;
  7289. rq->core_pick = NULL;
  7290. rq->core_dl_server = NULL;
  7291. rq->core_enabled = 0;
  7292. rq->core_tree = RB_ROOT;
  7293. rq->core_forceidle_count = 0;
  7294. rq->core_forceidle_occupation = 0;
  7295. rq->core_forceidle_start = 0;
  7296. rq->core_cookie = 0UL;
  7297. #endif
  7298. zalloc_cpumask_var_node(&rq->scratch_mask, GFP_KERNEL, cpu_to_node(i));
  7299. }
  7300. set_load_weight(&init_task, false);
  7301. init_task.se.slice = sysctl_sched_base_slice,
  7302. /*
  7303. * The boot idle thread does lazy MMU switching as well:
  7304. */
  7305. mmgrab_lazy_tlb(&init_mm);
  7306. enter_lazy_tlb(&init_mm, current);
  7307. /*
  7308. * The idle task doesn't need the kthread struct to function, but it
  7309. * is dressed up as a per-CPU kthread and thus needs to play the part
  7310. * if we want to avoid special-casing it in code that deals with per-CPU
  7311. * kthreads.
  7312. */
  7313. WARN_ON(!set_kthread_struct(current));
  7314. /*
  7315. * Make us the idle thread. Technically, schedule() should not be
  7316. * called from this thread, however somewhere below it might be,
  7317. * but because we are the idle thread, we just pick up running again
  7318. * when this runqueue becomes "idle".
  7319. */
  7320. __sched_fork(0, current);
  7321. init_idle(current, smp_processor_id());
  7322. calc_load_update = jiffies + LOAD_FREQ;
  7323. #ifdef CONFIG_SMP
  7324. idle_thread_set_boot_cpu();
  7325. balance_push_set(smp_processor_id(), false);
  7326. #endif
  7327. init_sched_fair_class();
  7328. init_sched_ext_class();
  7329. psi_init();
  7330. init_uclamp();
  7331. preempt_dynamic_init();
  7332. scheduler_running = 1;
  7333. }
  7334. #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
  7335. void __might_sleep(const char *file, int line)
  7336. {
  7337. unsigned int state = get_current_state();
  7338. /*
  7339. * Blocking primitives will set (and therefore destroy) current->state,
  7340. * since we will exit with TASK_RUNNING make sure we enter with it,
  7341. * otherwise we will destroy state.
  7342. */
  7343. WARN_ONCE(state != TASK_RUNNING && current->task_state_change,
  7344. "do not call blocking ops when !TASK_RUNNING; "
  7345. "state=%x set at [<%p>] %pS\n", state,
  7346. (void *)current->task_state_change,
  7347. (void *)current->task_state_change);
  7348. __might_resched(file, line, 0);
  7349. }
  7350. EXPORT_SYMBOL(__might_sleep);
  7351. static void print_preempt_disable_ip(int preempt_offset, unsigned long ip)
  7352. {
  7353. if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT))
  7354. return;
  7355. if (preempt_count() == preempt_offset)
  7356. return;
  7357. pr_err("Preemption disabled at:");
  7358. print_ip_sym(KERN_ERR, ip);
  7359. }
  7360. static inline bool resched_offsets_ok(unsigned int offsets)
  7361. {
  7362. unsigned int nested = preempt_count();
  7363. nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT;
  7364. return nested == offsets;
  7365. }
  7366. void __might_resched(const char *file, int line, unsigned int offsets)
  7367. {
  7368. /* Ratelimiting timestamp: */
  7369. static unsigned long prev_jiffy;
  7370. unsigned long preempt_disable_ip;
  7371. /* WARN_ON_ONCE() by default, no rate limit required: */
  7372. rcu_sleep_check();
  7373. if ((resched_offsets_ok(offsets) && !irqs_disabled() &&
  7374. !is_idle_task(current) && !current->non_block_count) ||
  7375. system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
  7376. oops_in_progress)
  7377. return;
  7378. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  7379. return;
  7380. prev_jiffy = jiffies;
  7381. /* Save this before calling printk(), since that will clobber it: */
  7382. preempt_disable_ip = get_preempt_disable_ip(current);
  7383. pr_err("BUG: sleeping function called from invalid context at %s:%d\n",
  7384. file, line);
  7385. pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
  7386. in_atomic(), irqs_disabled(), current->non_block_count,
  7387. current->pid, current->comm);
  7388. pr_err("preempt_count: %x, expected: %x\n", preempt_count(),
  7389. offsets & MIGHT_RESCHED_PREEMPT_MASK);
  7390. if (IS_ENABLED(CONFIG_PREEMPT_RCU)) {
  7391. pr_err("RCU nest depth: %d, expected: %u\n",
  7392. rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT);
  7393. }
  7394. if (task_stack_end_corrupted(current))
  7395. pr_emerg("Thread overran stack, or stack corrupted\n");
  7396. debug_show_held_locks(current);
  7397. if (irqs_disabled())
  7398. print_irqtrace_events(current);
  7399. print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK,
  7400. preempt_disable_ip);
  7401. dump_stack();
  7402. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  7403. }
  7404. EXPORT_SYMBOL(__might_resched);
  7405. void __cant_sleep(const char *file, int line, int preempt_offset)
  7406. {
  7407. static unsigned long prev_jiffy;
  7408. if (irqs_disabled())
  7409. return;
  7410. if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
  7411. return;
  7412. if (preempt_count() > preempt_offset)
  7413. return;
  7414. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  7415. return;
  7416. prev_jiffy = jiffies;
  7417. printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line);
  7418. printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
  7419. in_atomic(), irqs_disabled(),
  7420. current->pid, current->comm);
  7421. debug_show_held_locks(current);
  7422. dump_stack();
  7423. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  7424. }
  7425. EXPORT_SYMBOL_GPL(__cant_sleep);
  7426. #ifdef CONFIG_SMP
  7427. void __cant_migrate(const char *file, int line)
  7428. {
  7429. static unsigned long prev_jiffy;
  7430. if (irqs_disabled())
  7431. return;
  7432. if (is_migration_disabled(current))
  7433. return;
  7434. if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
  7435. return;
  7436. if (preempt_count() > 0)
  7437. return;
  7438. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  7439. return;
  7440. prev_jiffy = jiffies;
  7441. pr_err("BUG: assuming non migratable context at %s:%d\n", file, line);
  7442. pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n",
  7443. in_atomic(), irqs_disabled(), is_migration_disabled(current),
  7444. current->pid, current->comm);
  7445. debug_show_held_locks(current);
  7446. dump_stack();
  7447. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  7448. }
  7449. EXPORT_SYMBOL_GPL(__cant_migrate);
  7450. #endif
  7451. #endif
  7452. #ifdef CONFIG_MAGIC_SYSRQ
  7453. void normalize_rt_tasks(void)
  7454. {
  7455. struct task_struct *g, *p;
  7456. struct sched_attr attr = {
  7457. .sched_policy = SCHED_NORMAL,
  7458. };
  7459. read_lock(&tasklist_lock);
  7460. for_each_process_thread(g, p) {
  7461. /*
  7462. * Only normalize user tasks:
  7463. */
  7464. if (p->flags & PF_KTHREAD)
  7465. continue;
  7466. p->se.exec_start = 0;
  7467. schedstat_set(p->stats.wait_start, 0);
  7468. schedstat_set(p->stats.sleep_start, 0);
  7469. schedstat_set(p->stats.block_start, 0);
  7470. if (!rt_or_dl_task(p)) {
  7471. /*
  7472. * Renice negative nice level userspace
  7473. * tasks back to 0:
  7474. */
  7475. if (task_nice(p) < 0)
  7476. set_user_nice(p, 0);
  7477. continue;
  7478. }
  7479. __sched_setscheduler(p, &attr, false, false);
  7480. }
  7481. read_unlock(&tasklist_lock);
  7482. }
  7483. #endif /* CONFIG_MAGIC_SYSRQ */
  7484. #if defined(CONFIG_KGDB_KDB)
  7485. /*
  7486. * These functions are only useful for KDB.
  7487. *
  7488. * They can only be called when the whole system has been
  7489. * stopped - every CPU needs to be quiescent, and no scheduling
  7490. * activity can take place. Using them for anything else would
  7491. * be a serious bug, and as a result, they aren't even visible
  7492. * under any other configuration.
  7493. */
  7494. /**
  7495. * curr_task - return the current task for a given CPU.
  7496. * @cpu: the processor in question.
  7497. *
  7498. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  7499. *
  7500. * Return: The current task for @cpu.
  7501. */
  7502. struct task_struct *curr_task(int cpu)
  7503. {
  7504. return cpu_curr(cpu);
  7505. }
  7506. #endif /* defined(CONFIG_KGDB_KDB) */
  7507. #ifdef CONFIG_CGROUP_SCHED
  7508. /* task_group_lock serializes the addition/removal of task groups */
  7509. static DEFINE_SPINLOCK(task_group_lock);
  7510. static inline void alloc_uclamp_sched_group(struct task_group *tg,
  7511. struct task_group *parent)
  7512. {
  7513. #ifdef CONFIG_UCLAMP_TASK_GROUP
  7514. enum uclamp_id clamp_id;
  7515. for_each_clamp_id(clamp_id) {
  7516. uclamp_se_set(&tg->uclamp_req[clamp_id],
  7517. uclamp_none(clamp_id), false);
  7518. tg->uclamp[clamp_id] = parent->uclamp[clamp_id];
  7519. }
  7520. #endif
  7521. }
  7522. static void sched_free_group(struct task_group *tg)
  7523. {
  7524. free_fair_sched_group(tg);
  7525. free_rt_sched_group(tg);
  7526. autogroup_free(tg);
  7527. kmem_cache_free(task_group_cache, tg);
  7528. }
  7529. static void sched_free_group_rcu(struct rcu_head *rcu)
  7530. {
  7531. sched_free_group(container_of(rcu, struct task_group, rcu));
  7532. }
  7533. static void sched_unregister_group(struct task_group *tg)
  7534. {
  7535. unregister_fair_sched_group(tg);
  7536. unregister_rt_sched_group(tg);
  7537. /*
  7538. * We have to wait for yet another RCU grace period to expire, as
  7539. * print_cfs_stats() might run concurrently.
  7540. */
  7541. call_rcu(&tg->rcu, sched_free_group_rcu);
  7542. }
  7543. /* allocate runqueue etc for a new task group */
  7544. struct task_group *sched_create_group(struct task_group *parent)
  7545. {
  7546. struct task_group *tg;
  7547. tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
  7548. if (!tg)
  7549. return ERR_PTR(-ENOMEM);
  7550. if (!alloc_fair_sched_group(tg, parent))
  7551. goto err;
  7552. if (!alloc_rt_sched_group(tg, parent))
  7553. goto err;
  7554. scx_group_set_weight(tg, CGROUP_WEIGHT_DFL);
  7555. alloc_uclamp_sched_group(tg, parent);
  7556. return tg;
  7557. err:
  7558. sched_free_group(tg);
  7559. return ERR_PTR(-ENOMEM);
  7560. }
  7561. void sched_online_group(struct task_group *tg, struct task_group *parent)
  7562. {
  7563. unsigned long flags;
  7564. spin_lock_irqsave(&task_group_lock, flags);
  7565. list_add_rcu(&tg->list, &task_groups);
  7566. /* Root should already exist: */
  7567. WARN_ON(!parent);
  7568. tg->parent = parent;
  7569. INIT_LIST_HEAD(&tg->children);
  7570. list_add_rcu(&tg->siblings, &parent->children);
  7571. spin_unlock_irqrestore(&task_group_lock, flags);
  7572. online_fair_sched_group(tg);
  7573. }
  7574. /* RCU callback to free various structures associated with a task group */
  7575. static void sched_unregister_group_rcu(struct rcu_head *rhp)
  7576. {
  7577. /* Now it should be safe to free those cfs_rqs: */
  7578. sched_unregister_group(container_of(rhp, struct task_group, rcu));
  7579. }
  7580. void sched_destroy_group(struct task_group *tg)
  7581. {
  7582. /* Wait for possible concurrent references to cfs_rqs complete: */
  7583. call_rcu(&tg->rcu, sched_unregister_group_rcu);
  7584. }
  7585. void sched_release_group(struct task_group *tg)
  7586. {
  7587. unsigned long flags;
  7588. /*
  7589. * Unlink first, to avoid walk_tg_tree_from() from finding us (via
  7590. * sched_cfs_period_timer()).
  7591. *
  7592. * For this to be effective, we have to wait for all pending users of
  7593. * this task group to leave their RCU critical section to ensure no new
  7594. * user will see our dying task group any more. Specifically ensure
  7595. * that tg_unthrottle_up() won't add decayed cfs_rq's to it.
  7596. *
  7597. * We therefore defer calling unregister_fair_sched_group() to
  7598. * sched_unregister_group() which is guarantied to get called only after the
  7599. * current RCU grace period has expired.
  7600. */
  7601. spin_lock_irqsave(&task_group_lock, flags);
  7602. list_del_rcu(&tg->list);
  7603. list_del_rcu(&tg->siblings);
  7604. spin_unlock_irqrestore(&task_group_lock, flags);
  7605. }
  7606. static struct task_group *sched_get_task_group(struct task_struct *tsk)
  7607. {
  7608. struct task_group *tg;
  7609. /*
  7610. * All callers are synchronized by task_rq_lock(); we do not use RCU
  7611. * which is pointless here. Thus, we pass "true" to task_css_check()
  7612. * to prevent lockdep warnings.
  7613. */
  7614. tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
  7615. struct task_group, css);
  7616. tg = autogroup_task_group(tsk, tg);
  7617. return tg;
  7618. }
  7619. static void sched_change_group(struct task_struct *tsk, struct task_group *group)
  7620. {
  7621. tsk->sched_task_group = group;
  7622. #ifdef CONFIG_FAIR_GROUP_SCHED
  7623. if (tsk->sched_class->task_change_group)
  7624. tsk->sched_class->task_change_group(tsk);
  7625. else
  7626. #endif
  7627. set_task_rq(tsk, task_cpu(tsk));
  7628. }
  7629. /*
  7630. * Change task's runqueue when it moves between groups.
  7631. *
  7632. * The caller of this function should have put the task in its new group by
  7633. * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
  7634. * its new group.
  7635. */
  7636. void sched_move_task(struct task_struct *tsk, bool for_autogroup)
  7637. {
  7638. int queued, running, queue_flags =
  7639. DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  7640. struct task_group *group;
  7641. struct rq *rq;
  7642. CLASS(task_rq_lock, rq_guard)(tsk);
  7643. rq = rq_guard.rq;
  7644. /*
  7645. * Esp. with SCHED_AUTOGROUP enabled it is possible to get superfluous
  7646. * group changes.
  7647. */
  7648. group = sched_get_task_group(tsk);
  7649. if (group == tsk->sched_task_group)
  7650. return;
  7651. update_rq_clock(rq);
  7652. running = task_current(rq, tsk);
  7653. queued = task_on_rq_queued(tsk);
  7654. if (queued)
  7655. dequeue_task(rq, tsk, queue_flags);
  7656. if (running)
  7657. put_prev_task(rq, tsk);
  7658. sched_change_group(tsk, group);
  7659. if (!for_autogroup)
  7660. scx_cgroup_move_task(tsk);
  7661. if (queued)
  7662. enqueue_task(rq, tsk, queue_flags);
  7663. if (running) {
  7664. set_next_task(rq, tsk);
  7665. /*
  7666. * After changing group, the running task may have joined a
  7667. * throttled one but it's still the running task. Trigger a
  7668. * resched to make sure that task can still run.
  7669. */
  7670. resched_curr(rq);
  7671. }
  7672. }
  7673. static struct cgroup_subsys_state *
  7674. cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  7675. {
  7676. struct task_group *parent = css_tg(parent_css);
  7677. struct task_group *tg;
  7678. if (!parent) {
  7679. /* This is early initialization for the top cgroup */
  7680. return &root_task_group.css;
  7681. }
  7682. tg = sched_create_group(parent);
  7683. if (IS_ERR(tg))
  7684. return ERR_PTR(-ENOMEM);
  7685. return &tg->css;
  7686. }
  7687. /* Expose task group only after completing cgroup initialization */
  7688. static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
  7689. {
  7690. struct task_group *tg = css_tg(css);
  7691. struct task_group *parent = css_tg(css->parent);
  7692. int ret;
  7693. ret = scx_tg_online(tg);
  7694. if (ret)
  7695. return ret;
  7696. if (parent)
  7697. sched_online_group(tg, parent);
  7698. #ifdef CONFIG_UCLAMP_TASK_GROUP
  7699. /* Propagate the effective uclamp value for the new group */
  7700. guard(mutex)(&uclamp_mutex);
  7701. guard(rcu)();
  7702. cpu_util_update_eff(css);
  7703. #endif
  7704. return 0;
  7705. }
  7706. static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css)
  7707. {
  7708. struct task_group *tg = css_tg(css);
  7709. scx_tg_offline(tg);
  7710. }
  7711. static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
  7712. {
  7713. struct task_group *tg = css_tg(css);
  7714. sched_release_group(tg);
  7715. }
  7716. static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
  7717. {
  7718. struct task_group *tg = css_tg(css);
  7719. /*
  7720. * Relies on the RCU grace period between css_released() and this.
  7721. */
  7722. sched_unregister_group(tg);
  7723. }
  7724. static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
  7725. {
  7726. #ifdef CONFIG_RT_GROUP_SCHED
  7727. struct task_struct *task;
  7728. struct cgroup_subsys_state *css;
  7729. cgroup_taskset_for_each(task, css, tset) {
  7730. if (!sched_rt_can_attach(css_tg(css), task))
  7731. return -EINVAL;
  7732. }
  7733. #endif
  7734. return scx_cgroup_can_attach(tset);
  7735. }
  7736. static void cpu_cgroup_attach(struct cgroup_taskset *tset)
  7737. {
  7738. struct task_struct *task;
  7739. struct cgroup_subsys_state *css;
  7740. cgroup_taskset_for_each(task, css, tset)
  7741. sched_move_task(task, false);
  7742. scx_cgroup_finish_attach();
  7743. }
  7744. static void cpu_cgroup_cancel_attach(struct cgroup_taskset *tset)
  7745. {
  7746. scx_cgroup_cancel_attach(tset);
  7747. }
  7748. #ifdef CONFIG_UCLAMP_TASK_GROUP
  7749. static void cpu_util_update_eff(struct cgroup_subsys_state *css)
  7750. {
  7751. struct cgroup_subsys_state *top_css = css;
  7752. struct uclamp_se *uc_parent = NULL;
  7753. struct uclamp_se *uc_se = NULL;
  7754. unsigned int eff[UCLAMP_CNT];
  7755. enum uclamp_id clamp_id;
  7756. unsigned int clamps;
  7757. lockdep_assert_held(&uclamp_mutex);
  7758. SCHED_WARN_ON(!rcu_read_lock_held());
  7759. css_for_each_descendant_pre(css, top_css) {
  7760. uc_parent = css_tg(css)->parent
  7761. ? css_tg(css)->parent->uclamp : NULL;
  7762. for_each_clamp_id(clamp_id) {
  7763. /* Assume effective clamps matches requested clamps */
  7764. eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value;
  7765. /* Cap effective clamps with parent's effective clamps */
  7766. if (uc_parent &&
  7767. eff[clamp_id] > uc_parent[clamp_id].value) {
  7768. eff[clamp_id] = uc_parent[clamp_id].value;
  7769. }
  7770. }
  7771. /* Ensure protection is always capped by limit */
  7772. eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]);
  7773. /* Propagate most restrictive effective clamps */
  7774. clamps = 0x0;
  7775. uc_se = css_tg(css)->uclamp;
  7776. for_each_clamp_id(clamp_id) {
  7777. if (eff[clamp_id] == uc_se[clamp_id].value)
  7778. continue;
  7779. uc_se[clamp_id].value = eff[clamp_id];
  7780. uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]);
  7781. clamps |= (0x1 << clamp_id);
  7782. }
  7783. if (!clamps) {
  7784. css = css_rightmost_descendant(css);
  7785. continue;
  7786. }
  7787. /* Immediately update descendants RUNNABLE tasks */
  7788. uclamp_update_active_tasks(css);
  7789. }
  7790. }
  7791. /*
  7792. * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
  7793. * C expression. Since there is no way to convert a macro argument (N) into a
  7794. * character constant, use two levels of macros.
  7795. */
  7796. #define _POW10(exp) ((unsigned int)1e##exp)
  7797. #define POW10(exp) _POW10(exp)
  7798. struct uclamp_request {
  7799. #define UCLAMP_PERCENT_SHIFT 2
  7800. #define UCLAMP_PERCENT_SCALE (100 * POW10(UCLAMP_PERCENT_SHIFT))
  7801. s64 percent;
  7802. u64 util;
  7803. int ret;
  7804. };
  7805. static inline struct uclamp_request
  7806. capacity_from_percent(char *buf)
  7807. {
  7808. struct uclamp_request req = {
  7809. .percent = UCLAMP_PERCENT_SCALE,
  7810. .util = SCHED_CAPACITY_SCALE,
  7811. .ret = 0,
  7812. };
  7813. buf = strim(buf);
  7814. if (strcmp(buf, "max")) {
  7815. req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT,
  7816. &req.percent);
  7817. if (req.ret)
  7818. return req;
  7819. if ((u64)req.percent > UCLAMP_PERCENT_SCALE) {
  7820. req.ret = -ERANGE;
  7821. return req;
  7822. }
  7823. req.util = req.percent << SCHED_CAPACITY_SHIFT;
  7824. req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE);
  7825. }
  7826. return req;
  7827. }
  7828. static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf,
  7829. size_t nbytes, loff_t off,
  7830. enum uclamp_id clamp_id)
  7831. {
  7832. struct uclamp_request req;
  7833. struct task_group *tg;
  7834. req = capacity_from_percent(buf);
  7835. if (req.ret)
  7836. return req.ret;
  7837. static_branch_enable(&sched_uclamp_used);
  7838. guard(mutex)(&uclamp_mutex);
  7839. guard(rcu)();
  7840. tg = css_tg(of_css(of));
  7841. if (tg->uclamp_req[clamp_id].value != req.util)
  7842. uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false);
  7843. /*
  7844. * Because of not recoverable conversion rounding we keep track of the
  7845. * exact requested value
  7846. */
  7847. tg->uclamp_pct[clamp_id] = req.percent;
  7848. /* Update effective clamps to track the most restrictive value */
  7849. cpu_util_update_eff(of_css(of));
  7850. return nbytes;
  7851. }
  7852. static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of,
  7853. char *buf, size_t nbytes,
  7854. loff_t off)
  7855. {
  7856. return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN);
  7857. }
  7858. static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of,
  7859. char *buf, size_t nbytes,
  7860. loff_t off)
  7861. {
  7862. return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX);
  7863. }
  7864. static inline void cpu_uclamp_print(struct seq_file *sf,
  7865. enum uclamp_id clamp_id)
  7866. {
  7867. struct task_group *tg;
  7868. u64 util_clamp;
  7869. u64 percent;
  7870. u32 rem;
  7871. scoped_guard (rcu) {
  7872. tg = css_tg(seq_css(sf));
  7873. util_clamp = tg->uclamp_req[clamp_id].value;
  7874. }
  7875. if (util_clamp == SCHED_CAPACITY_SCALE) {
  7876. seq_puts(sf, "max\n");
  7877. return;
  7878. }
  7879. percent = tg->uclamp_pct[clamp_id];
  7880. percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem);
  7881. seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem);
  7882. }
  7883. static int cpu_uclamp_min_show(struct seq_file *sf, void *v)
  7884. {
  7885. cpu_uclamp_print(sf, UCLAMP_MIN);
  7886. return 0;
  7887. }
  7888. static int cpu_uclamp_max_show(struct seq_file *sf, void *v)
  7889. {
  7890. cpu_uclamp_print(sf, UCLAMP_MAX);
  7891. return 0;
  7892. }
  7893. #endif /* CONFIG_UCLAMP_TASK_GROUP */
  7894. #ifdef CONFIG_GROUP_SCHED_WEIGHT
  7895. static unsigned long tg_weight(struct task_group *tg)
  7896. {
  7897. #ifdef CONFIG_FAIR_GROUP_SCHED
  7898. return scale_load_down(tg->shares);
  7899. #else
  7900. return sched_weight_from_cgroup(tg->scx_weight);
  7901. #endif
  7902. }
  7903. static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
  7904. struct cftype *cftype, u64 shareval)
  7905. {
  7906. int ret;
  7907. if (shareval > scale_load_down(ULONG_MAX))
  7908. shareval = MAX_SHARES;
  7909. ret = sched_group_set_shares(css_tg(css), scale_load(shareval));
  7910. if (!ret)
  7911. scx_group_set_weight(css_tg(css),
  7912. sched_weight_to_cgroup(shareval));
  7913. return ret;
  7914. }
  7915. static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
  7916. struct cftype *cft)
  7917. {
  7918. return tg_weight(css_tg(css));
  7919. }
  7920. #endif /* CONFIG_GROUP_SCHED_WEIGHT */
  7921. #ifdef CONFIG_CFS_BANDWIDTH
  7922. static DEFINE_MUTEX(cfs_constraints_mutex);
  7923. const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
  7924. static const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
  7925. /* More than 203 days if BW_SHIFT equals 20. */
  7926. static const u64 max_cfs_runtime = MAX_BW * NSEC_PER_USEC;
  7927. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
  7928. static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota,
  7929. u64 burst)
  7930. {
  7931. int i, ret = 0, runtime_enabled, runtime_was_enabled;
  7932. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  7933. if (tg == &root_task_group)
  7934. return -EINVAL;
  7935. /*
  7936. * Ensure we have at some amount of bandwidth every period. This is
  7937. * to prevent reaching a state of large arrears when throttled via
  7938. * entity_tick() resulting in prolonged exit starvation.
  7939. */
  7940. if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
  7941. return -EINVAL;
  7942. /*
  7943. * Likewise, bound things on the other side by preventing insane quota
  7944. * periods. This also allows us to normalize in computing quota
  7945. * feasibility.
  7946. */
  7947. if (period > max_cfs_quota_period)
  7948. return -EINVAL;
  7949. /*
  7950. * Bound quota to defend quota against overflow during bandwidth shift.
  7951. */
  7952. if (quota != RUNTIME_INF && quota > max_cfs_runtime)
  7953. return -EINVAL;
  7954. if (quota != RUNTIME_INF && (burst > quota ||
  7955. burst + quota > max_cfs_runtime))
  7956. return -EINVAL;
  7957. /*
  7958. * Prevent race between setting of cfs_rq->runtime_enabled and
  7959. * unthrottle_offline_cfs_rqs().
  7960. */
  7961. guard(cpus_read_lock)();
  7962. guard(mutex)(&cfs_constraints_mutex);
  7963. ret = __cfs_schedulable(tg, period, quota);
  7964. if (ret)
  7965. return ret;
  7966. runtime_enabled = quota != RUNTIME_INF;
  7967. runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
  7968. /*
  7969. * If we need to toggle cfs_bandwidth_used, off->on must occur
  7970. * before making related changes, and on->off must occur afterwards
  7971. */
  7972. if (runtime_enabled && !runtime_was_enabled)
  7973. cfs_bandwidth_usage_inc();
  7974. scoped_guard (raw_spinlock_irq, &cfs_b->lock) {
  7975. cfs_b->period = ns_to_ktime(period);
  7976. cfs_b->quota = quota;
  7977. cfs_b->burst = burst;
  7978. __refill_cfs_bandwidth_runtime(cfs_b);
  7979. /*
  7980. * Restart the period timer (if active) to handle new
  7981. * period expiry:
  7982. */
  7983. if (runtime_enabled)
  7984. start_cfs_bandwidth(cfs_b);
  7985. }
  7986. for_each_online_cpu(i) {
  7987. struct cfs_rq *cfs_rq = tg->cfs_rq[i];
  7988. struct rq *rq = cfs_rq->rq;
  7989. guard(rq_lock_irq)(rq);
  7990. cfs_rq->runtime_enabled = runtime_enabled;
  7991. cfs_rq->runtime_remaining = 0;
  7992. if (cfs_rq->throttled)
  7993. unthrottle_cfs_rq(cfs_rq);
  7994. }
  7995. if (runtime_was_enabled && !runtime_enabled)
  7996. cfs_bandwidth_usage_dec();
  7997. return 0;
  7998. }
  7999. static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
  8000. {
  8001. u64 quota, period, burst;
  8002. period = ktime_to_ns(tg->cfs_bandwidth.period);
  8003. burst = tg->cfs_bandwidth.burst;
  8004. if (cfs_quota_us < 0)
  8005. quota = RUNTIME_INF;
  8006. else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
  8007. quota = (u64)cfs_quota_us * NSEC_PER_USEC;
  8008. else
  8009. return -EINVAL;
  8010. return tg_set_cfs_bandwidth(tg, period, quota, burst);
  8011. }
  8012. static long tg_get_cfs_quota(struct task_group *tg)
  8013. {
  8014. u64 quota_us;
  8015. if (tg->cfs_bandwidth.quota == RUNTIME_INF)
  8016. return -1;
  8017. quota_us = tg->cfs_bandwidth.quota;
  8018. do_div(quota_us, NSEC_PER_USEC);
  8019. return quota_us;
  8020. }
  8021. static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
  8022. {
  8023. u64 quota, period, burst;
  8024. if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
  8025. return -EINVAL;
  8026. period = (u64)cfs_period_us * NSEC_PER_USEC;
  8027. quota = tg->cfs_bandwidth.quota;
  8028. burst = tg->cfs_bandwidth.burst;
  8029. return tg_set_cfs_bandwidth(tg, period, quota, burst);
  8030. }
  8031. static long tg_get_cfs_period(struct task_group *tg)
  8032. {
  8033. u64 cfs_period_us;
  8034. cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
  8035. do_div(cfs_period_us, NSEC_PER_USEC);
  8036. return cfs_period_us;
  8037. }
  8038. static int tg_set_cfs_burst(struct task_group *tg, long cfs_burst_us)
  8039. {
  8040. u64 quota, period, burst;
  8041. if ((u64)cfs_burst_us > U64_MAX / NSEC_PER_USEC)
  8042. return -EINVAL;
  8043. burst = (u64)cfs_burst_us * NSEC_PER_USEC;
  8044. period = ktime_to_ns(tg->cfs_bandwidth.period);
  8045. quota = tg->cfs_bandwidth.quota;
  8046. return tg_set_cfs_bandwidth(tg, period, quota, burst);
  8047. }
  8048. static long tg_get_cfs_burst(struct task_group *tg)
  8049. {
  8050. u64 burst_us;
  8051. burst_us = tg->cfs_bandwidth.burst;
  8052. do_div(burst_us, NSEC_PER_USEC);
  8053. return burst_us;
  8054. }
  8055. static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
  8056. struct cftype *cft)
  8057. {
  8058. return tg_get_cfs_quota(css_tg(css));
  8059. }
  8060. static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
  8061. struct cftype *cftype, s64 cfs_quota_us)
  8062. {
  8063. return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
  8064. }
  8065. static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
  8066. struct cftype *cft)
  8067. {
  8068. return tg_get_cfs_period(css_tg(css));
  8069. }
  8070. static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
  8071. struct cftype *cftype, u64 cfs_period_us)
  8072. {
  8073. return tg_set_cfs_period(css_tg(css), cfs_period_us);
  8074. }
  8075. static u64 cpu_cfs_burst_read_u64(struct cgroup_subsys_state *css,
  8076. struct cftype *cft)
  8077. {
  8078. return tg_get_cfs_burst(css_tg(css));
  8079. }
  8080. static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state *css,
  8081. struct cftype *cftype, u64 cfs_burst_us)
  8082. {
  8083. return tg_set_cfs_burst(css_tg(css), cfs_burst_us);
  8084. }
  8085. struct cfs_schedulable_data {
  8086. struct task_group *tg;
  8087. u64 period, quota;
  8088. };
  8089. /*
  8090. * normalize group quota/period to be quota/max_period
  8091. * note: units are usecs
  8092. */
  8093. static u64 normalize_cfs_quota(struct task_group *tg,
  8094. struct cfs_schedulable_data *d)
  8095. {
  8096. u64 quota, period;
  8097. if (tg == d->tg) {
  8098. period = d->period;
  8099. quota = d->quota;
  8100. } else {
  8101. period = tg_get_cfs_period(tg);
  8102. quota = tg_get_cfs_quota(tg);
  8103. }
  8104. /* note: these should typically be equivalent */
  8105. if (quota == RUNTIME_INF || quota == -1)
  8106. return RUNTIME_INF;
  8107. return to_ratio(period, quota);
  8108. }
  8109. static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
  8110. {
  8111. struct cfs_schedulable_data *d = data;
  8112. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  8113. s64 quota = 0, parent_quota = -1;
  8114. if (!tg->parent) {
  8115. quota = RUNTIME_INF;
  8116. } else {
  8117. struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
  8118. quota = normalize_cfs_quota(tg, d);
  8119. parent_quota = parent_b->hierarchical_quota;
  8120. /*
  8121. * Ensure max(child_quota) <= parent_quota. On cgroup2,
  8122. * always take the non-RUNTIME_INF min. On cgroup1, only
  8123. * inherit when no limit is set. In both cases this is used
  8124. * by the scheduler to determine if a given CFS task has a
  8125. * bandwidth constraint at some higher level.
  8126. */
  8127. if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
  8128. if (quota == RUNTIME_INF)
  8129. quota = parent_quota;
  8130. else if (parent_quota != RUNTIME_INF)
  8131. quota = min(quota, parent_quota);
  8132. } else {
  8133. if (quota == RUNTIME_INF)
  8134. quota = parent_quota;
  8135. else if (parent_quota != RUNTIME_INF && quota > parent_quota)
  8136. return -EINVAL;
  8137. }
  8138. }
  8139. cfs_b->hierarchical_quota = quota;
  8140. return 0;
  8141. }
  8142. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
  8143. {
  8144. struct cfs_schedulable_data data = {
  8145. .tg = tg,
  8146. .period = period,
  8147. .quota = quota,
  8148. };
  8149. if (quota != RUNTIME_INF) {
  8150. do_div(data.period, NSEC_PER_USEC);
  8151. do_div(data.quota, NSEC_PER_USEC);
  8152. }
  8153. guard(rcu)();
  8154. return walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
  8155. }
  8156. static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
  8157. {
  8158. struct task_group *tg = css_tg(seq_css(sf));
  8159. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  8160. seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
  8161. seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
  8162. seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
  8163. if (schedstat_enabled() && tg != &root_task_group) {
  8164. struct sched_statistics *stats;
  8165. u64 ws = 0;
  8166. int i;
  8167. for_each_possible_cpu(i) {
  8168. stats = __schedstats_from_se(tg->se[i]);
  8169. ws += schedstat_val(stats->wait_sum);
  8170. }
  8171. seq_printf(sf, "wait_sum %llu\n", ws);
  8172. }
  8173. seq_printf(sf, "nr_bursts %d\n", cfs_b->nr_burst);
  8174. seq_printf(sf, "burst_time %llu\n", cfs_b->burst_time);
  8175. return 0;
  8176. }
  8177. static u64 throttled_time_self(struct task_group *tg)
  8178. {
  8179. int i;
  8180. u64 total = 0;
  8181. for_each_possible_cpu(i) {
  8182. total += READ_ONCE(tg->cfs_rq[i]->throttled_clock_self_time);
  8183. }
  8184. return total;
  8185. }
  8186. static int cpu_cfs_local_stat_show(struct seq_file *sf, void *v)
  8187. {
  8188. struct task_group *tg = css_tg(seq_css(sf));
  8189. seq_printf(sf, "throttled_time %llu\n", throttled_time_self(tg));
  8190. return 0;
  8191. }
  8192. #endif /* CONFIG_CFS_BANDWIDTH */
  8193. #ifdef CONFIG_RT_GROUP_SCHED
  8194. static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
  8195. struct cftype *cft, s64 val)
  8196. {
  8197. return sched_group_set_rt_runtime(css_tg(css), val);
  8198. }
  8199. static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
  8200. struct cftype *cft)
  8201. {
  8202. return sched_group_rt_runtime(css_tg(css));
  8203. }
  8204. static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
  8205. struct cftype *cftype, u64 rt_period_us)
  8206. {
  8207. return sched_group_set_rt_period(css_tg(css), rt_period_us);
  8208. }
  8209. static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
  8210. struct cftype *cft)
  8211. {
  8212. return sched_group_rt_period(css_tg(css));
  8213. }
  8214. #endif /* CONFIG_RT_GROUP_SCHED */
  8215. #ifdef CONFIG_GROUP_SCHED_WEIGHT
  8216. static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css,
  8217. struct cftype *cft)
  8218. {
  8219. return css_tg(css)->idle;
  8220. }
  8221. static int cpu_idle_write_s64(struct cgroup_subsys_state *css,
  8222. struct cftype *cft, s64 idle)
  8223. {
  8224. int ret;
  8225. ret = sched_group_set_idle(css_tg(css), idle);
  8226. if (!ret)
  8227. scx_group_set_idle(css_tg(css), idle);
  8228. return ret;
  8229. }
  8230. #endif
  8231. static struct cftype cpu_legacy_files[] = {
  8232. #ifdef CONFIG_GROUP_SCHED_WEIGHT
  8233. {
  8234. .name = "shares",
  8235. .read_u64 = cpu_shares_read_u64,
  8236. .write_u64 = cpu_shares_write_u64,
  8237. },
  8238. {
  8239. .name = "idle",
  8240. .read_s64 = cpu_idle_read_s64,
  8241. .write_s64 = cpu_idle_write_s64,
  8242. },
  8243. #endif
  8244. #ifdef CONFIG_CFS_BANDWIDTH
  8245. {
  8246. .name = "cfs_quota_us",
  8247. .read_s64 = cpu_cfs_quota_read_s64,
  8248. .write_s64 = cpu_cfs_quota_write_s64,
  8249. },
  8250. {
  8251. .name = "cfs_period_us",
  8252. .read_u64 = cpu_cfs_period_read_u64,
  8253. .write_u64 = cpu_cfs_period_write_u64,
  8254. },
  8255. {
  8256. .name = "cfs_burst_us",
  8257. .read_u64 = cpu_cfs_burst_read_u64,
  8258. .write_u64 = cpu_cfs_burst_write_u64,
  8259. },
  8260. {
  8261. .name = "stat",
  8262. .seq_show = cpu_cfs_stat_show,
  8263. },
  8264. {
  8265. .name = "stat.local",
  8266. .seq_show = cpu_cfs_local_stat_show,
  8267. },
  8268. #endif
  8269. #ifdef CONFIG_RT_GROUP_SCHED
  8270. {
  8271. .name = "rt_runtime_us",
  8272. .read_s64 = cpu_rt_runtime_read,
  8273. .write_s64 = cpu_rt_runtime_write,
  8274. },
  8275. {
  8276. .name = "rt_period_us",
  8277. .read_u64 = cpu_rt_period_read_uint,
  8278. .write_u64 = cpu_rt_period_write_uint,
  8279. },
  8280. #endif
  8281. #ifdef CONFIG_UCLAMP_TASK_GROUP
  8282. {
  8283. .name = "uclamp.min",
  8284. .flags = CFTYPE_NOT_ON_ROOT,
  8285. .seq_show = cpu_uclamp_min_show,
  8286. .write = cpu_uclamp_min_write,
  8287. },
  8288. {
  8289. .name = "uclamp.max",
  8290. .flags = CFTYPE_NOT_ON_ROOT,
  8291. .seq_show = cpu_uclamp_max_show,
  8292. .write = cpu_uclamp_max_write,
  8293. },
  8294. #endif
  8295. { } /* Terminate */
  8296. };
  8297. static int cpu_extra_stat_show(struct seq_file *sf,
  8298. struct cgroup_subsys_state *css)
  8299. {
  8300. #ifdef CONFIG_CFS_BANDWIDTH
  8301. {
  8302. struct task_group *tg = css_tg(css);
  8303. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  8304. u64 throttled_usec, burst_usec;
  8305. throttled_usec = cfs_b->throttled_time;
  8306. do_div(throttled_usec, NSEC_PER_USEC);
  8307. burst_usec = cfs_b->burst_time;
  8308. do_div(burst_usec, NSEC_PER_USEC);
  8309. seq_printf(sf, "nr_periods %d\n"
  8310. "nr_throttled %d\n"
  8311. "throttled_usec %llu\n"
  8312. "nr_bursts %d\n"
  8313. "burst_usec %llu\n",
  8314. cfs_b->nr_periods, cfs_b->nr_throttled,
  8315. throttled_usec, cfs_b->nr_burst, burst_usec);
  8316. }
  8317. #endif
  8318. return 0;
  8319. }
  8320. static int cpu_local_stat_show(struct seq_file *sf,
  8321. struct cgroup_subsys_state *css)
  8322. {
  8323. #ifdef CONFIG_CFS_BANDWIDTH
  8324. {
  8325. struct task_group *tg = css_tg(css);
  8326. u64 throttled_self_usec;
  8327. throttled_self_usec = throttled_time_self(tg);
  8328. do_div(throttled_self_usec, NSEC_PER_USEC);
  8329. seq_printf(sf, "throttled_usec %llu\n",
  8330. throttled_self_usec);
  8331. }
  8332. #endif
  8333. return 0;
  8334. }
  8335. #ifdef CONFIG_GROUP_SCHED_WEIGHT
  8336. static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
  8337. struct cftype *cft)
  8338. {
  8339. return sched_weight_to_cgroup(tg_weight(css_tg(css)));
  8340. }
  8341. static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
  8342. struct cftype *cft, u64 cgrp_weight)
  8343. {
  8344. unsigned long weight;
  8345. int ret;
  8346. if (cgrp_weight < CGROUP_WEIGHT_MIN || cgrp_weight > CGROUP_WEIGHT_MAX)
  8347. return -ERANGE;
  8348. weight = sched_weight_from_cgroup(cgrp_weight);
  8349. ret = sched_group_set_shares(css_tg(css), scale_load(weight));
  8350. if (!ret)
  8351. scx_group_set_weight(css_tg(css), cgrp_weight);
  8352. return ret;
  8353. }
  8354. static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
  8355. struct cftype *cft)
  8356. {
  8357. unsigned long weight = tg_weight(css_tg(css));
  8358. int last_delta = INT_MAX;
  8359. int prio, delta;
  8360. /* find the closest nice value to the current weight */
  8361. for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
  8362. delta = abs(sched_prio_to_weight[prio] - weight);
  8363. if (delta >= last_delta)
  8364. break;
  8365. last_delta = delta;
  8366. }
  8367. return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
  8368. }
  8369. static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
  8370. struct cftype *cft, s64 nice)
  8371. {
  8372. unsigned long weight;
  8373. int idx, ret;
  8374. if (nice < MIN_NICE || nice > MAX_NICE)
  8375. return -ERANGE;
  8376. idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
  8377. idx = array_index_nospec(idx, 40);
  8378. weight = sched_prio_to_weight[idx];
  8379. ret = sched_group_set_shares(css_tg(css), scale_load(weight));
  8380. if (!ret)
  8381. scx_group_set_weight(css_tg(css),
  8382. sched_weight_to_cgroup(weight));
  8383. return ret;
  8384. }
  8385. #endif /* CONFIG_GROUP_SCHED_WEIGHT */
  8386. static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
  8387. long period, long quota)
  8388. {
  8389. if (quota < 0)
  8390. seq_puts(sf, "max");
  8391. else
  8392. seq_printf(sf, "%ld", quota);
  8393. seq_printf(sf, " %ld\n", period);
  8394. }
  8395. /* caller should put the current value in *@periodp before calling */
  8396. static int __maybe_unused cpu_period_quota_parse(char *buf,
  8397. u64 *periodp, u64 *quotap)
  8398. {
  8399. char tok[21]; /* U64_MAX */
  8400. if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
  8401. return -EINVAL;
  8402. *periodp *= NSEC_PER_USEC;
  8403. if (sscanf(tok, "%llu", quotap))
  8404. *quotap *= NSEC_PER_USEC;
  8405. else if (!strcmp(tok, "max"))
  8406. *quotap = RUNTIME_INF;
  8407. else
  8408. return -EINVAL;
  8409. return 0;
  8410. }
  8411. #ifdef CONFIG_CFS_BANDWIDTH
  8412. static int cpu_max_show(struct seq_file *sf, void *v)
  8413. {
  8414. struct task_group *tg = css_tg(seq_css(sf));
  8415. cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
  8416. return 0;
  8417. }
  8418. static ssize_t cpu_max_write(struct kernfs_open_file *of,
  8419. char *buf, size_t nbytes, loff_t off)
  8420. {
  8421. struct task_group *tg = css_tg(of_css(of));
  8422. u64 period = tg_get_cfs_period(tg);
  8423. u64 burst = tg->cfs_bandwidth.burst;
  8424. u64 quota;
  8425. int ret;
  8426. ret = cpu_period_quota_parse(buf, &period, &quota);
  8427. if (!ret)
  8428. ret = tg_set_cfs_bandwidth(tg, period, quota, burst);
  8429. return ret ?: nbytes;
  8430. }
  8431. #endif
  8432. static struct cftype cpu_files[] = {
  8433. #ifdef CONFIG_GROUP_SCHED_WEIGHT
  8434. {
  8435. .name = "weight",
  8436. .flags = CFTYPE_NOT_ON_ROOT,
  8437. .read_u64 = cpu_weight_read_u64,
  8438. .write_u64 = cpu_weight_write_u64,
  8439. },
  8440. {
  8441. .name = "weight.nice",
  8442. .flags = CFTYPE_NOT_ON_ROOT,
  8443. .read_s64 = cpu_weight_nice_read_s64,
  8444. .write_s64 = cpu_weight_nice_write_s64,
  8445. },
  8446. {
  8447. .name = "idle",
  8448. .flags = CFTYPE_NOT_ON_ROOT,
  8449. .read_s64 = cpu_idle_read_s64,
  8450. .write_s64 = cpu_idle_write_s64,
  8451. },
  8452. #endif
  8453. #ifdef CONFIG_CFS_BANDWIDTH
  8454. {
  8455. .name = "max",
  8456. .flags = CFTYPE_NOT_ON_ROOT,
  8457. .seq_show = cpu_max_show,
  8458. .write = cpu_max_write,
  8459. },
  8460. {
  8461. .name = "max.burst",
  8462. .flags = CFTYPE_NOT_ON_ROOT,
  8463. .read_u64 = cpu_cfs_burst_read_u64,
  8464. .write_u64 = cpu_cfs_burst_write_u64,
  8465. },
  8466. #endif
  8467. #ifdef CONFIG_UCLAMP_TASK_GROUP
  8468. {
  8469. .name = "uclamp.min",
  8470. .flags = CFTYPE_NOT_ON_ROOT,
  8471. .seq_show = cpu_uclamp_min_show,
  8472. .write = cpu_uclamp_min_write,
  8473. },
  8474. {
  8475. .name = "uclamp.max",
  8476. .flags = CFTYPE_NOT_ON_ROOT,
  8477. .seq_show = cpu_uclamp_max_show,
  8478. .write = cpu_uclamp_max_write,
  8479. },
  8480. #endif
  8481. { } /* terminate */
  8482. };
  8483. struct cgroup_subsys cpu_cgrp_subsys = {
  8484. .css_alloc = cpu_cgroup_css_alloc,
  8485. .css_online = cpu_cgroup_css_online,
  8486. .css_offline = cpu_cgroup_css_offline,
  8487. .css_released = cpu_cgroup_css_released,
  8488. .css_free = cpu_cgroup_css_free,
  8489. .css_extra_stat_show = cpu_extra_stat_show,
  8490. .css_local_stat_show = cpu_local_stat_show,
  8491. .can_attach = cpu_cgroup_can_attach,
  8492. .attach = cpu_cgroup_attach,
  8493. .cancel_attach = cpu_cgroup_cancel_attach,
  8494. .legacy_cftypes = cpu_legacy_files,
  8495. .dfl_cftypes = cpu_files,
  8496. .early_init = true,
  8497. .threaded = true,
  8498. };
  8499. #endif /* CONFIG_CGROUP_SCHED */
  8500. void dump_cpu_task(int cpu)
  8501. {
  8502. if (in_hardirq() && cpu == smp_processor_id()) {
  8503. struct pt_regs *regs;
  8504. regs = get_irq_regs();
  8505. if (regs) {
  8506. show_regs(regs);
  8507. return;
  8508. }
  8509. }
  8510. if (trigger_single_cpu_backtrace(cpu))
  8511. return;
  8512. pr_info("Task dump for CPU %d:\n", cpu);
  8513. sched_show_task(cpu_curr(cpu));
  8514. }
  8515. /*
  8516. * Nice levels are multiplicative, with a gentle 10% change for every
  8517. * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
  8518. * nice 1, it will get ~10% less CPU time than another CPU-bound task
  8519. * that remained on nice 0.
  8520. *
  8521. * The "10% effect" is relative and cumulative: from _any_ nice level,
  8522. * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
  8523. * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
  8524. * If a task goes up by ~10% and another task goes down by ~10% then
  8525. * the relative distance between them is ~25%.)
  8526. */
  8527. const int sched_prio_to_weight[40] = {
  8528. /* -20 */ 88761, 71755, 56483, 46273, 36291,
  8529. /* -15 */ 29154, 23254, 18705, 14949, 11916,
  8530. /* -10 */ 9548, 7620, 6100, 4904, 3906,
  8531. /* -5 */ 3121, 2501, 1991, 1586, 1277,
  8532. /* 0 */ 1024, 820, 655, 526, 423,
  8533. /* 5 */ 335, 272, 215, 172, 137,
  8534. /* 10 */ 110, 87, 70, 56, 45,
  8535. /* 15 */ 36, 29, 23, 18, 15,
  8536. };
  8537. /*
  8538. * Inverse (2^32/x) values of the sched_prio_to_weight[] array, pre-calculated.
  8539. *
  8540. * In cases where the weight does not change often, we can use the
  8541. * pre-calculated inverse to speed up arithmetics by turning divisions
  8542. * into multiplications:
  8543. */
  8544. const u32 sched_prio_to_wmult[40] = {
  8545. /* -20 */ 48388, 59856, 76040, 92818, 118348,
  8546. /* -15 */ 147320, 184698, 229616, 287308, 360437,
  8547. /* -10 */ 449829, 563644, 704093, 875809, 1099582,
  8548. /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
  8549. /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
  8550. /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
  8551. /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
  8552. /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
  8553. };
  8554. void call_trace_sched_update_nr_running(struct rq *rq, int count)
  8555. {
  8556. trace_sched_update_nr_running_tp(rq, count);
  8557. }
  8558. #ifdef CONFIG_SCHED_MM_CID
  8559. /*
  8560. * @cid_lock: Guarantee forward-progress of cid allocation.
  8561. *
  8562. * Concurrency ID allocation within a bitmap is mostly lock-free. The cid_lock
  8563. * is only used when contention is detected by the lock-free allocation so
  8564. * forward progress can be guaranteed.
  8565. */
  8566. DEFINE_RAW_SPINLOCK(cid_lock);
  8567. /*
  8568. * @use_cid_lock: Select cid allocation behavior: lock-free vs spinlock.
  8569. *
  8570. * When @use_cid_lock is 0, the cid allocation is lock-free. When contention is
  8571. * detected, it is set to 1 to ensure that all newly coming allocations are
  8572. * serialized by @cid_lock until the allocation which detected contention
  8573. * completes and sets @use_cid_lock back to 0. This guarantees forward progress
  8574. * of a cid allocation.
  8575. */
  8576. int use_cid_lock;
  8577. /*
  8578. * mm_cid remote-clear implements a lock-free algorithm to clear per-mm/cpu cid
  8579. * concurrently with respect to the execution of the source runqueue context
  8580. * switch.
  8581. *
  8582. * There is one basic properties we want to guarantee here:
  8583. *
  8584. * (1) Remote-clear should _never_ mark a per-cpu cid UNSET when it is actively
  8585. * used by a task. That would lead to concurrent allocation of the cid and
  8586. * userspace corruption.
  8587. *
  8588. * Provide this guarantee by introducing a Dekker memory ordering to guarantee
  8589. * that a pair of loads observe at least one of a pair of stores, which can be
  8590. * shown as:
  8591. *
  8592. * X = Y = 0
  8593. *
  8594. * w[X]=1 w[Y]=1
  8595. * MB MB
  8596. * r[Y]=y r[X]=x
  8597. *
  8598. * Which guarantees that x==0 && y==0 is impossible. But rather than using
  8599. * values 0 and 1, this algorithm cares about specific state transitions of the
  8600. * runqueue current task (as updated by the scheduler context switch), and the
  8601. * per-mm/cpu cid value.
  8602. *
  8603. * Let's introduce task (Y) which has task->mm == mm and task (N) which has
  8604. * task->mm != mm for the rest of the discussion. There are two scheduler state
  8605. * transitions on context switch we care about:
  8606. *
  8607. * (TSA) Store to rq->curr with transition from (N) to (Y)
  8608. *
  8609. * (TSB) Store to rq->curr with transition from (Y) to (N)
  8610. *
  8611. * On the remote-clear side, there is one transition we care about:
  8612. *
  8613. * (TMA) cmpxchg to *pcpu_cid to set the LAZY flag
  8614. *
  8615. * There is also a transition to UNSET state which can be performed from all
  8616. * sides (scheduler, remote-clear). It is always performed with a cmpxchg which
  8617. * guarantees that only a single thread will succeed:
  8618. *
  8619. * (TMB) cmpxchg to *pcpu_cid to mark UNSET
  8620. *
  8621. * Just to be clear, what we do _not_ want to happen is a transition to UNSET
  8622. * when a thread is actively using the cid (property (1)).
  8623. *
  8624. * Let's looks at the relevant combinations of TSA/TSB, and TMA transitions.
  8625. *
  8626. * Scenario A) (TSA)+(TMA) (from next task perspective)
  8627. *
  8628. * CPU0 CPU1
  8629. *
  8630. * Context switch CS-1 Remote-clear
  8631. * - store to rq->curr: (N)->(Y) (TSA) - cmpxchg to *pcpu_id to LAZY (TMA)
  8632. * (implied barrier after cmpxchg)
  8633. * - switch_mm_cid()
  8634. * - memory barrier (see switch_mm_cid()
  8635. * comment explaining how this barrier
  8636. * is combined with other scheduler
  8637. * barriers)
  8638. * - mm_cid_get (next)
  8639. * - READ_ONCE(*pcpu_cid) - rcu_dereference(src_rq->curr)
  8640. *
  8641. * This Dekker ensures that either task (Y) is observed by the
  8642. * rcu_dereference() or the LAZY flag is observed by READ_ONCE(), or both are
  8643. * observed.
  8644. *
  8645. * If task (Y) store is observed by rcu_dereference(), it means that there is
  8646. * still an active task on the cpu. Remote-clear will therefore not transition
  8647. * to UNSET, which fulfills property (1).
  8648. *
  8649. * If task (Y) is not observed, but the lazy flag is observed by READ_ONCE(),
  8650. * it will move its state to UNSET, which clears the percpu cid perhaps
  8651. * uselessly (which is not an issue for correctness). Because task (Y) is not
  8652. * observed, CPU1 can move ahead to set the state to UNSET. Because moving
  8653. * state to UNSET is done with a cmpxchg expecting that the old state has the
  8654. * LAZY flag set, only one thread will successfully UNSET.
  8655. *
  8656. * If both states (LAZY flag and task (Y)) are observed, the thread on CPU0
  8657. * will observe the LAZY flag and transition to UNSET (perhaps uselessly), and
  8658. * CPU1 will observe task (Y) and do nothing more, which is fine.
  8659. *
  8660. * What we are effectively preventing with this Dekker is a scenario where
  8661. * neither LAZY flag nor store (Y) are observed, which would fail property (1)
  8662. * because this would UNSET a cid which is actively used.
  8663. */
  8664. void sched_mm_cid_migrate_from(struct task_struct *t)
  8665. {
  8666. t->migrate_from_cpu = task_cpu(t);
  8667. }
  8668. static
  8669. int __sched_mm_cid_migrate_from_fetch_cid(struct rq *src_rq,
  8670. struct task_struct *t,
  8671. struct mm_cid *src_pcpu_cid)
  8672. {
  8673. struct mm_struct *mm = t->mm;
  8674. struct task_struct *src_task;
  8675. int src_cid, last_mm_cid;
  8676. if (!mm)
  8677. return -1;
  8678. last_mm_cid = t->last_mm_cid;
  8679. /*
  8680. * If the migrated task has no last cid, or if the current
  8681. * task on src rq uses the cid, it means the source cid does not need
  8682. * to be moved to the destination cpu.
  8683. */
  8684. if (last_mm_cid == -1)
  8685. return -1;
  8686. src_cid = READ_ONCE(src_pcpu_cid->cid);
  8687. if (!mm_cid_is_valid(src_cid) || last_mm_cid != src_cid)
  8688. return -1;
  8689. /*
  8690. * If we observe an active task using the mm on this rq, it means we
  8691. * are not the last task to be migrated from this cpu for this mm, so
  8692. * there is no need to move src_cid to the destination cpu.
  8693. */
  8694. guard(rcu)();
  8695. src_task = rcu_dereference(src_rq->curr);
  8696. if (READ_ONCE(src_task->mm_cid_active) && src_task->mm == mm) {
  8697. t->last_mm_cid = -1;
  8698. return -1;
  8699. }
  8700. return src_cid;
  8701. }
  8702. static
  8703. int __sched_mm_cid_migrate_from_try_steal_cid(struct rq *src_rq,
  8704. struct task_struct *t,
  8705. struct mm_cid *src_pcpu_cid,
  8706. int src_cid)
  8707. {
  8708. struct task_struct *src_task;
  8709. struct mm_struct *mm = t->mm;
  8710. int lazy_cid;
  8711. if (src_cid == -1)
  8712. return -1;
  8713. /*
  8714. * Attempt to clear the source cpu cid to move it to the destination
  8715. * cpu.
  8716. */
  8717. lazy_cid = mm_cid_set_lazy_put(src_cid);
  8718. if (!try_cmpxchg(&src_pcpu_cid->cid, &src_cid, lazy_cid))
  8719. return -1;
  8720. /*
  8721. * The implicit barrier after cmpxchg per-mm/cpu cid before loading
  8722. * rq->curr->mm matches the scheduler barrier in context_switch()
  8723. * between store to rq->curr and load of prev and next task's
  8724. * per-mm/cpu cid.
  8725. *
  8726. * The implicit barrier after cmpxchg per-mm/cpu cid before loading
  8727. * rq->curr->mm_cid_active matches the barrier in
  8728. * sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and
  8729. * sched_mm_cid_after_execve() between store to t->mm_cid_active and
  8730. * load of per-mm/cpu cid.
  8731. */
  8732. /*
  8733. * If we observe an active task using the mm on this rq after setting
  8734. * the lazy-put flag, this task will be responsible for transitioning
  8735. * from lazy-put flag set to MM_CID_UNSET.
  8736. */
  8737. scoped_guard (rcu) {
  8738. src_task = rcu_dereference(src_rq->curr);
  8739. if (READ_ONCE(src_task->mm_cid_active) && src_task->mm == mm) {
  8740. /*
  8741. * We observed an active task for this mm, there is therefore
  8742. * no point in moving this cid to the destination cpu.
  8743. */
  8744. t->last_mm_cid = -1;
  8745. return -1;
  8746. }
  8747. }
  8748. /*
  8749. * The src_cid is unused, so it can be unset.
  8750. */
  8751. if (!try_cmpxchg(&src_pcpu_cid->cid, &lazy_cid, MM_CID_UNSET))
  8752. return -1;
  8753. return src_cid;
  8754. }
  8755. /*
  8756. * Migration to dst cpu. Called with dst_rq lock held.
  8757. * Interrupts are disabled, which keeps the window of cid ownership without the
  8758. * source rq lock held small.
  8759. */
  8760. void sched_mm_cid_migrate_to(struct rq *dst_rq, struct task_struct *t)
  8761. {
  8762. struct mm_cid *src_pcpu_cid, *dst_pcpu_cid;
  8763. struct mm_struct *mm = t->mm;
  8764. int src_cid, dst_cid, src_cpu;
  8765. struct rq *src_rq;
  8766. lockdep_assert_rq_held(dst_rq);
  8767. if (!mm)
  8768. return;
  8769. src_cpu = t->migrate_from_cpu;
  8770. if (src_cpu == -1) {
  8771. t->last_mm_cid = -1;
  8772. return;
  8773. }
  8774. /*
  8775. * Move the src cid if the dst cid is unset. This keeps id
  8776. * allocation closest to 0 in cases where few threads migrate around
  8777. * many CPUs.
  8778. *
  8779. * If destination cid is already set, we may have to just clear
  8780. * the src cid to ensure compactness in frequent migrations
  8781. * scenarios.
  8782. *
  8783. * It is not useful to clear the src cid when the number of threads is
  8784. * greater or equal to the number of allowed CPUs, because user-space
  8785. * can expect that the number of allowed cids can reach the number of
  8786. * allowed CPUs.
  8787. */
  8788. dst_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu_of(dst_rq));
  8789. dst_cid = READ_ONCE(dst_pcpu_cid->cid);
  8790. if (!mm_cid_is_unset(dst_cid) &&
  8791. atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)
  8792. return;
  8793. src_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, src_cpu);
  8794. src_rq = cpu_rq(src_cpu);
  8795. src_cid = __sched_mm_cid_migrate_from_fetch_cid(src_rq, t, src_pcpu_cid);
  8796. if (src_cid == -1)
  8797. return;
  8798. src_cid = __sched_mm_cid_migrate_from_try_steal_cid(src_rq, t, src_pcpu_cid,
  8799. src_cid);
  8800. if (src_cid == -1)
  8801. return;
  8802. if (!mm_cid_is_unset(dst_cid)) {
  8803. __mm_cid_put(mm, src_cid);
  8804. return;
  8805. }
  8806. /* Move src_cid to dst cpu. */
  8807. mm_cid_snapshot_time(dst_rq, mm);
  8808. WRITE_ONCE(dst_pcpu_cid->cid, src_cid);
  8809. }
  8810. static void sched_mm_cid_remote_clear(struct mm_struct *mm, struct mm_cid *pcpu_cid,
  8811. int cpu)
  8812. {
  8813. struct rq *rq = cpu_rq(cpu);
  8814. struct task_struct *t;
  8815. int cid, lazy_cid;
  8816. cid = READ_ONCE(pcpu_cid->cid);
  8817. if (!mm_cid_is_valid(cid))
  8818. return;
  8819. /*
  8820. * Clear the cpu cid if it is set to keep cid allocation compact. If
  8821. * there happens to be other tasks left on the source cpu using this
  8822. * mm, the next task using this mm will reallocate its cid on context
  8823. * switch.
  8824. */
  8825. lazy_cid = mm_cid_set_lazy_put(cid);
  8826. if (!try_cmpxchg(&pcpu_cid->cid, &cid, lazy_cid))
  8827. return;
  8828. /*
  8829. * The implicit barrier after cmpxchg per-mm/cpu cid before loading
  8830. * rq->curr->mm matches the scheduler barrier in context_switch()
  8831. * between store to rq->curr and load of prev and next task's
  8832. * per-mm/cpu cid.
  8833. *
  8834. * The implicit barrier after cmpxchg per-mm/cpu cid before loading
  8835. * rq->curr->mm_cid_active matches the barrier in
  8836. * sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and
  8837. * sched_mm_cid_after_execve() between store to t->mm_cid_active and
  8838. * load of per-mm/cpu cid.
  8839. */
  8840. /*
  8841. * If we observe an active task using the mm on this rq after setting
  8842. * the lazy-put flag, that task will be responsible for transitioning
  8843. * from lazy-put flag set to MM_CID_UNSET.
  8844. */
  8845. scoped_guard (rcu) {
  8846. t = rcu_dereference(rq->curr);
  8847. if (READ_ONCE(t->mm_cid_active) && t->mm == mm)
  8848. return;
  8849. }
  8850. /*
  8851. * The cid is unused, so it can be unset.
  8852. * Disable interrupts to keep the window of cid ownership without rq
  8853. * lock small.
  8854. */
  8855. scoped_guard (irqsave) {
  8856. if (try_cmpxchg(&pcpu_cid->cid, &lazy_cid, MM_CID_UNSET))
  8857. __mm_cid_put(mm, cid);
  8858. }
  8859. }
  8860. static void sched_mm_cid_remote_clear_old(struct mm_struct *mm, int cpu)
  8861. {
  8862. struct rq *rq = cpu_rq(cpu);
  8863. struct mm_cid *pcpu_cid;
  8864. struct task_struct *curr;
  8865. u64 rq_clock;
  8866. /*
  8867. * rq->clock load is racy on 32-bit but one spurious clear once in a
  8868. * while is irrelevant.
  8869. */
  8870. rq_clock = READ_ONCE(rq->clock);
  8871. pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
  8872. /*
  8873. * In order to take care of infrequently scheduled tasks, bump the time
  8874. * snapshot associated with this cid if an active task using the mm is
  8875. * observed on this rq.
  8876. */
  8877. scoped_guard (rcu) {
  8878. curr = rcu_dereference(rq->curr);
  8879. if (READ_ONCE(curr->mm_cid_active) && curr->mm == mm) {
  8880. WRITE_ONCE(pcpu_cid->time, rq_clock);
  8881. return;
  8882. }
  8883. }
  8884. if (rq_clock < pcpu_cid->time + SCHED_MM_CID_PERIOD_NS)
  8885. return;
  8886. sched_mm_cid_remote_clear(mm, pcpu_cid, cpu);
  8887. }
  8888. static void sched_mm_cid_remote_clear_weight(struct mm_struct *mm, int cpu,
  8889. int weight)
  8890. {
  8891. struct mm_cid *pcpu_cid;
  8892. int cid;
  8893. pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
  8894. cid = READ_ONCE(pcpu_cid->cid);
  8895. if (!mm_cid_is_valid(cid) || cid < weight)
  8896. return;
  8897. sched_mm_cid_remote_clear(mm, pcpu_cid, cpu);
  8898. }
  8899. static void task_mm_cid_work(struct callback_head *work)
  8900. {
  8901. unsigned long now = jiffies, old_scan, next_scan;
  8902. struct task_struct *t = current;
  8903. struct cpumask *cidmask;
  8904. struct mm_struct *mm;
  8905. int weight, cpu;
  8906. SCHED_WARN_ON(t != container_of(work, struct task_struct, cid_work));
  8907. work->next = work; /* Prevent double-add */
  8908. if (t->flags & PF_EXITING)
  8909. return;
  8910. mm = t->mm;
  8911. if (!mm)
  8912. return;
  8913. old_scan = READ_ONCE(mm->mm_cid_next_scan);
  8914. next_scan = now + msecs_to_jiffies(MM_CID_SCAN_DELAY);
  8915. if (!old_scan) {
  8916. unsigned long res;
  8917. res = cmpxchg(&mm->mm_cid_next_scan, old_scan, next_scan);
  8918. if (res != old_scan)
  8919. old_scan = res;
  8920. else
  8921. old_scan = next_scan;
  8922. }
  8923. if (time_before(now, old_scan))
  8924. return;
  8925. if (!try_cmpxchg(&mm->mm_cid_next_scan, &old_scan, next_scan))
  8926. return;
  8927. cidmask = mm_cidmask(mm);
  8928. /* Clear cids that were not recently used. */
  8929. for_each_possible_cpu(cpu)
  8930. sched_mm_cid_remote_clear_old(mm, cpu);
  8931. weight = cpumask_weight(cidmask);
  8932. /*
  8933. * Clear cids that are greater or equal to the cidmask weight to
  8934. * recompact it.
  8935. */
  8936. for_each_possible_cpu(cpu)
  8937. sched_mm_cid_remote_clear_weight(mm, cpu, weight);
  8938. }
  8939. void init_sched_mm_cid(struct task_struct *t)
  8940. {
  8941. struct mm_struct *mm = t->mm;
  8942. int mm_users = 0;
  8943. if (mm) {
  8944. mm_users = atomic_read(&mm->mm_users);
  8945. if (mm_users == 1)
  8946. mm->mm_cid_next_scan = jiffies + msecs_to_jiffies(MM_CID_SCAN_DELAY);
  8947. }
  8948. t->cid_work.next = &t->cid_work; /* Protect against double add */
  8949. init_task_work(&t->cid_work, task_mm_cid_work);
  8950. }
  8951. void task_tick_mm_cid(struct rq *rq, struct task_struct *curr)
  8952. {
  8953. struct callback_head *work = &curr->cid_work;
  8954. unsigned long now = jiffies;
  8955. if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) ||
  8956. work->next != work)
  8957. return;
  8958. if (time_before(now, READ_ONCE(curr->mm->mm_cid_next_scan)))
  8959. return;
  8960. /* No page allocation under rq lock */
  8961. task_work_add(curr, work, TWA_RESUME | TWAF_NO_ALLOC);
  8962. }
  8963. void sched_mm_cid_exit_signals(struct task_struct *t)
  8964. {
  8965. struct mm_struct *mm = t->mm;
  8966. struct rq *rq;
  8967. if (!mm)
  8968. return;
  8969. preempt_disable();
  8970. rq = this_rq();
  8971. guard(rq_lock_irqsave)(rq);
  8972. preempt_enable_no_resched(); /* holding spinlock */
  8973. WRITE_ONCE(t->mm_cid_active, 0);
  8974. /*
  8975. * Store t->mm_cid_active before loading per-mm/cpu cid.
  8976. * Matches barrier in sched_mm_cid_remote_clear_old().
  8977. */
  8978. smp_mb();
  8979. mm_cid_put(mm);
  8980. t->last_mm_cid = t->mm_cid = -1;
  8981. }
  8982. void sched_mm_cid_before_execve(struct task_struct *t)
  8983. {
  8984. struct mm_struct *mm = t->mm;
  8985. struct rq *rq;
  8986. if (!mm)
  8987. return;
  8988. preempt_disable();
  8989. rq = this_rq();
  8990. guard(rq_lock_irqsave)(rq);
  8991. preempt_enable_no_resched(); /* holding spinlock */
  8992. WRITE_ONCE(t->mm_cid_active, 0);
  8993. /*
  8994. * Store t->mm_cid_active before loading per-mm/cpu cid.
  8995. * Matches barrier in sched_mm_cid_remote_clear_old().
  8996. */
  8997. smp_mb();
  8998. mm_cid_put(mm);
  8999. t->last_mm_cid = t->mm_cid = -1;
  9000. }
  9001. void sched_mm_cid_after_execve(struct task_struct *t)
  9002. {
  9003. struct mm_struct *mm = t->mm;
  9004. struct rq *rq;
  9005. if (!mm)
  9006. return;
  9007. preempt_disable();
  9008. rq = this_rq();
  9009. scoped_guard (rq_lock_irqsave, rq) {
  9010. preempt_enable_no_resched(); /* holding spinlock */
  9011. WRITE_ONCE(t->mm_cid_active, 1);
  9012. /*
  9013. * Store t->mm_cid_active before loading per-mm/cpu cid.
  9014. * Matches barrier in sched_mm_cid_remote_clear_old().
  9015. */
  9016. smp_mb();
  9017. t->last_mm_cid = t->mm_cid = mm_cid_get(rq, mm);
  9018. }
  9019. rseq_set_notify_resume(t);
  9020. }
  9021. void sched_mm_cid_fork(struct task_struct *t)
  9022. {
  9023. WARN_ON_ONCE(!t->mm || t->mm_cid != -1);
  9024. t->mm_cid_active = 1;
  9025. }
  9026. #endif
  9027. #ifdef CONFIG_SCHED_CLASS_EXT
  9028. void sched_deq_and_put_task(struct task_struct *p, int queue_flags,
  9029. struct sched_enq_and_set_ctx *ctx)
  9030. {
  9031. struct rq *rq = task_rq(p);
  9032. lockdep_assert_rq_held(rq);
  9033. *ctx = (struct sched_enq_and_set_ctx){
  9034. .p = p,
  9035. .queue_flags = queue_flags,
  9036. .queued = task_on_rq_queued(p),
  9037. .running = task_current(rq, p),
  9038. };
  9039. update_rq_clock(rq);
  9040. if (ctx->queued)
  9041. dequeue_task(rq, p, queue_flags | DEQUEUE_NOCLOCK);
  9042. if (ctx->running)
  9043. put_prev_task(rq, p);
  9044. }
  9045. void sched_enq_and_set_task(struct sched_enq_and_set_ctx *ctx)
  9046. {
  9047. struct rq *rq = task_rq(ctx->p);
  9048. lockdep_assert_rq_held(rq);
  9049. if (ctx->queued)
  9050. enqueue_task(rq, ctx->p, ctx->queue_flags | ENQUEUE_NOCLOCK);
  9051. if (ctx->running)
  9052. set_next_task(rq, ctx->p);
  9053. }
  9054. #endif /* CONFIG_SCHED_CLASS_EXT */