core.c 293 KB

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