core.c 174 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109
  1. /*
  2. * kernel/sched/core.c
  3. *
  4. * Core kernel scheduler code and related syscalls
  5. *
  6. * Copyright (C) 1991-2002 Linus Torvalds
  7. */
  8. #include "sched.h"
  9. #include <linux/nospec.h>
  10. #include <linux/kcov.h>
  11. #include <asm/switch_to.h>
  12. #include <asm/tlb.h>
  13. #include "../workqueue_internal.h"
  14. #include "../smpboot.h"
  15. #include "pelt.h"
  16. #define CREATE_TRACE_POINTS
  17. #include <trace/events/sched.h>
  18. DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
  19. #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_JUMP_LABEL)
  20. /*
  21. * Debugging: various feature bits
  22. *
  23. * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
  24. * sysctl_sched_features, defined in sched.h, to allow constants propagation
  25. * at compile time and compiler optimization based on features default.
  26. */
  27. #define SCHED_FEAT(name, enabled) \
  28. (1UL << __SCHED_FEAT_##name) * enabled |
  29. const_debug unsigned int sysctl_sched_features =
  30. #include "features.h"
  31. 0;
  32. #undef SCHED_FEAT
  33. #endif
  34. /*
  35. * Number of tasks to iterate in a single balance run.
  36. * Limited because this is done with IRQs disabled.
  37. */
  38. const_debug unsigned int sysctl_sched_nr_migrate = 32;
  39. /*
  40. * period over which we measure -rt task CPU usage in us.
  41. * default: 1s
  42. */
  43. unsigned int sysctl_sched_rt_period = 1000000;
  44. __read_mostly int scheduler_running;
  45. /*
  46. * part of the period that we allow rt tasks to run in us.
  47. * default: 0.95s
  48. */
  49. int sysctl_sched_rt_runtime = 950000;
  50. /*
  51. * __task_rq_lock - lock the rq @p resides on.
  52. */
  53. struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  54. __acquires(rq->lock)
  55. {
  56. struct rq *rq;
  57. lockdep_assert_held(&p->pi_lock);
  58. for (;;) {
  59. rq = task_rq(p);
  60. raw_spin_lock(&rq->lock);
  61. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  62. rq_pin_lock(rq, rf);
  63. return rq;
  64. }
  65. raw_spin_unlock(&rq->lock);
  66. while (unlikely(task_on_rq_migrating(p)))
  67. cpu_relax();
  68. }
  69. }
  70. /*
  71. * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
  72. */
  73. struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  74. __acquires(p->pi_lock)
  75. __acquires(rq->lock)
  76. {
  77. struct rq *rq;
  78. for (;;) {
  79. raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
  80. rq = task_rq(p);
  81. raw_spin_lock(&rq->lock);
  82. /*
  83. * move_queued_task() task_rq_lock()
  84. *
  85. * ACQUIRE (rq->lock)
  86. * [S] ->on_rq = MIGRATING [L] rq = task_rq()
  87. * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
  88. * [S] ->cpu = new_cpu [L] task_rq()
  89. * [L] ->on_rq
  90. * RELEASE (rq->lock)
  91. *
  92. * If we observe the old CPU in task_rq_lock(), the acquire of
  93. * the old rq->lock will fully serialize against the stores.
  94. *
  95. * If we observe the new CPU in task_rq_lock(), the address
  96. * dependency headed by '[L] rq = task_rq()' and the acquire
  97. * will pair with the WMB to ensure we then also see migrating.
  98. */
  99. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  100. rq_pin_lock(rq, rf);
  101. return rq;
  102. }
  103. raw_spin_unlock(&rq->lock);
  104. raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
  105. while (unlikely(task_on_rq_migrating(p)))
  106. cpu_relax();
  107. }
  108. }
  109. /*
  110. * RQ-clock updating methods:
  111. */
  112. static void update_rq_clock_task(struct rq *rq, s64 delta)
  113. {
  114. /*
  115. * In theory, the compile should just see 0 here, and optimize out the call
  116. * to sched_rt_avg_update. But I don't trust it...
  117. */
  118. s64 __maybe_unused steal = 0, irq_delta = 0;
  119. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  120. irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
  121. /*
  122. * Since irq_time is only updated on {soft,}irq_exit, we might run into
  123. * this case when a previous update_rq_clock() happened inside a
  124. * {soft,}irq region.
  125. *
  126. * When this happens, we stop ->clock_task and only update the
  127. * prev_irq_time stamp to account for the part that fit, so that a next
  128. * update will consume the rest. This ensures ->clock_task is
  129. * monotonic.
  130. *
  131. * It does however cause some slight miss-attribution of {soft,}irq
  132. * time, a more accurate solution would be to update the irq_time using
  133. * the current rq->clock timestamp, except that would require using
  134. * atomic ops.
  135. */
  136. if (irq_delta > delta)
  137. irq_delta = delta;
  138. rq->prev_irq_time += irq_delta;
  139. delta -= irq_delta;
  140. #endif
  141. #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
  142. if (static_key_false((&paravirt_steal_rq_enabled))) {
  143. steal = paravirt_steal_clock(cpu_of(rq));
  144. steal -= rq->prev_steal_time_rq;
  145. if (unlikely(steal > delta))
  146. steal = delta;
  147. rq->prev_steal_time_rq += steal;
  148. delta -= steal;
  149. }
  150. #endif
  151. rq->clock_task += delta;
  152. #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
  153. if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
  154. update_irq_load_avg(rq, irq_delta + steal);
  155. #endif
  156. }
  157. void update_rq_clock(struct rq *rq)
  158. {
  159. s64 delta;
  160. lockdep_assert_held(&rq->lock);
  161. if (rq->clock_update_flags & RQCF_ACT_SKIP)
  162. return;
  163. #ifdef CONFIG_SCHED_DEBUG
  164. if (sched_feat(WARN_DOUBLE_CLOCK))
  165. SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
  166. rq->clock_update_flags |= RQCF_UPDATED;
  167. #endif
  168. delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
  169. if (delta < 0)
  170. return;
  171. rq->clock += delta;
  172. update_rq_clock_task(rq, delta);
  173. }
  174. #ifdef CONFIG_SCHED_HRTICK
  175. /*
  176. * Use HR-timers to deliver accurate preemption points.
  177. */
  178. static void hrtick_clear(struct rq *rq)
  179. {
  180. if (hrtimer_active(&rq->hrtick_timer))
  181. hrtimer_cancel(&rq->hrtick_timer);
  182. }
  183. /*
  184. * High-resolution timer tick.
  185. * Runs from hardirq context with interrupts disabled.
  186. */
  187. static enum hrtimer_restart hrtick(struct hrtimer *timer)
  188. {
  189. struct rq *rq = container_of(timer, struct rq, hrtick_timer);
  190. struct rq_flags rf;
  191. WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
  192. rq_lock(rq, &rf);
  193. update_rq_clock(rq);
  194. rq->curr->sched_class->task_tick(rq, rq->curr, 1);
  195. rq_unlock(rq, &rf);
  196. return HRTIMER_NORESTART;
  197. }
  198. #ifdef CONFIG_SMP
  199. static void __hrtick_restart(struct rq *rq)
  200. {
  201. struct hrtimer *timer = &rq->hrtick_timer;
  202. hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
  203. }
  204. /*
  205. * called from hardirq (IPI) context
  206. */
  207. static void __hrtick_start(void *arg)
  208. {
  209. struct rq *rq = arg;
  210. struct rq_flags rf;
  211. rq_lock(rq, &rf);
  212. __hrtick_restart(rq);
  213. rq->hrtick_csd_pending = 0;
  214. rq_unlock(rq, &rf);
  215. }
  216. /*
  217. * Called to set the hrtick timer state.
  218. *
  219. * called with rq->lock held and irqs disabled
  220. */
  221. void hrtick_start(struct rq *rq, u64 delay)
  222. {
  223. struct hrtimer *timer = &rq->hrtick_timer;
  224. ktime_t time;
  225. s64 delta;
  226. /*
  227. * Don't schedule slices shorter than 10000ns, that just
  228. * doesn't make sense and can cause timer DoS.
  229. */
  230. delta = max_t(s64, delay, 10000LL);
  231. time = ktime_add_ns(timer->base->get_time(), delta);
  232. hrtimer_set_expires(timer, time);
  233. if (rq == this_rq()) {
  234. __hrtick_restart(rq);
  235. } else if (!rq->hrtick_csd_pending) {
  236. smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
  237. rq->hrtick_csd_pending = 1;
  238. }
  239. }
  240. #else
  241. /*
  242. * Called to set the hrtick timer state.
  243. *
  244. * called with rq->lock held and irqs disabled
  245. */
  246. void hrtick_start(struct rq *rq, u64 delay)
  247. {
  248. /*
  249. * Don't schedule slices shorter than 10000ns, that just
  250. * doesn't make sense. Rely on vruntime for fairness.
  251. */
  252. delay = max_t(u64, delay, 10000LL);
  253. hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
  254. HRTIMER_MODE_REL_PINNED);
  255. }
  256. #endif /* CONFIG_SMP */
  257. static void hrtick_rq_init(struct rq *rq)
  258. {
  259. #ifdef CONFIG_SMP
  260. rq->hrtick_csd_pending = 0;
  261. rq->hrtick_csd.flags = 0;
  262. rq->hrtick_csd.func = __hrtick_start;
  263. rq->hrtick_csd.info = rq;
  264. #endif
  265. hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  266. rq->hrtick_timer.function = hrtick;
  267. }
  268. #else /* CONFIG_SCHED_HRTICK */
  269. static inline void hrtick_clear(struct rq *rq)
  270. {
  271. }
  272. static inline void hrtick_rq_init(struct rq *rq)
  273. {
  274. }
  275. #endif /* CONFIG_SCHED_HRTICK */
  276. /*
  277. * cmpxchg based fetch_or, macro so it works for different integer types
  278. */
  279. #define fetch_or(ptr, mask) \
  280. ({ \
  281. typeof(ptr) _ptr = (ptr); \
  282. typeof(mask) _mask = (mask); \
  283. typeof(*_ptr) _old, _val = *_ptr; \
  284. \
  285. for (;;) { \
  286. _old = cmpxchg(_ptr, _val, _val | _mask); \
  287. if (_old == _val) \
  288. break; \
  289. _val = _old; \
  290. } \
  291. _old; \
  292. })
  293. #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
  294. /*
  295. * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
  296. * this avoids any races wrt polling state changes and thereby avoids
  297. * spurious IPIs.
  298. */
  299. static bool set_nr_and_not_polling(struct task_struct *p)
  300. {
  301. struct thread_info *ti = task_thread_info(p);
  302. return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
  303. }
  304. /*
  305. * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
  306. *
  307. * If this returns true, then the idle task promises to call
  308. * sched_ttwu_pending() and reschedule soon.
  309. */
  310. static bool set_nr_if_polling(struct task_struct *p)
  311. {
  312. struct thread_info *ti = task_thread_info(p);
  313. typeof(ti->flags) old, val = READ_ONCE(ti->flags);
  314. for (;;) {
  315. if (!(val & _TIF_POLLING_NRFLAG))
  316. return false;
  317. if (val & _TIF_NEED_RESCHED)
  318. return true;
  319. old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
  320. if (old == val)
  321. break;
  322. val = old;
  323. }
  324. return true;
  325. }
  326. #else
  327. static bool set_nr_and_not_polling(struct task_struct *p)
  328. {
  329. set_tsk_need_resched(p);
  330. return true;
  331. }
  332. #ifdef CONFIG_SMP
  333. static bool set_nr_if_polling(struct task_struct *p)
  334. {
  335. return false;
  336. }
  337. #endif
  338. #endif
  339. void wake_q_add(struct wake_q_head *head, struct task_struct *task)
  340. {
  341. struct wake_q_node *node = &task->wake_q;
  342. /*
  343. * Atomically grab the task, if ->wake_q is !nil already it means
  344. * its already queued (either by us or someone else) and will get the
  345. * wakeup due to that.
  346. *
  347. * In order to ensure that a pending wakeup will observe our pending
  348. * state, even in the failed case, an explicit smp_mb() must be used.
  349. */
  350. smp_mb__before_atomic();
  351. if (cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL))
  352. return;
  353. get_task_struct(task);
  354. /*
  355. * The head is context local, there can be no concurrency.
  356. */
  357. *head->lastp = node;
  358. head->lastp = &node->next;
  359. }
  360. void wake_up_q(struct wake_q_head *head)
  361. {
  362. struct wake_q_node *node = head->first;
  363. while (node != WAKE_Q_TAIL) {
  364. struct task_struct *task;
  365. task = container_of(node, struct task_struct, wake_q);
  366. BUG_ON(!task);
  367. /* Task can safely be re-inserted now: */
  368. node = node->next;
  369. task->wake_q.next = NULL;
  370. /*
  371. * wake_up_process() executes a full barrier, which pairs with
  372. * the queueing in wake_q_add() so as not to miss wakeups.
  373. */
  374. wake_up_process(task);
  375. put_task_struct(task);
  376. }
  377. }
  378. /*
  379. * resched_curr - mark rq's current task 'to be rescheduled now'.
  380. *
  381. * On UP this means the setting of the need_resched flag, on SMP it
  382. * might also involve a cross-CPU call to trigger the scheduler on
  383. * the target CPU.
  384. */
  385. void resched_curr(struct rq *rq)
  386. {
  387. struct task_struct *curr = rq->curr;
  388. int cpu;
  389. lockdep_assert_held(&rq->lock);
  390. if (test_tsk_need_resched(curr))
  391. return;
  392. cpu = cpu_of(rq);
  393. if (cpu == smp_processor_id()) {
  394. set_tsk_need_resched(curr);
  395. set_preempt_need_resched();
  396. return;
  397. }
  398. if (set_nr_and_not_polling(curr))
  399. smp_send_reschedule(cpu);
  400. else
  401. trace_sched_wake_idle_without_ipi(cpu);
  402. }
  403. void resched_cpu(int cpu)
  404. {
  405. struct rq *rq = cpu_rq(cpu);
  406. unsigned long flags;
  407. raw_spin_lock_irqsave(&rq->lock, flags);
  408. if (cpu_online(cpu) || cpu == smp_processor_id())
  409. resched_curr(rq);
  410. raw_spin_unlock_irqrestore(&rq->lock, flags);
  411. }
  412. #ifdef CONFIG_SMP
  413. #ifdef CONFIG_NO_HZ_COMMON
  414. /*
  415. * In the semi idle case, use the nearest busy CPU for migrating timers
  416. * from an idle CPU. This is good for power-savings.
  417. *
  418. * We don't do similar optimization for completely idle system, as
  419. * selecting an idle CPU will add more delays to the timers than intended
  420. * (as that CPU's timer base may not be uptodate wrt jiffies etc).
  421. */
  422. int get_nohz_timer_target(void)
  423. {
  424. int i, cpu = smp_processor_id();
  425. struct sched_domain *sd;
  426. if (!idle_cpu(cpu) && housekeeping_cpu(cpu, HK_FLAG_TIMER))
  427. return cpu;
  428. rcu_read_lock();
  429. for_each_domain(cpu, sd) {
  430. for_each_cpu(i, sched_domain_span(sd)) {
  431. if (cpu == i)
  432. continue;
  433. if (!idle_cpu(i) && housekeeping_cpu(i, HK_FLAG_TIMER)) {
  434. cpu = i;
  435. goto unlock;
  436. }
  437. }
  438. }
  439. if (!housekeeping_cpu(cpu, HK_FLAG_TIMER))
  440. cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
  441. unlock:
  442. rcu_read_unlock();
  443. return cpu;
  444. }
  445. /*
  446. * When add_timer_on() enqueues a timer into the timer wheel of an
  447. * idle CPU then this timer might expire before the next timer event
  448. * which is scheduled to wake up that CPU. In case of a completely
  449. * idle system the next event might even be infinite time into the
  450. * future. wake_up_idle_cpu() ensures that the CPU is woken up and
  451. * leaves the inner idle loop so the newly added timer is taken into
  452. * account when the CPU goes back to idle and evaluates the timer
  453. * wheel for the next timer event.
  454. */
  455. static void wake_up_idle_cpu(int cpu)
  456. {
  457. struct rq *rq = cpu_rq(cpu);
  458. if (cpu == smp_processor_id())
  459. return;
  460. if (set_nr_and_not_polling(rq->idle))
  461. smp_send_reschedule(cpu);
  462. else
  463. trace_sched_wake_idle_without_ipi(cpu);
  464. }
  465. static bool wake_up_full_nohz_cpu(int cpu)
  466. {
  467. /*
  468. * We just need the target to call irq_exit() and re-evaluate
  469. * the next tick. The nohz full kick at least implies that.
  470. * If needed we can still optimize that later with an
  471. * empty IRQ.
  472. */
  473. if (cpu_is_offline(cpu))
  474. return true; /* Don't try to wake offline CPUs. */
  475. if (tick_nohz_full_cpu(cpu)) {
  476. if (cpu != smp_processor_id() ||
  477. tick_nohz_tick_stopped())
  478. tick_nohz_full_kick_cpu(cpu);
  479. return true;
  480. }
  481. return false;
  482. }
  483. /*
  484. * Wake up the specified CPU. If the CPU is going offline, it is the
  485. * caller's responsibility to deal with the lost wakeup, for example,
  486. * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
  487. */
  488. void wake_up_nohz_cpu(int cpu)
  489. {
  490. if (!wake_up_full_nohz_cpu(cpu))
  491. wake_up_idle_cpu(cpu);
  492. }
  493. static inline bool got_nohz_idle_kick(void)
  494. {
  495. int cpu = smp_processor_id();
  496. if (!(atomic_read(nohz_flags(cpu)) & NOHZ_KICK_MASK))
  497. return false;
  498. if (idle_cpu(cpu) && !need_resched())
  499. return true;
  500. /*
  501. * We can't run Idle Load Balance on this CPU for this time so we
  502. * cancel it and clear NOHZ_BALANCE_KICK
  503. */
  504. atomic_andnot(NOHZ_KICK_MASK, nohz_flags(cpu));
  505. return false;
  506. }
  507. #else /* CONFIG_NO_HZ_COMMON */
  508. static inline bool got_nohz_idle_kick(void)
  509. {
  510. return false;
  511. }
  512. #endif /* CONFIG_NO_HZ_COMMON */
  513. #ifdef CONFIG_NO_HZ_FULL
  514. bool sched_can_stop_tick(struct rq *rq)
  515. {
  516. int fifo_nr_running;
  517. /* Deadline tasks, even if single, need the tick */
  518. if (rq->dl.dl_nr_running)
  519. return false;
  520. /*
  521. * If there are more than one RR tasks, we need the tick to effect the
  522. * actual RR behaviour.
  523. */
  524. if (rq->rt.rr_nr_running) {
  525. if (rq->rt.rr_nr_running == 1)
  526. return true;
  527. else
  528. return false;
  529. }
  530. /*
  531. * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
  532. * forced preemption between FIFO tasks.
  533. */
  534. fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
  535. if (fifo_nr_running)
  536. return true;
  537. /*
  538. * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
  539. * if there's more than one we need the tick for involuntary
  540. * preemption.
  541. */
  542. if (rq->nr_running > 1)
  543. return false;
  544. return true;
  545. }
  546. #endif /* CONFIG_NO_HZ_FULL */
  547. #endif /* CONFIG_SMP */
  548. #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
  549. (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
  550. /*
  551. * Iterate task_group tree rooted at *from, calling @down when first entering a
  552. * node and @up when leaving it for the final time.
  553. *
  554. * Caller must hold rcu_lock or sufficient equivalent.
  555. */
  556. int walk_tg_tree_from(struct task_group *from,
  557. tg_visitor down, tg_visitor up, void *data)
  558. {
  559. struct task_group *parent, *child;
  560. int ret;
  561. parent = from;
  562. down:
  563. ret = (*down)(parent, data);
  564. if (ret)
  565. goto out;
  566. list_for_each_entry_rcu(child, &parent->children, siblings) {
  567. parent = child;
  568. goto down;
  569. up:
  570. continue;
  571. }
  572. ret = (*up)(parent, data);
  573. if (ret || parent == from)
  574. goto out;
  575. child = parent;
  576. parent = parent->parent;
  577. if (parent)
  578. goto up;
  579. out:
  580. return ret;
  581. }
  582. int tg_nop(struct task_group *tg, void *data)
  583. {
  584. return 0;
  585. }
  586. #endif
  587. static void set_load_weight(struct task_struct *p, bool update_load)
  588. {
  589. int prio = p->static_prio - MAX_RT_PRIO;
  590. struct load_weight *load = &p->se.load;
  591. /*
  592. * SCHED_IDLE tasks get minimal weight:
  593. */
  594. if (idle_policy(p->policy)) {
  595. load->weight = scale_load(WEIGHT_IDLEPRIO);
  596. load->inv_weight = WMULT_IDLEPRIO;
  597. return;
  598. }
  599. /*
  600. * SCHED_OTHER tasks have to update their load when changing their
  601. * weight
  602. */
  603. if (update_load && p->sched_class == &fair_sched_class) {
  604. reweight_task(p, prio);
  605. } else {
  606. load->weight = scale_load(sched_prio_to_weight[prio]);
  607. load->inv_weight = sched_prio_to_wmult[prio];
  608. }
  609. }
  610. static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
  611. {
  612. if (!(flags & ENQUEUE_NOCLOCK))
  613. update_rq_clock(rq);
  614. if (!(flags & ENQUEUE_RESTORE))
  615. sched_info_queued(rq, p);
  616. p->sched_class->enqueue_task(rq, p, flags);
  617. }
  618. static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
  619. {
  620. if (!(flags & DEQUEUE_NOCLOCK))
  621. update_rq_clock(rq);
  622. if (!(flags & DEQUEUE_SAVE))
  623. sched_info_dequeued(rq, p);
  624. p->sched_class->dequeue_task(rq, p, flags);
  625. }
  626. void activate_task(struct rq *rq, struct task_struct *p, int flags)
  627. {
  628. if (task_contributes_to_load(p))
  629. rq->nr_uninterruptible--;
  630. enqueue_task(rq, p, flags);
  631. }
  632. void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
  633. {
  634. if (task_contributes_to_load(p))
  635. rq->nr_uninterruptible++;
  636. dequeue_task(rq, p, flags);
  637. }
  638. /*
  639. * __normal_prio - return the priority that is based on the static prio
  640. */
  641. static inline int __normal_prio(struct task_struct *p)
  642. {
  643. return p->static_prio;
  644. }
  645. /*
  646. * Calculate the expected normal priority: i.e. priority
  647. * without taking RT-inheritance into account. Might be
  648. * boosted by interactivity modifiers. Changes upon fork,
  649. * setprio syscalls, and whenever the interactivity
  650. * estimator recalculates.
  651. */
  652. static inline int normal_prio(struct task_struct *p)
  653. {
  654. int prio;
  655. if (task_has_dl_policy(p))
  656. prio = MAX_DL_PRIO-1;
  657. else if (task_has_rt_policy(p))
  658. prio = MAX_RT_PRIO-1 - p->rt_priority;
  659. else
  660. prio = __normal_prio(p);
  661. return prio;
  662. }
  663. /*
  664. * Calculate the current priority, i.e. the priority
  665. * taken into account by the scheduler. This value might
  666. * be boosted by RT tasks, or might be boosted by
  667. * interactivity modifiers. Will be RT if the task got
  668. * RT-boosted. If not then it returns p->normal_prio.
  669. */
  670. static int effective_prio(struct task_struct *p)
  671. {
  672. p->normal_prio = normal_prio(p);
  673. /*
  674. * If we are RT tasks or we were boosted to RT priority,
  675. * keep the priority unchanged. Otherwise, update priority
  676. * to the normal priority:
  677. */
  678. if (!rt_prio(p->prio))
  679. return p->normal_prio;
  680. return p->prio;
  681. }
  682. /**
  683. * task_curr - is this task currently executing on a CPU?
  684. * @p: the task in question.
  685. *
  686. * Return: 1 if the task is currently executing. 0 otherwise.
  687. */
  688. inline int task_curr(const struct task_struct *p)
  689. {
  690. return cpu_curr(task_cpu(p)) == p;
  691. }
  692. /*
  693. * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
  694. * use the balance_callback list if you want balancing.
  695. *
  696. * this means any call to check_class_changed() must be followed by a call to
  697. * balance_callback().
  698. */
  699. static inline void check_class_changed(struct rq *rq, struct task_struct *p,
  700. const struct sched_class *prev_class,
  701. int oldprio)
  702. {
  703. if (prev_class != p->sched_class) {
  704. if (prev_class->switched_from)
  705. prev_class->switched_from(rq, p);
  706. p->sched_class->switched_to(rq, p);
  707. } else if (oldprio != p->prio || dl_task(p))
  708. p->sched_class->prio_changed(rq, p, oldprio);
  709. }
  710. void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
  711. {
  712. const struct sched_class *class;
  713. if (p->sched_class == rq->curr->sched_class) {
  714. rq->curr->sched_class->check_preempt_curr(rq, p, flags);
  715. } else {
  716. for_each_class(class) {
  717. if (class == rq->curr->sched_class)
  718. break;
  719. if (class == p->sched_class) {
  720. resched_curr(rq);
  721. break;
  722. }
  723. }
  724. }
  725. /*
  726. * A queue event has occurred, and we're going to schedule. In
  727. * this case, we can save a useless back to back clock update.
  728. */
  729. if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
  730. rq_clock_skip_update(rq);
  731. }
  732. #ifdef CONFIG_SMP
  733. static inline bool is_per_cpu_kthread(struct task_struct *p)
  734. {
  735. if (!(p->flags & PF_KTHREAD))
  736. return false;
  737. if (p->nr_cpus_allowed != 1)
  738. return false;
  739. return true;
  740. }
  741. /*
  742. * Per-CPU kthreads are allowed to run on !actie && online CPUs, see
  743. * __set_cpus_allowed_ptr() and select_fallback_rq().
  744. */
  745. static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
  746. {
  747. if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
  748. return false;
  749. if (is_per_cpu_kthread(p))
  750. return cpu_online(cpu);
  751. return cpu_active(cpu);
  752. }
  753. /*
  754. * This is how migration works:
  755. *
  756. * 1) we invoke migration_cpu_stop() on the target CPU using
  757. * stop_one_cpu().
  758. * 2) stopper starts to run (implicitly forcing the migrated thread
  759. * off the CPU)
  760. * 3) it checks whether the migrated task is still in the wrong runqueue.
  761. * 4) if it's in the wrong runqueue then the migration thread removes
  762. * it and puts it into the right queue.
  763. * 5) stopper completes and stop_one_cpu() returns and the migration
  764. * is done.
  765. */
  766. /*
  767. * move_queued_task - move a queued task to new rq.
  768. *
  769. * Returns (locked) new rq. Old rq's lock is released.
  770. */
  771. static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
  772. struct task_struct *p, int new_cpu)
  773. {
  774. lockdep_assert_held(&rq->lock);
  775. WRITE_ONCE(p->on_rq, TASK_ON_RQ_MIGRATING);
  776. dequeue_task(rq, p, DEQUEUE_NOCLOCK);
  777. set_task_cpu(p, new_cpu);
  778. rq_unlock(rq, rf);
  779. rq = cpu_rq(new_cpu);
  780. rq_lock(rq, rf);
  781. BUG_ON(task_cpu(p) != new_cpu);
  782. enqueue_task(rq, p, 0);
  783. p->on_rq = TASK_ON_RQ_QUEUED;
  784. check_preempt_curr(rq, p, 0);
  785. return rq;
  786. }
  787. struct migration_arg {
  788. struct task_struct *task;
  789. int dest_cpu;
  790. };
  791. /*
  792. * Move (not current) task off this CPU, onto the destination CPU. We're doing
  793. * this because either it can't run here any more (set_cpus_allowed()
  794. * away from this CPU, or CPU going down), or because we're
  795. * attempting to rebalance this task on exec (sched_exec).
  796. *
  797. * So we race with normal scheduler movements, but that's OK, as long
  798. * as the task is no longer on this CPU.
  799. */
  800. static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
  801. struct task_struct *p, int dest_cpu)
  802. {
  803. /* Affinity changed (again). */
  804. if (!is_cpu_allowed(p, dest_cpu))
  805. return rq;
  806. update_rq_clock(rq);
  807. rq = move_queued_task(rq, rf, p, dest_cpu);
  808. return rq;
  809. }
  810. /*
  811. * migration_cpu_stop - this will be executed by a highprio stopper thread
  812. * and performs thread migration by bumping thread off CPU then
  813. * 'pushing' onto another runqueue.
  814. */
  815. static int migration_cpu_stop(void *data)
  816. {
  817. struct migration_arg *arg = data;
  818. struct task_struct *p = arg->task;
  819. struct rq *rq = this_rq();
  820. struct rq_flags rf;
  821. /*
  822. * The original target CPU might have gone down and we might
  823. * be on another CPU but it doesn't matter.
  824. */
  825. local_irq_disable();
  826. /*
  827. * We need to explicitly wake pending tasks before running
  828. * __migrate_task() such that we will not miss enforcing cpus_allowed
  829. * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
  830. */
  831. sched_ttwu_pending();
  832. raw_spin_lock(&p->pi_lock);
  833. rq_lock(rq, &rf);
  834. /*
  835. * If task_rq(p) != rq, it cannot be migrated here, because we're
  836. * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
  837. * we're holding p->pi_lock.
  838. */
  839. if (task_rq(p) == rq) {
  840. if (task_on_rq_queued(p))
  841. rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
  842. else
  843. p->wake_cpu = arg->dest_cpu;
  844. }
  845. rq_unlock(rq, &rf);
  846. raw_spin_unlock(&p->pi_lock);
  847. local_irq_enable();
  848. return 0;
  849. }
  850. /*
  851. * sched_class::set_cpus_allowed must do the below, but is not required to
  852. * actually call this function.
  853. */
  854. void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
  855. {
  856. cpumask_copy(&p->cpus_allowed, new_mask);
  857. p->nr_cpus_allowed = cpumask_weight(new_mask);
  858. }
  859. void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
  860. {
  861. struct rq *rq = task_rq(p);
  862. bool queued, running;
  863. lockdep_assert_held(&p->pi_lock);
  864. queued = task_on_rq_queued(p);
  865. running = task_current(rq, p);
  866. if (queued) {
  867. /*
  868. * Because __kthread_bind() calls this on blocked tasks without
  869. * holding rq->lock.
  870. */
  871. lockdep_assert_held(&rq->lock);
  872. dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
  873. }
  874. if (running)
  875. put_prev_task(rq, p);
  876. p->sched_class->set_cpus_allowed(p, new_mask);
  877. if (queued)
  878. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  879. if (running)
  880. set_curr_task(rq, p);
  881. }
  882. /*
  883. * Change a given task's CPU affinity. Migrate the thread to a
  884. * proper CPU and schedule it away if the CPU it's executing on
  885. * is removed from the allowed bitmask.
  886. *
  887. * NOTE: the caller must have a valid reference to the task, the
  888. * task must not exit() & deallocate itself prematurely. The
  889. * call is not atomic; no spinlocks may be held.
  890. */
  891. static int __set_cpus_allowed_ptr(struct task_struct *p,
  892. const struct cpumask *new_mask, bool check)
  893. {
  894. const struct cpumask *cpu_valid_mask = cpu_active_mask;
  895. unsigned int dest_cpu;
  896. struct rq_flags rf;
  897. struct rq *rq;
  898. int ret = 0;
  899. rq = task_rq_lock(p, &rf);
  900. update_rq_clock(rq);
  901. if (p->flags & PF_KTHREAD) {
  902. /*
  903. * Kernel threads are allowed on online && !active CPUs
  904. */
  905. cpu_valid_mask = cpu_online_mask;
  906. }
  907. /*
  908. * Must re-check here, to close a race against __kthread_bind(),
  909. * sched_setaffinity() is not guaranteed to observe the flag.
  910. */
  911. if (check && (p->flags & PF_NO_SETAFFINITY)) {
  912. ret = -EINVAL;
  913. goto out;
  914. }
  915. if (cpumask_equal(&p->cpus_allowed, new_mask))
  916. goto out;
  917. dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
  918. if (dest_cpu >= nr_cpu_ids) {
  919. ret = -EINVAL;
  920. goto out;
  921. }
  922. do_set_cpus_allowed(p, new_mask);
  923. if (p->flags & PF_KTHREAD) {
  924. /*
  925. * For kernel threads that do indeed end up on online &&
  926. * !active we want to ensure they are strict per-CPU threads.
  927. */
  928. WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
  929. !cpumask_intersects(new_mask, cpu_active_mask) &&
  930. p->nr_cpus_allowed != 1);
  931. }
  932. /* Can the task run on the task's current CPU? If so, we're done */
  933. if (cpumask_test_cpu(task_cpu(p), new_mask))
  934. goto out;
  935. if (task_running(rq, p) || p->state == TASK_WAKING) {
  936. struct migration_arg arg = { p, dest_cpu };
  937. /* Need help from migration thread: drop lock and wait. */
  938. task_rq_unlock(rq, p, &rf);
  939. stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
  940. tlb_migrate_finish(p->mm);
  941. return 0;
  942. } else if (task_on_rq_queued(p)) {
  943. /*
  944. * OK, since we're going to drop the lock immediately
  945. * afterwards anyway.
  946. */
  947. rq = move_queued_task(rq, &rf, p, dest_cpu);
  948. }
  949. out:
  950. task_rq_unlock(rq, p, &rf);
  951. return ret;
  952. }
  953. int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
  954. {
  955. return __set_cpus_allowed_ptr(p, new_mask, false);
  956. }
  957. EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
  958. void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
  959. {
  960. #ifdef CONFIG_SCHED_DEBUG
  961. /*
  962. * We should never call set_task_cpu() on a blocked task,
  963. * ttwu() will sort out the placement.
  964. */
  965. WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
  966. !p->on_rq);
  967. /*
  968. * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
  969. * because schedstat_wait_{start,end} rebase migrating task's wait_start
  970. * time relying on p->on_rq.
  971. */
  972. WARN_ON_ONCE(p->state == TASK_RUNNING &&
  973. p->sched_class == &fair_sched_class &&
  974. (p->on_rq && !task_on_rq_migrating(p)));
  975. #ifdef CONFIG_LOCKDEP
  976. /*
  977. * The caller should hold either p->pi_lock or rq->lock, when changing
  978. * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
  979. *
  980. * sched_move_task() holds both and thus holding either pins the cgroup,
  981. * see task_group().
  982. *
  983. * Furthermore, all task_rq users should acquire both locks, see
  984. * task_rq_lock().
  985. */
  986. WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
  987. lockdep_is_held(&task_rq(p)->lock)));
  988. #endif
  989. /*
  990. * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
  991. */
  992. WARN_ON_ONCE(!cpu_online(new_cpu));
  993. #endif
  994. trace_sched_migrate_task(p, new_cpu);
  995. if (task_cpu(p) != new_cpu) {
  996. if (p->sched_class->migrate_task_rq)
  997. p->sched_class->migrate_task_rq(p, new_cpu);
  998. p->se.nr_migrations++;
  999. rseq_migrate(p);
  1000. perf_event_task_migrate(p);
  1001. }
  1002. __set_task_cpu(p, new_cpu);
  1003. }
  1004. #ifdef CONFIG_NUMA_BALANCING
  1005. static void __migrate_swap_task(struct task_struct *p, int cpu)
  1006. {
  1007. if (task_on_rq_queued(p)) {
  1008. struct rq *src_rq, *dst_rq;
  1009. struct rq_flags srf, drf;
  1010. src_rq = task_rq(p);
  1011. dst_rq = cpu_rq(cpu);
  1012. rq_pin_lock(src_rq, &srf);
  1013. rq_pin_lock(dst_rq, &drf);
  1014. p->on_rq = TASK_ON_RQ_MIGRATING;
  1015. deactivate_task(src_rq, p, 0);
  1016. set_task_cpu(p, cpu);
  1017. activate_task(dst_rq, p, 0);
  1018. p->on_rq = TASK_ON_RQ_QUEUED;
  1019. check_preempt_curr(dst_rq, p, 0);
  1020. rq_unpin_lock(dst_rq, &drf);
  1021. rq_unpin_lock(src_rq, &srf);
  1022. } else {
  1023. /*
  1024. * Task isn't running anymore; make it appear like we migrated
  1025. * it before it went to sleep. This means on wakeup we make the
  1026. * previous CPU our target instead of where it really is.
  1027. */
  1028. p->wake_cpu = cpu;
  1029. }
  1030. }
  1031. struct migration_swap_arg {
  1032. struct task_struct *src_task, *dst_task;
  1033. int src_cpu, dst_cpu;
  1034. };
  1035. static int migrate_swap_stop(void *data)
  1036. {
  1037. struct migration_swap_arg *arg = data;
  1038. struct rq *src_rq, *dst_rq;
  1039. int ret = -EAGAIN;
  1040. if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
  1041. return -EAGAIN;
  1042. src_rq = cpu_rq(arg->src_cpu);
  1043. dst_rq = cpu_rq(arg->dst_cpu);
  1044. double_raw_lock(&arg->src_task->pi_lock,
  1045. &arg->dst_task->pi_lock);
  1046. double_rq_lock(src_rq, dst_rq);
  1047. if (task_cpu(arg->dst_task) != arg->dst_cpu)
  1048. goto unlock;
  1049. if (task_cpu(arg->src_task) != arg->src_cpu)
  1050. goto unlock;
  1051. if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
  1052. goto unlock;
  1053. if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
  1054. goto unlock;
  1055. __migrate_swap_task(arg->src_task, arg->dst_cpu);
  1056. __migrate_swap_task(arg->dst_task, arg->src_cpu);
  1057. ret = 0;
  1058. unlock:
  1059. double_rq_unlock(src_rq, dst_rq);
  1060. raw_spin_unlock(&arg->dst_task->pi_lock);
  1061. raw_spin_unlock(&arg->src_task->pi_lock);
  1062. return ret;
  1063. }
  1064. /*
  1065. * Cross migrate two tasks
  1066. */
  1067. int migrate_swap(struct task_struct *cur, struct task_struct *p,
  1068. int target_cpu, int curr_cpu)
  1069. {
  1070. struct migration_swap_arg arg;
  1071. int ret = -EINVAL;
  1072. arg = (struct migration_swap_arg){
  1073. .src_task = cur,
  1074. .src_cpu = curr_cpu,
  1075. .dst_task = p,
  1076. .dst_cpu = target_cpu,
  1077. };
  1078. if (arg.src_cpu == arg.dst_cpu)
  1079. goto out;
  1080. /*
  1081. * These three tests are all lockless; this is OK since all of them
  1082. * will be re-checked with proper locks held further down the line.
  1083. */
  1084. if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
  1085. goto out;
  1086. if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
  1087. goto out;
  1088. if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
  1089. goto out;
  1090. trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
  1091. ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
  1092. out:
  1093. return ret;
  1094. }
  1095. #endif /* CONFIG_NUMA_BALANCING */
  1096. /*
  1097. * wait_task_inactive - wait for a thread to unschedule.
  1098. *
  1099. * If @match_state is nonzero, it's the @p->state value just checked and
  1100. * not expected to change. If it changes, i.e. @p might have woken up,
  1101. * then return zero. When we succeed in waiting for @p to be off its CPU,
  1102. * we return a positive number (its total switch count). If a second call
  1103. * a short while later returns the same number, the caller can be sure that
  1104. * @p has remained unscheduled the whole time.
  1105. *
  1106. * The caller must ensure that the task *will* unschedule sometime soon,
  1107. * else this function might spin for a *long* time. This function can't
  1108. * be called with interrupts off, or it may introduce deadlock with
  1109. * smp_call_function() if an IPI is sent by the same process we are
  1110. * waiting to become inactive.
  1111. */
  1112. unsigned long wait_task_inactive(struct task_struct *p, long match_state)
  1113. {
  1114. int running, queued;
  1115. struct rq_flags rf;
  1116. unsigned long ncsw;
  1117. struct rq *rq;
  1118. for (;;) {
  1119. /*
  1120. * We do the initial early heuristics without holding
  1121. * any task-queue locks at all. We'll only try to get
  1122. * the runqueue lock when things look like they will
  1123. * work out!
  1124. */
  1125. rq = task_rq(p);
  1126. /*
  1127. * If the task is actively running on another CPU
  1128. * still, just relax and busy-wait without holding
  1129. * any locks.
  1130. *
  1131. * NOTE! Since we don't hold any locks, it's not
  1132. * even sure that "rq" stays as the right runqueue!
  1133. * But we don't care, since "task_running()" will
  1134. * return false if the runqueue has changed and p
  1135. * is actually now running somewhere else!
  1136. */
  1137. while (task_running(rq, p)) {
  1138. if (match_state && unlikely(p->state != match_state))
  1139. return 0;
  1140. cpu_relax();
  1141. }
  1142. /*
  1143. * Ok, time to look more closely! We need the rq
  1144. * lock now, to be *sure*. If we're wrong, we'll
  1145. * just go back and repeat.
  1146. */
  1147. rq = task_rq_lock(p, &rf);
  1148. trace_sched_wait_task(p);
  1149. running = task_running(rq, p);
  1150. queued = task_on_rq_queued(p);
  1151. ncsw = 0;
  1152. if (!match_state || p->state == match_state)
  1153. ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
  1154. task_rq_unlock(rq, p, &rf);
  1155. /*
  1156. * If it changed from the expected state, bail out now.
  1157. */
  1158. if (unlikely(!ncsw))
  1159. break;
  1160. /*
  1161. * Was it really running after all now that we
  1162. * checked with the proper locks actually held?
  1163. *
  1164. * Oops. Go back and try again..
  1165. */
  1166. if (unlikely(running)) {
  1167. cpu_relax();
  1168. continue;
  1169. }
  1170. /*
  1171. * It's not enough that it's not actively running,
  1172. * it must be off the runqueue _entirely_, and not
  1173. * preempted!
  1174. *
  1175. * So if it was still runnable (but just not actively
  1176. * running right now), it's preempted, and we should
  1177. * yield - it could be a while.
  1178. */
  1179. if (unlikely(queued)) {
  1180. ktime_t to = NSEC_PER_SEC / HZ;
  1181. set_current_state(TASK_UNINTERRUPTIBLE);
  1182. schedule_hrtimeout(&to, HRTIMER_MODE_REL);
  1183. continue;
  1184. }
  1185. /*
  1186. * Ahh, all good. It wasn't running, and it wasn't
  1187. * runnable, which means that it will never become
  1188. * running in the future either. We're all done!
  1189. */
  1190. break;
  1191. }
  1192. return ncsw;
  1193. }
  1194. /***
  1195. * kick_process - kick a running thread to enter/exit the kernel
  1196. * @p: the to-be-kicked thread
  1197. *
  1198. * Cause a process which is running on another CPU to enter
  1199. * kernel-mode, without any delay. (to get signals handled.)
  1200. *
  1201. * NOTE: this function doesn't have to take the runqueue lock,
  1202. * because all it wants to ensure is that the remote task enters
  1203. * the kernel. If the IPI races and the task has been migrated
  1204. * to another CPU then no harm is done and the purpose has been
  1205. * achieved as well.
  1206. */
  1207. void kick_process(struct task_struct *p)
  1208. {
  1209. int cpu;
  1210. preempt_disable();
  1211. cpu = task_cpu(p);
  1212. if ((cpu != smp_processor_id()) && task_curr(p))
  1213. smp_send_reschedule(cpu);
  1214. preempt_enable();
  1215. }
  1216. EXPORT_SYMBOL_GPL(kick_process);
  1217. /*
  1218. * ->cpus_allowed is protected by both rq->lock and p->pi_lock
  1219. *
  1220. * A few notes on cpu_active vs cpu_online:
  1221. *
  1222. * - cpu_active must be a subset of cpu_online
  1223. *
  1224. * - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
  1225. * see __set_cpus_allowed_ptr(). At this point the newly online
  1226. * CPU isn't yet part of the sched domains, and balancing will not
  1227. * see it.
  1228. *
  1229. * - on CPU-down we clear cpu_active() to mask the sched domains and
  1230. * avoid the load balancer to place new tasks on the to be removed
  1231. * CPU. Existing tasks will remain running there and will be taken
  1232. * off.
  1233. *
  1234. * This means that fallback selection must not select !active CPUs.
  1235. * And can assume that any active CPU must be online. Conversely
  1236. * select_task_rq() below may allow selection of !active CPUs in order
  1237. * to satisfy the above rules.
  1238. */
  1239. static int select_fallback_rq(int cpu, struct task_struct *p)
  1240. {
  1241. int nid = cpu_to_node(cpu);
  1242. const struct cpumask *nodemask = NULL;
  1243. enum { cpuset, possible, fail } state = cpuset;
  1244. int dest_cpu;
  1245. /*
  1246. * If the node that the CPU is on has been offlined, cpu_to_node()
  1247. * will return -1. There is no CPU on the node, and we should
  1248. * select the CPU on the other node.
  1249. */
  1250. if (nid != -1) {
  1251. nodemask = cpumask_of_node(nid);
  1252. /* Look for allowed, online CPU in same node. */
  1253. for_each_cpu(dest_cpu, nodemask) {
  1254. if (!cpu_active(dest_cpu))
  1255. continue;
  1256. if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
  1257. return dest_cpu;
  1258. }
  1259. }
  1260. for (;;) {
  1261. /* Any allowed, online CPU? */
  1262. for_each_cpu(dest_cpu, &p->cpus_allowed) {
  1263. if (!is_cpu_allowed(p, dest_cpu))
  1264. continue;
  1265. goto out;
  1266. }
  1267. /* No more Mr. Nice Guy. */
  1268. switch (state) {
  1269. case cpuset:
  1270. if (IS_ENABLED(CONFIG_CPUSETS)) {
  1271. cpuset_cpus_allowed_fallback(p);
  1272. state = possible;
  1273. break;
  1274. }
  1275. /* Fall-through */
  1276. case possible:
  1277. do_set_cpus_allowed(p, cpu_possible_mask);
  1278. state = fail;
  1279. break;
  1280. case fail:
  1281. BUG();
  1282. break;
  1283. }
  1284. }
  1285. out:
  1286. if (state != cpuset) {
  1287. /*
  1288. * Don't tell them about moving exiting tasks or
  1289. * kernel threads (both mm NULL), since they never
  1290. * leave kernel.
  1291. */
  1292. if (p->mm && printk_ratelimit()) {
  1293. printk_deferred("process %d (%s) no longer affine to cpu%d\n",
  1294. task_pid_nr(p), p->comm, cpu);
  1295. }
  1296. }
  1297. return dest_cpu;
  1298. }
  1299. /*
  1300. * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
  1301. */
  1302. static inline
  1303. int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
  1304. {
  1305. lockdep_assert_held(&p->pi_lock);
  1306. if (p->nr_cpus_allowed > 1)
  1307. cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
  1308. else
  1309. cpu = cpumask_any(&p->cpus_allowed);
  1310. /*
  1311. * In order not to call set_task_cpu() on a blocking task we need
  1312. * to rely on ttwu() to place the task on a valid ->cpus_allowed
  1313. * CPU.
  1314. *
  1315. * Since this is common to all placement strategies, this lives here.
  1316. *
  1317. * [ this allows ->select_task() to simply return task_cpu(p) and
  1318. * not worry about this generic constraint ]
  1319. */
  1320. if (unlikely(!is_cpu_allowed(p, cpu)))
  1321. cpu = select_fallback_rq(task_cpu(p), p);
  1322. return cpu;
  1323. }
  1324. static void update_avg(u64 *avg, u64 sample)
  1325. {
  1326. s64 diff = sample - *avg;
  1327. *avg += diff >> 3;
  1328. }
  1329. void sched_set_stop_task(int cpu, struct task_struct *stop)
  1330. {
  1331. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  1332. struct task_struct *old_stop = cpu_rq(cpu)->stop;
  1333. if (stop) {
  1334. /*
  1335. * Make it appear like a SCHED_FIFO task, its something
  1336. * userspace knows about and won't get confused about.
  1337. *
  1338. * Also, it will make PI more or less work without too
  1339. * much confusion -- but then, stop work should not
  1340. * rely on PI working anyway.
  1341. */
  1342. sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
  1343. stop->sched_class = &stop_sched_class;
  1344. }
  1345. cpu_rq(cpu)->stop = stop;
  1346. if (old_stop) {
  1347. /*
  1348. * Reset it back to a normal scheduling class so that
  1349. * it can die in pieces.
  1350. */
  1351. old_stop->sched_class = &rt_sched_class;
  1352. }
  1353. }
  1354. #else
  1355. static inline int __set_cpus_allowed_ptr(struct task_struct *p,
  1356. const struct cpumask *new_mask, bool check)
  1357. {
  1358. return set_cpus_allowed_ptr(p, new_mask);
  1359. }
  1360. #endif /* CONFIG_SMP */
  1361. static void
  1362. ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
  1363. {
  1364. struct rq *rq;
  1365. if (!schedstat_enabled())
  1366. return;
  1367. rq = this_rq();
  1368. #ifdef CONFIG_SMP
  1369. if (cpu == rq->cpu) {
  1370. __schedstat_inc(rq->ttwu_local);
  1371. __schedstat_inc(p->se.statistics.nr_wakeups_local);
  1372. } else {
  1373. struct sched_domain *sd;
  1374. __schedstat_inc(p->se.statistics.nr_wakeups_remote);
  1375. rcu_read_lock();
  1376. for_each_domain(rq->cpu, sd) {
  1377. if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
  1378. __schedstat_inc(sd->ttwu_wake_remote);
  1379. break;
  1380. }
  1381. }
  1382. rcu_read_unlock();
  1383. }
  1384. if (wake_flags & WF_MIGRATED)
  1385. __schedstat_inc(p->se.statistics.nr_wakeups_migrate);
  1386. #endif /* CONFIG_SMP */
  1387. __schedstat_inc(rq->ttwu_count);
  1388. __schedstat_inc(p->se.statistics.nr_wakeups);
  1389. if (wake_flags & WF_SYNC)
  1390. __schedstat_inc(p->se.statistics.nr_wakeups_sync);
  1391. }
  1392. static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
  1393. {
  1394. activate_task(rq, p, en_flags);
  1395. p->on_rq = TASK_ON_RQ_QUEUED;
  1396. /* If a worker is waking up, notify the workqueue: */
  1397. if (p->flags & PF_WQ_WORKER)
  1398. wq_worker_waking_up(p, cpu_of(rq));
  1399. }
  1400. /*
  1401. * Mark the task runnable and perform wakeup-preemption.
  1402. */
  1403. static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
  1404. struct rq_flags *rf)
  1405. {
  1406. check_preempt_curr(rq, p, wake_flags);
  1407. p->state = TASK_RUNNING;
  1408. trace_sched_wakeup(p);
  1409. #ifdef CONFIG_SMP
  1410. if (p->sched_class->task_woken) {
  1411. /*
  1412. * Our task @p is fully woken up and running; so its safe to
  1413. * drop the rq->lock, hereafter rq is only used for statistics.
  1414. */
  1415. rq_unpin_lock(rq, rf);
  1416. p->sched_class->task_woken(rq, p);
  1417. rq_repin_lock(rq, rf);
  1418. }
  1419. if (rq->idle_stamp) {
  1420. u64 delta = rq_clock(rq) - rq->idle_stamp;
  1421. u64 max = 2*rq->max_idle_balance_cost;
  1422. update_avg(&rq->avg_idle, delta);
  1423. if (rq->avg_idle > max)
  1424. rq->avg_idle = max;
  1425. rq->idle_stamp = 0;
  1426. }
  1427. #endif
  1428. }
  1429. static void
  1430. ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
  1431. struct rq_flags *rf)
  1432. {
  1433. int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
  1434. lockdep_assert_held(&rq->lock);
  1435. #ifdef CONFIG_SMP
  1436. if (p->sched_contributes_to_load)
  1437. rq->nr_uninterruptible--;
  1438. if (wake_flags & WF_MIGRATED)
  1439. en_flags |= ENQUEUE_MIGRATED;
  1440. #endif
  1441. ttwu_activate(rq, p, en_flags);
  1442. ttwu_do_wakeup(rq, p, wake_flags, rf);
  1443. }
  1444. /*
  1445. * Called in case the task @p isn't fully descheduled from its runqueue,
  1446. * in this case we must do a remote wakeup. Its a 'light' wakeup though,
  1447. * since all we need to do is flip p->state to TASK_RUNNING, since
  1448. * the task is still ->on_rq.
  1449. */
  1450. static int ttwu_remote(struct task_struct *p, int wake_flags)
  1451. {
  1452. struct rq_flags rf;
  1453. struct rq *rq;
  1454. int ret = 0;
  1455. rq = __task_rq_lock(p, &rf);
  1456. if (task_on_rq_queued(p)) {
  1457. /* check_preempt_curr() may use rq clock */
  1458. update_rq_clock(rq);
  1459. ttwu_do_wakeup(rq, p, wake_flags, &rf);
  1460. ret = 1;
  1461. }
  1462. __task_rq_unlock(rq, &rf);
  1463. return ret;
  1464. }
  1465. #ifdef CONFIG_SMP
  1466. void sched_ttwu_pending(void)
  1467. {
  1468. struct rq *rq = this_rq();
  1469. struct llist_node *llist = llist_del_all(&rq->wake_list);
  1470. struct task_struct *p, *t;
  1471. struct rq_flags rf;
  1472. if (!llist)
  1473. return;
  1474. rq_lock_irqsave(rq, &rf);
  1475. update_rq_clock(rq);
  1476. llist_for_each_entry_safe(p, t, llist, wake_entry)
  1477. ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
  1478. rq_unlock_irqrestore(rq, &rf);
  1479. }
  1480. void scheduler_ipi(void)
  1481. {
  1482. /*
  1483. * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
  1484. * TIF_NEED_RESCHED remotely (for the first time) will also send
  1485. * this IPI.
  1486. */
  1487. preempt_fold_need_resched();
  1488. if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
  1489. return;
  1490. /*
  1491. * Not all reschedule IPI handlers call irq_enter/irq_exit, since
  1492. * traditionally all their work was done from the interrupt return
  1493. * path. Now that we actually do some work, we need to make sure
  1494. * we do call them.
  1495. *
  1496. * Some archs already do call them, luckily irq_enter/exit nest
  1497. * properly.
  1498. *
  1499. * Arguably we should visit all archs and update all handlers,
  1500. * however a fair share of IPIs are still resched only so this would
  1501. * somewhat pessimize the simple resched case.
  1502. */
  1503. irq_enter();
  1504. sched_ttwu_pending();
  1505. /*
  1506. * Check if someone kicked us for doing the nohz idle load balance.
  1507. */
  1508. if (unlikely(got_nohz_idle_kick())) {
  1509. this_rq()->idle_balance = 1;
  1510. raise_softirq_irqoff(SCHED_SOFTIRQ);
  1511. }
  1512. irq_exit();
  1513. }
  1514. static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
  1515. {
  1516. struct rq *rq = cpu_rq(cpu);
  1517. p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
  1518. if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
  1519. if (!set_nr_if_polling(rq->idle))
  1520. smp_send_reschedule(cpu);
  1521. else
  1522. trace_sched_wake_idle_without_ipi(cpu);
  1523. }
  1524. }
  1525. void wake_up_if_idle(int cpu)
  1526. {
  1527. struct rq *rq = cpu_rq(cpu);
  1528. struct rq_flags rf;
  1529. rcu_read_lock();
  1530. if (!is_idle_task(rcu_dereference(rq->curr)))
  1531. goto out;
  1532. if (set_nr_if_polling(rq->idle)) {
  1533. trace_sched_wake_idle_without_ipi(cpu);
  1534. } else {
  1535. rq_lock_irqsave(rq, &rf);
  1536. if (is_idle_task(rq->curr))
  1537. smp_send_reschedule(cpu);
  1538. /* Else CPU is not idle, do nothing here: */
  1539. rq_unlock_irqrestore(rq, &rf);
  1540. }
  1541. out:
  1542. rcu_read_unlock();
  1543. }
  1544. bool cpus_share_cache(int this_cpu, int that_cpu)
  1545. {
  1546. return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
  1547. }
  1548. #endif /* CONFIG_SMP */
  1549. static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
  1550. {
  1551. struct rq *rq = cpu_rq(cpu);
  1552. struct rq_flags rf;
  1553. #if defined(CONFIG_SMP)
  1554. if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
  1555. sched_clock_cpu(cpu); /* Sync clocks across CPUs */
  1556. ttwu_queue_remote(p, cpu, wake_flags);
  1557. return;
  1558. }
  1559. #endif
  1560. rq_lock(rq, &rf);
  1561. update_rq_clock(rq);
  1562. ttwu_do_activate(rq, p, wake_flags, &rf);
  1563. rq_unlock(rq, &rf);
  1564. }
  1565. /*
  1566. * Notes on Program-Order guarantees on SMP systems.
  1567. *
  1568. * MIGRATION
  1569. *
  1570. * The basic program-order guarantee on SMP systems is that when a task [t]
  1571. * migrates, all its activity on its old CPU [c0] happens-before any subsequent
  1572. * execution on its new CPU [c1].
  1573. *
  1574. * For migration (of runnable tasks) this is provided by the following means:
  1575. *
  1576. * A) UNLOCK of the rq(c0)->lock scheduling out task t
  1577. * B) migration for t is required to synchronize *both* rq(c0)->lock and
  1578. * rq(c1)->lock (if not at the same time, then in that order).
  1579. * C) LOCK of the rq(c1)->lock scheduling in task
  1580. *
  1581. * Release/acquire chaining guarantees that B happens after A and C after B.
  1582. * Note: the CPU doing B need not be c0 or c1
  1583. *
  1584. * Example:
  1585. *
  1586. * CPU0 CPU1 CPU2
  1587. *
  1588. * LOCK rq(0)->lock
  1589. * sched-out X
  1590. * sched-in Y
  1591. * UNLOCK rq(0)->lock
  1592. *
  1593. * LOCK rq(0)->lock // orders against CPU0
  1594. * dequeue X
  1595. * UNLOCK rq(0)->lock
  1596. *
  1597. * LOCK rq(1)->lock
  1598. * enqueue X
  1599. * UNLOCK rq(1)->lock
  1600. *
  1601. * LOCK rq(1)->lock // orders against CPU2
  1602. * sched-out Z
  1603. * sched-in X
  1604. * UNLOCK rq(1)->lock
  1605. *
  1606. *
  1607. * BLOCKING -- aka. SLEEP + WAKEUP
  1608. *
  1609. * For blocking we (obviously) need to provide the same guarantee as for
  1610. * migration. However the means are completely different as there is no lock
  1611. * chain to provide order. Instead we do:
  1612. *
  1613. * 1) smp_store_release(X->on_cpu, 0)
  1614. * 2) smp_cond_load_acquire(!X->on_cpu)
  1615. *
  1616. * Example:
  1617. *
  1618. * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
  1619. *
  1620. * LOCK rq(0)->lock LOCK X->pi_lock
  1621. * dequeue X
  1622. * sched-out X
  1623. * smp_store_release(X->on_cpu, 0);
  1624. *
  1625. * smp_cond_load_acquire(&X->on_cpu, !VAL);
  1626. * X->state = WAKING
  1627. * set_task_cpu(X,2)
  1628. *
  1629. * LOCK rq(2)->lock
  1630. * enqueue X
  1631. * X->state = RUNNING
  1632. * UNLOCK rq(2)->lock
  1633. *
  1634. * LOCK rq(2)->lock // orders against CPU1
  1635. * sched-out Z
  1636. * sched-in X
  1637. * UNLOCK rq(2)->lock
  1638. *
  1639. * UNLOCK X->pi_lock
  1640. * UNLOCK rq(0)->lock
  1641. *
  1642. *
  1643. * However, for wakeups there is a second guarantee we must provide, namely we
  1644. * must ensure that CONDITION=1 done by the caller can not be reordered with
  1645. * accesses to the task state; see try_to_wake_up() and set_current_state().
  1646. */
  1647. /**
  1648. * try_to_wake_up - wake up a thread
  1649. * @p: the thread to be awakened
  1650. * @state: the mask of task states that can be woken
  1651. * @wake_flags: wake modifier flags (WF_*)
  1652. *
  1653. * If (@state & @p->state) @p->state = TASK_RUNNING.
  1654. *
  1655. * If the task was not queued/runnable, also place it back on a runqueue.
  1656. *
  1657. * Atomic against schedule() which would dequeue a task, also see
  1658. * set_current_state().
  1659. *
  1660. * This function executes a full memory barrier before accessing the task
  1661. * state; see set_current_state().
  1662. *
  1663. * Return: %true if @p->state changes (an actual wakeup was done),
  1664. * %false otherwise.
  1665. */
  1666. static int
  1667. try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
  1668. {
  1669. unsigned long flags;
  1670. int cpu, success = 0;
  1671. /*
  1672. * If we are going to wake up a thread waiting for CONDITION we
  1673. * need to ensure that CONDITION=1 done by the caller can not be
  1674. * reordered with p->state check below. This pairs with mb() in
  1675. * set_current_state() the waiting thread does.
  1676. */
  1677. raw_spin_lock_irqsave(&p->pi_lock, flags);
  1678. smp_mb__after_spinlock();
  1679. if (!(p->state & state))
  1680. goto out;
  1681. trace_sched_waking(p);
  1682. /* We're going to change ->state: */
  1683. success = 1;
  1684. cpu = task_cpu(p);
  1685. /*
  1686. * Ensure we load p->on_rq _after_ p->state, otherwise it would
  1687. * be possible to, falsely, observe p->on_rq == 0 and get stuck
  1688. * in smp_cond_load_acquire() below.
  1689. *
  1690. * sched_ttwu_pending() try_to_wake_up()
  1691. * STORE p->on_rq = 1 LOAD p->state
  1692. * UNLOCK rq->lock
  1693. *
  1694. * __schedule() (switch to task 'p')
  1695. * LOCK rq->lock smp_rmb();
  1696. * smp_mb__after_spinlock();
  1697. * UNLOCK rq->lock
  1698. *
  1699. * [task p]
  1700. * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq
  1701. *
  1702. * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
  1703. * __schedule(). See the comment for smp_mb__after_spinlock().
  1704. */
  1705. smp_rmb();
  1706. if (p->on_rq && ttwu_remote(p, wake_flags))
  1707. goto stat;
  1708. #ifdef CONFIG_SMP
  1709. /*
  1710. * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
  1711. * possible to, falsely, observe p->on_cpu == 0.
  1712. *
  1713. * One must be running (->on_cpu == 1) in order to remove oneself
  1714. * from the runqueue.
  1715. *
  1716. * __schedule() (switch to task 'p') try_to_wake_up()
  1717. * STORE p->on_cpu = 1 LOAD p->on_rq
  1718. * UNLOCK rq->lock
  1719. *
  1720. * __schedule() (put 'p' to sleep)
  1721. * LOCK rq->lock smp_rmb();
  1722. * smp_mb__after_spinlock();
  1723. * STORE p->on_rq = 0 LOAD p->on_cpu
  1724. *
  1725. * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
  1726. * __schedule(). See the comment for smp_mb__after_spinlock().
  1727. */
  1728. smp_rmb();
  1729. /*
  1730. * If the owning (remote) CPU is still in the middle of schedule() with
  1731. * this task as prev, wait until its done referencing the task.
  1732. *
  1733. * Pairs with the smp_store_release() in finish_task().
  1734. *
  1735. * This ensures that tasks getting woken will be fully ordered against
  1736. * their previous state and preserve Program Order.
  1737. */
  1738. smp_cond_load_acquire(&p->on_cpu, !VAL);
  1739. p->sched_contributes_to_load = !!task_contributes_to_load(p);
  1740. p->state = TASK_WAKING;
  1741. if (p->in_iowait) {
  1742. delayacct_blkio_end(p);
  1743. atomic_dec(&task_rq(p)->nr_iowait);
  1744. }
  1745. cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
  1746. if (task_cpu(p) != cpu) {
  1747. wake_flags |= WF_MIGRATED;
  1748. set_task_cpu(p, cpu);
  1749. }
  1750. #else /* CONFIG_SMP */
  1751. if (p->in_iowait) {
  1752. delayacct_blkio_end(p);
  1753. atomic_dec(&task_rq(p)->nr_iowait);
  1754. }
  1755. #endif /* CONFIG_SMP */
  1756. ttwu_queue(p, cpu, wake_flags);
  1757. stat:
  1758. ttwu_stat(p, cpu, wake_flags);
  1759. out:
  1760. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  1761. return success;
  1762. }
  1763. /**
  1764. * try_to_wake_up_local - try to wake up a local task with rq lock held
  1765. * @p: the thread to be awakened
  1766. * @rf: request-queue flags for pinning
  1767. *
  1768. * Put @p on the run-queue if it's not already there. The caller must
  1769. * ensure that this_rq() is locked, @p is bound to this_rq() and not
  1770. * the current task.
  1771. */
  1772. static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
  1773. {
  1774. struct rq *rq = task_rq(p);
  1775. if (WARN_ON_ONCE(rq != this_rq()) ||
  1776. WARN_ON_ONCE(p == current))
  1777. return;
  1778. lockdep_assert_held(&rq->lock);
  1779. if (!raw_spin_trylock(&p->pi_lock)) {
  1780. /*
  1781. * This is OK, because current is on_cpu, which avoids it being
  1782. * picked for load-balance and preemption/IRQs are still
  1783. * disabled avoiding further scheduler activity on it and we've
  1784. * not yet picked a replacement task.
  1785. */
  1786. rq_unlock(rq, rf);
  1787. raw_spin_lock(&p->pi_lock);
  1788. rq_relock(rq, rf);
  1789. }
  1790. if (!(p->state & TASK_NORMAL))
  1791. goto out;
  1792. trace_sched_waking(p);
  1793. if (!task_on_rq_queued(p)) {
  1794. if (p->in_iowait) {
  1795. delayacct_blkio_end(p);
  1796. atomic_dec(&rq->nr_iowait);
  1797. }
  1798. ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK);
  1799. }
  1800. ttwu_do_wakeup(rq, p, 0, rf);
  1801. ttwu_stat(p, smp_processor_id(), 0);
  1802. out:
  1803. raw_spin_unlock(&p->pi_lock);
  1804. }
  1805. /**
  1806. * wake_up_process - Wake up a specific process
  1807. * @p: The process to be woken up.
  1808. *
  1809. * Attempt to wake up the nominated process and move it to the set of runnable
  1810. * processes.
  1811. *
  1812. * Return: 1 if the process was woken up, 0 if it was already running.
  1813. *
  1814. * This function executes a full memory barrier before accessing the task state.
  1815. */
  1816. int wake_up_process(struct task_struct *p)
  1817. {
  1818. return try_to_wake_up(p, TASK_NORMAL, 0);
  1819. }
  1820. EXPORT_SYMBOL(wake_up_process);
  1821. int wake_up_state(struct task_struct *p, unsigned int state)
  1822. {
  1823. return try_to_wake_up(p, state, 0);
  1824. }
  1825. /*
  1826. * Perform scheduler related setup for a newly forked process p.
  1827. * p is forked by current.
  1828. *
  1829. * __sched_fork() is basic setup used by init_idle() too:
  1830. */
  1831. static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
  1832. {
  1833. p->on_rq = 0;
  1834. p->se.on_rq = 0;
  1835. p->se.exec_start = 0;
  1836. p->se.sum_exec_runtime = 0;
  1837. p->se.prev_sum_exec_runtime = 0;
  1838. p->se.nr_migrations = 0;
  1839. p->se.vruntime = 0;
  1840. INIT_LIST_HEAD(&p->se.group_node);
  1841. #ifdef CONFIG_FAIR_GROUP_SCHED
  1842. p->se.cfs_rq = NULL;
  1843. #endif
  1844. #ifdef CONFIG_SCHEDSTATS
  1845. /* Even if schedstat is disabled, there should not be garbage */
  1846. memset(&p->se.statistics, 0, sizeof(p->se.statistics));
  1847. #endif
  1848. RB_CLEAR_NODE(&p->dl.rb_node);
  1849. init_dl_task_timer(&p->dl);
  1850. init_dl_inactive_task_timer(&p->dl);
  1851. __dl_clear_params(p);
  1852. INIT_LIST_HEAD(&p->rt.run_list);
  1853. p->rt.timeout = 0;
  1854. p->rt.time_slice = sched_rr_timeslice;
  1855. p->rt.on_rq = 0;
  1856. p->rt.on_list = 0;
  1857. #ifdef CONFIG_PREEMPT_NOTIFIERS
  1858. INIT_HLIST_HEAD(&p->preempt_notifiers);
  1859. #endif
  1860. init_numa_balancing(clone_flags, p);
  1861. }
  1862. DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
  1863. #ifdef CONFIG_NUMA_BALANCING
  1864. void set_numabalancing_state(bool enabled)
  1865. {
  1866. if (enabled)
  1867. static_branch_enable(&sched_numa_balancing);
  1868. else
  1869. static_branch_disable(&sched_numa_balancing);
  1870. }
  1871. #ifdef CONFIG_PROC_SYSCTL
  1872. int sysctl_numa_balancing(struct ctl_table *table, int write,
  1873. void __user *buffer, size_t *lenp, loff_t *ppos)
  1874. {
  1875. struct ctl_table t;
  1876. int err;
  1877. int state = static_branch_likely(&sched_numa_balancing);
  1878. if (write && !capable(CAP_SYS_ADMIN))
  1879. return -EPERM;
  1880. t = *table;
  1881. t.data = &state;
  1882. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  1883. if (err < 0)
  1884. return err;
  1885. if (write)
  1886. set_numabalancing_state(state);
  1887. return err;
  1888. }
  1889. #endif
  1890. #endif
  1891. #ifdef CONFIG_SCHEDSTATS
  1892. DEFINE_STATIC_KEY_FALSE(sched_schedstats);
  1893. static bool __initdata __sched_schedstats = false;
  1894. static void set_schedstats(bool enabled)
  1895. {
  1896. if (enabled)
  1897. static_branch_enable(&sched_schedstats);
  1898. else
  1899. static_branch_disable(&sched_schedstats);
  1900. }
  1901. void force_schedstat_enabled(void)
  1902. {
  1903. if (!schedstat_enabled()) {
  1904. pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
  1905. static_branch_enable(&sched_schedstats);
  1906. }
  1907. }
  1908. static int __init setup_schedstats(char *str)
  1909. {
  1910. int ret = 0;
  1911. if (!str)
  1912. goto out;
  1913. /*
  1914. * This code is called before jump labels have been set up, so we can't
  1915. * change the static branch directly just yet. Instead set a temporary
  1916. * variable so init_schedstats() can do it later.
  1917. */
  1918. if (!strcmp(str, "enable")) {
  1919. __sched_schedstats = true;
  1920. ret = 1;
  1921. } else if (!strcmp(str, "disable")) {
  1922. __sched_schedstats = false;
  1923. ret = 1;
  1924. }
  1925. out:
  1926. if (!ret)
  1927. pr_warn("Unable to parse schedstats=\n");
  1928. return ret;
  1929. }
  1930. __setup("schedstats=", setup_schedstats);
  1931. static void __init init_schedstats(void)
  1932. {
  1933. set_schedstats(__sched_schedstats);
  1934. }
  1935. #ifdef CONFIG_PROC_SYSCTL
  1936. int sysctl_schedstats(struct ctl_table *table, int write,
  1937. void __user *buffer, size_t *lenp, loff_t *ppos)
  1938. {
  1939. struct ctl_table t;
  1940. int err;
  1941. int state = static_branch_likely(&sched_schedstats);
  1942. if (write && !capable(CAP_SYS_ADMIN))
  1943. return -EPERM;
  1944. t = *table;
  1945. t.data = &state;
  1946. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  1947. if (err < 0)
  1948. return err;
  1949. if (write)
  1950. set_schedstats(state);
  1951. return err;
  1952. }
  1953. #endif /* CONFIG_PROC_SYSCTL */
  1954. #else /* !CONFIG_SCHEDSTATS */
  1955. static inline void init_schedstats(void) {}
  1956. #endif /* CONFIG_SCHEDSTATS */
  1957. /*
  1958. * fork()/clone()-time setup:
  1959. */
  1960. int sched_fork(unsigned long clone_flags, struct task_struct *p)
  1961. {
  1962. unsigned long flags;
  1963. __sched_fork(clone_flags, p);
  1964. /*
  1965. * We mark the process as NEW here. This guarantees that
  1966. * nobody will actually run it, and a signal or other external
  1967. * event cannot wake it up and insert it on the runqueue either.
  1968. */
  1969. p->state = TASK_NEW;
  1970. /*
  1971. * Make sure we do not leak PI boosting priority to the child.
  1972. */
  1973. p->prio = current->normal_prio;
  1974. /*
  1975. * Revert to default priority/policy on fork if requested.
  1976. */
  1977. if (unlikely(p->sched_reset_on_fork)) {
  1978. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  1979. p->policy = SCHED_NORMAL;
  1980. p->static_prio = NICE_TO_PRIO(0);
  1981. p->rt_priority = 0;
  1982. } else if (PRIO_TO_NICE(p->static_prio) < 0)
  1983. p->static_prio = NICE_TO_PRIO(0);
  1984. p->prio = p->normal_prio = __normal_prio(p);
  1985. set_load_weight(p, false);
  1986. /*
  1987. * We don't need the reset flag anymore after the fork. It has
  1988. * fulfilled its duty:
  1989. */
  1990. p->sched_reset_on_fork = 0;
  1991. }
  1992. if (dl_prio(p->prio))
  1993. return -EAGAIN;
  1994. else if (rt_prio(p->prio))
  1995. p->sched_class = &rt_sched_class;
  1996. else
  1997. p->sched_class = &fair_sched_class;
  1998. init_entity_runnable_average(&p->se);
  1999. /*
  2000. * The child is not yet in the pid-hash so no cgroup attach races,
  2001. * and the cgroup is pinned to this child due to cgroup_fork()
  2002. * is ran before sched_fork().
  2003. *
  2004. * Silence PROVE_RCU.
  2005. */
  2006. raw_spin_lock_irqsave(&p->pi_lock, flags);
  2007. /*
  2008. * We're setting the CPU for the first time, we don't migrate,
  2009. * so use __set_task_cpu().
  2010. */
  2011. __set_task_cpu(p, smp_processor_id());
  2012. if (p->sched_class->task_fork)
  2013. p->sched_class->task_fork(p);
  2014. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  2015. #ifdef CONFIG_SCHED_INFO
  2016. if (likely(sched_info_on()))
  2017. memset(&p->sched_info, 0, sizeof(p->sched_info));
  2018. #endif
  2019. #if defined(CONFIG_SMP)
  2020. p->on_cpu = 0;
  2021. #endif
  2022. init_task_preempt_count(p);
  2023. #ifdef CONFIG_SMP
  2024. plist_node_init(&p->pushable_tasks, MAX_PRIO);
  2025. RB_CLEAR_NODE(&p->pushable_dl_tasks);
  2026. #endif
  2027. return 0;
  2028. }
  2029. unsigned long to_ratio(u64 period, u64 runtime)
  2030. {
  2031. if (runtime == RUNTIME_INF)
  2032. return BW_UNIT;
  2033. /*
  2034. * Doing this here saves a lot of checks in all
  2035. * the calling paths, and returning zero seems
  2036. * safe for them anyway.
  2037. */
  2038. if (period == 0)
  2039. return 0;
  2040. return div64_u64(runtime << BW_SHIFT, period);
  2041. }
  2042. /*
  2043. * wake_up_new_task - wake up a newly created task for the first time.
  2044. *
  2045. * This function will do some initial scheduler statistics housekeeping
  2046. * that must be done for every newly created context, then puts the task
  2047. * on the runqueue and wakes it.
  2048. */
  2049. void wake_up_new_task(struct task_struct *p)
  2050. {
  2051. struct rq_flags rf;
  2052. struct rq *rq;
  2053. raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
  2054. p->state = TASK_RUNNING;
  2055. #ifdef CONFIG_SMP
  2056. /*
  2057. * Fork balancing, do it here and not earlier because:
  2058. * - cpus_allowed can change in the fork path
  2059. * - any previously selected CPU might disappear through hotplug
  2060. *
  2061. * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
  2062. * as we're not fully set-up yet.
  2063. */
  2064. p->recent_used_cpu = task_cpu(p);
  2065. __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
  2066. #endif
  2067. rq = __task_rq_lock(p, &rf);
  2068. update_rq_clock(rq);
  2069. post_init_entity_util_avg(&p->se);
  2070. activate_task(rq, p, ENQUEUE_NOCLOCK);
  2071. p->on_rq = TASK_ON_RQ_QUEUED;
  2072. trace_sched_wakeup_new(p);
  2073. check_preempt_curr(rq, p, WF_FORK);
  2074. #ifdef CONFIG_SMP
  2075. if (p->sched_class->task_woken) {
  2076. /*
  2077. * Nothing relies on rq->lock after this, so its fine to
  2078. * drop it.
  2079. */
  2080. rq_unpin_lock(rq, &rf);
  2081. p->sched_class->task_woken(rq, p);
  2082. rq_repin_lock(rq, &rf);
  2083. }
  2084. #endif
  2085. task_rq_unlock(rq, p, &rf);
  2086. }
  2087. #ifdef CONFIG_PREEMPT_NOTIFIERS
  2088. static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
  2089. void preempt_notifier_inc(void)
  2090. {
  2091. static_branch_inc(&preempt_notifier_key);
  2092. }
  2093. EXPORT_SYMBOL_GPL(preempt_notifier_inc);
  2094. void preempt_notifier_dec(void)
  2095. {
  2096. static_branch_dec(&preempt_notifier_key);
  2097. }
  2098. EXPORT_SYMBOL_GPL(preempt_notifier_dec);
  2099. /**
  2100. * preempt_notifier_register - tell me when current is being preempted & rescheduled
  2101. * @notifier: notifier struct to register
  2102. */
  2103. void preempt_notifier_register(struct preempt_notifier *notifier)
  2104. {
  2105. if (!static_branch_unlikely(&preempt_notifier_key))
  2106. WARN(1, "registering preempt_notifier while notifiers disabled\n");
  2107. hlist_add_head(&notifier->link, &current->preempt_notifiers);
  2108. }
  2109. EXPORT_SYMBOL_GPL(preempt_notifier_register);
  2110. /**
  2111. * preempt_notifier_unregister - no longer interested in preemption notifications
  2112. * @notifier: notifier struct to unregister
  2113. *
  2114. * This is *not* safe to call from within a preemption notifier.
  2115. */
  2116. void preempt_notifier_unregister(struct preempt_notifier *notifier)
  2117. {
  2118. hlist_del(&notifier->link);
  2119. }
  2120. EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
  2121. static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
  2122. {
  2123. struct preempt_notifier *notifier;
  2124. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  2125. notifier->ops->sched_in(notifier, raw_smp_processor_id());
  2126. }
  2127. static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  2128. {
  2129. if (static_branch_unlikely(&preempt_notifier_key))
  2130. __fire_sched_in_preempt_notifiers(curr);
  2131. }
  2132. static void
  2133. __fire_sched_out_preempt_notifiers(struct task_struct *curr,
  2134. struct task_struct *next)
  2135. {
  2136. struct preempt_notifier *notifier;
  2137. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  2138. notifier->ops->sched_out(notifier, next);
  2139. }
  2140. static __always_inline void
  2141. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  2142. struct task_struct *next)
  2143. {
  2144. if (static_branch_unlikely(&preempt_notifier_key))
  2145. __fire_sched_out_preempt_notifiers(curr, next);
  2146. }
  2147. #else /* !CONFIG_PREEMPT_NOTIFIERS */
  2148. static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  2149. {
  2150. }
  2151. static inline void
  2152. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  2153. struct task_struct *next)
  2154. {
  2155. }
  2156. #endif /* CONFIG_PREEMPT_NOTIFIERS */
  2157. static inline void prepare_task(struct task_struct *next)
  2158. {
  2159. #ifdef CONFIG_SMP
  2160. /*
  2161. * Claim the task as running, we do this before switching to it
  2162. * such that any running task will have this set.
  2163. */
  2164. next->on_cpu = 1;
  2165. #endif
  2166. }
  2167. static inline void finish_task(struct task_struct *prev)
  2168. {
  2169. #ifdef CONFIG_SMP
  2170. /*
  2171. * After ->on_cpu is cleared, the task can be moved to a different CPU.
  2172. * We must ensure this doesn't happen until the switch is completely
  2173. * finished.
  2174. *
  2175. * In particular, the load of prev->state in finish_task_switch() must
  2176. * happen before this.
  2177. *
  2178. * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
  2179. */
  2180. smp_store_release(&prev->on_cpu, 0);
  2181. #endif
  2182. }
  2183. static inline void
  2184. prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
  2185. {
  2186. /*
  2187. * Since the runqueue lock will be released by the next
  2188. * task (which is an invalid locking op but in the case
  2189. * of the scheduler it's an obvious special-case), so we
  2190. * do an early lockdep release here:
  2191. */
  2192. rq_unpin_lock(rq, rf);
  2193. spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
  2194. #ifdef CONFIG_DEBUG_SPINLOCK
  2195. /* this is a valid case when another task releases the spinlock */
  2196. rq->lock.owner = next;
  2197. #endif
  2198. }
  2199. static inline void finish_lock_switch(struct rq *rq)
  2200. {
  2201. /*
  2202. * If we are tracking spinlock dependencies then we have to
  2203. * fix up the runqueue lock - which gets 'carried over' from
  2204. * prev into current:
  2205. */
  2206. spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
  2207. raw_spin_unlock_irq(&rq->lock);
  2208. }
  2209. /*
  2210. * NOP if the arch has not defined these:
  2211. */
  2212. #ifndef prepare_arch_switch
  2213. # define prepare_arch_switch(next) do { } while (0)
  2214. #endif
  2215. #ifndef finish_arch_post_lock_switch
  2216. # define finish_arch_post_lock_switch() do { } while (0)
  2217. #endif
  2218. /**
  2219. * prepare_task_switch - prepare to switch tasks
  2220. * @rq: the runqueue preparing to switch
  2221. * @prev: the current task that is being switched out
  2222. * @next: the task we are going to switch to.
  2223. *
  2224. * This is called with the rq lock held and interrupts off. It must
  2225. * be paired with a subsequent finish_task_switch after the context
  2226. * switch.
  2227. *
  2228. * prepare_task_switch sets up locking and calls architecture specific
  2229. * hooks.
  2230. */
  2231. static inline void
  2232. prepare_task_switch(struct rq *rq, struct task_struct *prev,
  2233. struct task_struct *next)
  2234. {
  2235. kcov_prepare_switch(prev);
  2236. sched_info_switch(rq, prev, next);
  2237. perf_event_task_sched_out(prev, next);
  2238. rseq_preempt(prev);
  2239. fire_sched_out_preempt_notifiers(prev, next);
  2240. prepare_task(next);
  2241. prepare_arch_switch(next);
  2242. }
  2243. /**
  2244. * finish_task_switch - clean up after a task-switch
  2245. * @prev: the thread we just switched away from.
  2246. *
  2247. * finish_task_switch must be called after the context switch, paired
  2248. * with a prepare_task_switch call before the context switch.
  2249. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  2250. * and do any other architecture-specific cleanup actions.
  2251. *
  2252. * Note that we may have delayed dropping an mm in context_switch(). If
  2253. * so, we finish that here outside of the runqueue lock. (Doing it
  2254. * with the lock held can cause deadlocks; see schedule() for
  2255. * details.)
  2256. *
  2257. * The context switch have flipped the stack from under us and restored the
  2258. * local variables which were saved when this task called schedule() in the
  2259. * past. prev == current is still correct but we need to recalculate this_rq
  2260. * because prev may have moved to another CPU.
  2261. */
  2262. static struct rq *finish_task_switch(struct task_struct *prev)
  2263. __releases(rq->lock)
  2264. {
  2265. struct rq *rq = this_rq();
  2266. struct mm_struct *mm = rq->prev_mm;
  2267. long prev_state;
  2268. /*
  2269. * The previous task will have left us with a preempt_count of 2
  2270. * because it left us after:
  2271. *
  2272. * schedule()
  2273. * preempt_disable(); // 1
  2274. * __schedule()
  2275. * raw_spin_lock_irq(&rq->lock) // 2
  2276. *
  2277. * Also, see FORK_PREEMPT_COUNT.
  2278. */
  2279. if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
  2280. "corrupted preempt_count: %s/%d/0x%x\n",
  2281. current->comm, current->pid, preempt_count()))
  2282. preempt_count_set(FORK_PREEMPT_COUNT);
  2283. rq->prev_mm = NULL;
  2284. /*
  2285. * A task struct has one reference for the use as "current".
  2286. * If a task dies, then it sets TASK_DEAD in tsk->state and calls
  2287. * schedule one last time. The schedule call will never return, and
  2288. * the scheduled task must drop that reference.
  2289. *
  2290. * We must observe prev->state before clearing prev->on_cpu (in
  2291. * finish_task), otherwise a concurrent wakeup can get prev
  2292. * running on another CPU and we could rave with its RUNNING -> DEAD
  2293. * transition, resulting in a double drop.
  2294. */
  2295. prev_state = prev->state;
  2296. vtime_task_switch(prev);
  2297. perf_event_task_sched_in(prev, current);
  2298. finish_task(prev);
  2299. finish_lock_switch(rq);
  2300. finish_arch_post_lock_switch();
  2301. kcov_finish_switch(current);
  2302. fire_sched_in_preempt_notifiers(current);
  2303. /*
  2304. * When switching through a kernel thread, the loop in
  2305. * membarrier_{private,global}_expedited() may have observed that
  2306. * kernel thread and not issued an IPI. It is therefore possible to
  2307. * schedule between user->kernel->user threads without passing though
  2308. * switch_mm(). Membarrier requires a barrier after storing to
  2309. * rq->curr, before returning to userspace, so provide them here:
  2310. *
  2311. * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
  2312. * provided by mmdrop(),
  2313. * - a sync_core for SYNC_CORE.
  2314. */
  2315. if (mm) {
  2316. membarrier_mm_sync_core_before_usermode(mm);
  2317. mmdrop(mm);
  2318. }
  2319. if (unlikely(prev_state == TASK_DEAD)) {
  2320. if (prev->sched_class->task_dead)
  2321. prev->sched_class->task_dead(prev);
  2322. /*
  2323. * Remove function-return probe instances associated with this
  2324. * task and put them back on the free list.
  2325. */
  2326. kprobe_flush_task(prev);
  2327. /* Task is done with its stack. */
  2328. put_task_stack(prev);
  2329. put_task_struct(prev);
  2330. }
  2331. tick_nohz_task_switch();
  2332. return rq;
  2333. }
  2334. #ifdef CONFIG_SMP
  2335. /* rq->lock is NOT held, but preemption is disabled */
  2336. static void __balance_callback(struct rq *rq)
  2337. {
  2338. struct callback_head *head, *next;
  2339. void (*func)(struct rq *rq);
  2340. unsigned long flags;
  2341. raw_spin_lock_irqsave(&rq->lock, flags);
  2342. head = rq->balance_callback;
  2343. rq->balance_callback = NULL;
  2344. while (head) {
  2345. func = (void (*)(struct rq *))head->func;
  2346. next = head->next;
  2347. head->next = NULL;
  2348. head = next;
  2349. func(rq);
  2350. }
  2351. raw_spin_unlock_irqrestore(&rq->lock, flags);
  2352. }
  2353. static inline void balance_callback(struct rq *rq)
  2354. {
  2355. if (unlikely(rq->balance_callback))
  2356. __balance_callback(rq);
  2357. }
  2358. #else
  2359. static inline void balance_callback(struct rq *rq)
  2360. {
  2361. }
  2362. #endif
  2363. /**
  2364. * schedule_tail - first thing a freshly forked thread must call.
  2365. * @prev: the thread we just switched away from.
  2366. */
  2367. asmlinkage __visible void schedule_tail(struct task_struct *prev)
  2368. __releases(rq->lock)
  2369. {
  2370. struct rq *rq;
  2371. /*
  2372. * New tasks start with FORK_PREEMPT_COUNT, see there and
  2373. * finish_task_switch() for details.
  2374. *
  2375. * finish_task_switch() will drop rq->lock() and lower preempt_count
  2376. * and the preempt_enable() will end up enabling preemption (on
  2377. * PREEMPT_COUNT kernels).
  2378. */
  2379. rq = finish_task_switch(prev);
  2380. balance_callback(rq);
  2381. preempt_enable();
  2382. if (current->set_child_tid)
  2383. put_user(task_pid_vnr(current), current->set_child_tid);
  2384. calculate_sigpending();
  2385. }
  2386. /*
  2387. * context_switch - switch to the new MM and the new thread's register state.
  2388. */
  2389. static __always_inline struct rq *
  2390. context_switch(struct rq *rq, struct task_struct *prev,
  2391. struct task_struct *next, struct rq_flags *rf)
  2392. {
  2393. struct mm_struct *mm, *oldmm;
  2394. prepare_task_switch(rq, prev, next);
  2395. mm = next->mm;
  2396. oldmm = prev->active_mm;
  2397. /*
  2398. * For paravirt, this is coupled with an exit in switch_to to
  2399. * combine the page table reload and the switch backend into
  2400. * one hypercall.
  2401. */
  2402. arch_start_context_switch(prev);
  2403. /*
  2404. * If mm is non-NULL, we pass through switch_mm(). If mm is
  2405. * NULL, we will pass through mmdrop() in finish_task_switch().
  2406. * Both of these contain the full memory barrier required by
  2407. * membarrier after storing to rq->curr, before returning to
  2408. * user-space.
  2409. */
  2410. if (!mm) {
  2411. next->active_mm = oldmm;
  2412. mmgrab(oldmm);
  2413. enter_lazy_tlb(oldmm, next);
  2414. } else
  2415. switch_mm_irqs_off(oldmm, mm, next);
  2416. if (!prev->mm) {
  2417. prev->active_mm = NULL;
  2418. rq->prev_mm = oldmm;
  2419. }
  2420. rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
  2421. prepare_lock_switch(rq, next, rf);
  2422. /* Here we just switch the register state and the stack. */
  2423. switch_to(prev, next, prev);
  2424. barrier();
  2425. return finish_task_switch(prev);
  2426. }
  2427. /*
  2428. * nr_running and nr_context_switches:
  2429. *
  2430. * externally visible scheduler statistics: current number of runnable
  2431. * threads, total number of context switches performed since bootup.
  2432. */
  2433. unsigned long nr_running(void)
  2434. {
  2435. unsigned long i, sum = 0;
  2436. for_each_online_cpu(i)
  2437. sum += cpu_rq(i)->nr_running;
  2438. return sum;
  2439. }
  2440. /*
  2441. * Check if only the current task is running on the CPU.
  2442. *
  2443. * Caution: this function does not check that the caller has disabled
  2444. * preemption, thus the result might have a time-of-check-to-time-of-use
  2445. * race. The caller is responsible to use it correctly, for example:
  2446. *
  2447. * - from a non-preemptable section (of course)
  2448. *
  2449. * - from a thread that is bound to a single CPU
  2450. *
  2451. * - in a loop with very short iterations (e.g. a polling loop)
  2452. */
  2453. bool single_task_running(void)
  2454. {
  2455. return raw_rq()->nr_running == 1;
  2456. }
  2457. EXPORT_SYMBOL(single_task_running);
  2458. unsigned long long nr_context_switches(void)
  2459. {
  2460. int i;
  2461. unsigned long long sum = 0;
  2462. for_each_possible_cpu(i)
  2463. sum += cpu_rq(i)->nr_switches;
  2464. return sum;
  2465. }
  2466. /*
  2467. * IO-wait accounting, and how its mostly bollocks (on SMP).
  2468. *
  2469. * The idea behind IO-wait account is to account the idle time that we could
  2470. * have spend running if it were not for IO. That is, if we were to improve the
  2471. * storage performance, we'd have a proportional reduction in IO-wait time.
  2472. *
  2473. * This all works nicely on UP, where, when a task blocks on IO, we account
  2474. * idle time as IO-wait, because if the storage were faster, it could've been
  2475. * running and we'd not be idle.
  2476. *
  2477. * This has been extended to SMP, by doing the same for each CPU. This however
  2478. * is broken.
  2479. *
  2480. * Imagine for instance the case where two tasks block on one CPU, only the one
  2481. * CPU will have IO-wait accounted, while the other has regular idle. Even
  2482. * though, if the storage were faster, both could've ran at the same time,
  2483. * utilising both CPUs.
  2484. *
  2485. * This means, that when looking globally, the current IO-wait accounting on
  2486. * SMP is a lower bound, by reason of under accounting.
  2487. *
  2488. * Worse, since the numbers are provided per CPU, they are sometimes
  2489. * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
  2490. * associated with any one particular CPU, it can wake to another CPU than it
  2491. * blocked on. This means the per CPU IO-wait number is meaningless.
  2492. *
  2493. * Task CPU affinities can make all that even more 'interesting'.
  2494. */
  2495. unsigned long nr_iowait(void)
  2496. {
  2497. unsigned long i, sum = 0;
  2498. for_each_possible_cpu(i)
  2499. sum += atomic_read(&cpu_rq(i)->nr_iowait);
  2500. return sum;
  2501. }
  2502. /*
  2503. * Consumers of these two interfaces, like for example the cpufreq menu
  2504. * governor are using nonsensical data. Boosting frequency for a CPU that has
  2505. * IO-wait which might not even end up running the task when it does become
  2506. * runnable.
  2507. */
  2508. unsigned long nr_iowait_cpu(int cpu)
  2509. {
  2510. struct rq *this = cpu_rq(cpu);
  2511. return atomic_read(&this->nr_iowait);
  2512. }
  2513. void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
  2514. {
  2515. struct rq *rq = this_rq();
  2516. *nr_waiters = atomic_read(&rq->nr_iowait);
  2517. *load = rq->load.weight;
  2518. }
  2519. #ifdef CONFIG_SMP
  2520. /*
  2521. * sched_exec - execve() is a valuable balancing opportunity, because at
  2522. * this point the task has the smallest effective memory and cache footprint.
  2523. */
  2524. void sched_exec(void)
  2525. {
  2526. struct task_struct *p = current;
  2527. unsigned long flags;
  2528. int dest_cpu;
  2529. raw_spin_lock_irqsave(&p->pi_lock, flags);
  2530. dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
  2531. if (dest_cpu == smp_processor_id())
  2532. goto unlock;
  2533. if (likely(cpu_active(dest_cpu))) {
  2534. struct migration_arg arg = { p, dest_cpu };
  2535. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  2536. stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
  2537. return;
  2538. }
  2539. unlock:
  2540. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  2541. }
  2542. #endif
  2543. DEFINE_PER_CPU(struct kernel_stat, kstat);
  2544. DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
  2545. EXPORT_PER_CPU_SYMBOL(kstat);
  2546. EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
  2547. /*
  2548. * The function fair_sched_class.update_curr accesses the struct curr
  2549. * and its field curr->exec_start; when called from task_sched_runtime(),
  2550. * we observe a high rate of cache misses in practice.
  2551. * Prefetching this data results in improved performance.
  2552. */
  2553. static inline void prefetch_curr_exec_start(struct task_struct *p)
  2554. {
  2555. #ifdef CONFIG_FAIR_GROUP_SCHED
  2556. struct sched_entity *curr = (&p->se)->cfs_rq->curr;
  2557. #else
  2558. struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
  2559. #endif
  2560. prefetch(curr);
  2561. prefetch(&curr->exec_start);
  2562. }
  2563. /*
  2564. * Return accounted runtime for the task.
  2565. * In case the task is currently running, return the runtime plus current's
  2566. * pending runtime that have not been accounted yet.
  2567. */
  2568. unsigned long long task_sched_runtime(struct task_struct *p)
  2569. {
  2570. struct rq_flags rf;
  2571. struct rq *rq;
  2572. u64 ns;
  2573. #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
  2574. /*
  2575. * 64-bit doesn't need locks to atomically read a 64-bit value.
  2576. * So we have a optimization chance when the task's delta_exec is 0.
  2577. * Reading ->on_cpu is racy, but this is ok.
  2578. *
  2579. * If we race with it leaving CPU, we'll take a lock. So we're correct.
  2580. * If we race with it entering CPU, unaccounted time is 0. This is
  2581. * indistinguishable from the read occurring a few cycles earlier.
  2582. * If we see ->on_cpu without ->on_rq, the task is leaving, and has
  2583. * been accounted, so we're correct here as well.
  2584. */
  2585. if (!p->on_cpu || !task_on_rq_queued(p))
  2586. return p->se.sum_exec_runtime;
  2587. #endif
  2588. rq = task_rq_lock(p, &rf);
  2589. /*
  2590. * Must be ->curr _and_ ->on_rq. If dequeued, we would
  2591. * project cycles that may never be accounted to this
  2592. * thread, breaking clock_gettime().
  2593. */
  2594. if (task_current(rq, p) && task_on_rq_queued(p)) {
  2595. prefetch_curr_exec_start(p);
  2596. update_rq_clock(rq);
  2597. p->sched_class->update_curr(rq);
  2598. }
  2599. ns = p->se.sum_exec_runtime;
  2600. task_rq_unlock(rq, p, &rf);
  2601. return ns;
  2602. }
  2603. /*
  2604. * This function gets called by the timer code, with HZ frequency.
  2605. * We call it with interrupts disabled.
  2606. */
  2607. void scheduler_tick(void)
  2608. {
  2609. int cpu = smp_processor_id();
  2610. struct rq *rq = cpu_rq(cpu);
  2611. struct task_struct *curr = rq->curr;
  2612. struct rq_flags rf;
  2613. sched_clock_tick();
  2614. rq_lock(rq, &rf);
  2615. update_rq_clock(rq);
  2616. curr->sched_class->task_tick(rq, curr, 0);
  2617. cpu_load_update_active(rq);
  2618. calc_global_load_tick(rq);
  2619. rq_unlock(rq, &rf);
  2620. perf_event_task_tick();
  2621. #ifdef CONFIG_SMP
  2622. rq->idle_balance = idle_cpu(cpu);
  2623. trigger_load_balance(rq);
  2624. #endif
  2625. }
  2626. #ifdef CONFIG_NO_HZ_FULL
  2627. struct tick_work {
  2628. int cpu;
  2629. atomic_t state;
  2630. struct delayed_work work;
  2631. };
  2632. /* Values for ->state, see diagram below. */
  2633. #define TICK_SCHED_REMOTE_OFFLINE 0
  2634. #define TICK_SCHED_REMOTE_OFFLINING 1
  2635. #define TICK_SCHED_REMOTE_RUNNING 2
  2636. /*
  2637. * State diagram for ->state:
  2638. *
  2639. *
  2640. * TICK_SCHED_REMOTE_OFFLINE
  2641. * | ^
  2642. * | |
  2643. * | | sched_tick_remote()
  2644. * | |
  2645. * | |
  2646. * +--TICK_SCHED_REMOTE_OFFLINING
  2647. * | ^
  2648. * | |
  2649. * sched_tick_start() | | sched_tick_stop()
  2650. * | |
  2651. * V |
  2652. * TICK_SCHED_REMOTE_RUNNING
  2653. *
  2654. *
  2655. * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
  2656. * and sched_tick_start() are happy to leave the state in RUNNING.
  2657. */
  2658. static struct tick_work __percpu *tick_work_cpu;
  2659. static void sched_tick_remote(struct work_struct *work)
  2660. {
  2661. struct delayed_work *dwork = to_delayed_work(work);
  2662. struct tick_work *twork = container_of(dwork, struct tick_work, work);
  2663. int cpu = twork->cpu;
  2664. struct rq *rq = cpu_rq(cpu);
  2665. struct task_struct *curr;
  2666. struct rq_flags rf;
  2667. u64 delta;
  2668. int os;
  2669. /*
  2670. * Handle the tick only if it appears the remote CPU is running in full
  2671. * dynticks mode. The check is racy by nature, but missing a tick or
  2672. * having one too much is no big deal because the scheduler tick updates
  2673. * statistics and checks timeslices in a time-independent way, regardless
  2674. * of when exactly it is running.
  2675. */
  2676. if (idle_cpu(cpu) || !tick_nohz_tick_stopped_cpu(cpu))
  2677. goto out_requeue;
  2678. rq_lock_irq(rq, &rf);
  2679. curr = rq->curr;
  2680. if (is_idle_task(curr) || cpu_is_offline(cpu))
  2681. goto out_unlock;
  2682. update_rq_clock(rq);
  2683. delta = rq_clock_task(rq) - curr->se.exec_start;
  2684. /*
  2685. * Make sure the next tick runs within a reasonable
  2686. * amount of time.
  2687. */
  2688. WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
  2689. curr->sched_class->task_tick(rq, curr, 0);
  2690. out_unlock:
  2691. rq_unlock_irq(rq, &rf);
  2692. out_requeue:
  2693. /*
  2694. * Run the remote tick once per second (1Hz). This arbitrary
  2695. * frequency is large enough to avoid overload but short enough
  2696. * to keep scheduler internal stats reasonably up to date. But
  2697. * first update state to reflect hotplug activity if required.
  2698. */
  2699. os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
  2700. WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
  2701. if (os == TICK_SCHED_REMOTE_RUNNING)
  2702. queue_delayed_work(system_unbound_wq, dwork, HZ);
  2703. }
  2704. static void sched_tick_start(int cpu)
  2705. {
  2706. int os;
  2707. struct tick_work *twork;
  2708. if (housekeeping_cpu(cpu, HK_FLAG_TICK))
  2709. return;
  2710. WARN_ON_ONCE(!tick_work_cpu);
  2711. twork = per_cpu_ptr(tick_work_cpu, cpu);
  2712. os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
  2713. WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
  2714. if (os == TICK_SCHED_REMOTE_OFFLINE) {
  2715. twork->cpu = cpu;
  2716. INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
  2717. queue_delayed_work(system_unbound_wq, &twork->work, HZ);
  2718. }
  2719. }
  2720. #ifdef CONFIG_HOTPLUG_CPU
  2721. static void sched_tick_stop(int cpu)
  2722. {
  2723. struct tick_work *twork;
  2724. int os;
  2725. if (housekeeping_cpu(cpu, HK_FLAG_TICK))
  2726. return;
  2727. WARN_ON_ONCE(!tick_work_cpu);
  2728. twork = per_cpu_ptr(tick_work_cpu, cpu);
  2729. /* There cannot be competing actions, but don't rely on stop-machine. */
  2730. os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
  2731. WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
  2732. /* Don't cancel, as this would mess up the state machine. */
  2733. }
  2734. #endif /* CONFIG_HOTPLUG_CPU */
  2735. int __init sched_tick_offload_init(void)
  2736. {
  2737. tick_work_cpu = alloc_percpu(struct tick_work);
  2738. BUG_ON(!tick_work_cpu);
  2739. return 0;
  2740. }
  2741. #else /* !CONFIG_NO_HZ_FULL */
  2742. static inline void sched_tick_start(int cpu) { }
  2743. static inline void sched_tick_stop(int cpu) { }
  2744. #endif
  2745. #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
  2746. defined(CONFIG_TRACE_PREEMPT_TOGGLE))
  2747. /*
  2748. * If the value passed in is equal to the current preempt count
  2749. * then we just disabled preemption. Start timing the latency.
  2750. */
  2751. static inline void preempt_latency_start(int val)
  2752. {
  2753. if (preempt_count() == val) {
  2754. unsigned long ip = get_lock_parent_ip();
  2755. #ifdef CONFIG_DEBUG_PREEMPT
  2756. current->preempt_disable_ip = ip;
  2757. #endif
  2758. trace_preempt_off(CALLER_ADDR0, ip);
  2759. }
  2760. }
  2761. void preempt_count_add(int val)
  2762. {
  2763. #ifdef CONFIG_DEBUG_PREEMPT
  2764. /*
  2765. * Underflow?
  2766. */
  2767. if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
  2768. return;
  2769. #endif
  2770. __preempt_count_add(val);
  2771. #ifdef CONFIG_DEBUG_PREEMPT
  2772. /*
  2773. * Spinlock count overflowing soon?
  2774. */
  2775. DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
  2776. PREEMPT_MASK - 10);
  2777. #endif
  2778. preempt_latency_start(val);
  2779. }
  2780. EXPORT_SYMBOL(preempt_count_add);
  2781. NOKPROBE_SYMBOL(preempt_count_add);
  2782. /*
  2783. * If the value passed in equals to the current preempt count
  2784. * then we just enabled preemption. Stop timing the latency.
  2785. */
  2786. static inline void preempt_latency_stop(int val)
  2787. {
  2788. if (preempt_count() == val)
  2789. trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
  2790. }
  2791. void preempt_count_sub(int val)
  2792. {
  2793. #ifdef CONFIG_DEBUG_PREEMPT
  2794. /*
  2795. * Underflow?
  2796. */
  2797. if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
  2798. return;
  2799. /*
  2800. * Is the spinlock portion underflowing?
  2801. */
  2802. if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
  2803. !(preempt_count() & PREEMPT_MASK)))
  2804. return;
  2805. #endif
  2806. preempt_latency_stop(val);
  2807. __preempt_count_sub(val);
  2808. }
  2809. EXPORT_SYMBOL(preempt_count_sub);
  2810. NOKPROBE_SYMBOL(preempt_count_sub);
  2811. #else
  2812. static inline void preempt_latency_start(int val) { }
  2813. static inline void preempt_latency_stop(int val) { }
  2814. #endif
  2815. static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
  2816. {
  2817. #ifdef CONFIG_DEBUG_PREEMPT
  2818. return p->preempt_disable_ip;
  2819. #else
  2820. return 0;
  2821. #endif
  2822. }
  2823. /*
  2824. * Print scheduling while atomic bug:
  2825. */
  2826. static noinline void __schedule_bug(struct task_struct *prev)
  2827. {
  2828. /* Save this before calling printk(), since that will clobber it */
  2829. unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
  2830. if (oops_in_progress)
  2831. return;
  2832. printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
  2833. prev->comm, prev->pid, preempt_count());
  2834. debug_show_held_locks(prev);
  2835. print_modules();
  2836. if (irqs_disabled())
  2837. print_irqtrace_events(prev);
  2838. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
  2839. && in_atomic_preempt_off()) {
  2840. pr_err("Preemption disabled at:");
  2841. print_ip_sym(preempt_disable_ip);
  2842. pr_cont("\n");
  2843. }
  2844. if (panic_on_warn)
  2845. panic("scheduling while atomic\n");
  2846. dump_stack();
  2847. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  2848. }
  2849. /*
  2850. * Various schedule()-time debugging checks and statistics:
  2851. */
  2852. static inline void schedule_debug(struct task_struct *prev)
  2853. {
  2854. #ifdef CONFIG_SCHED_STACK_END_CHECK
  2855. if (task_stack_end_corrupted(prev))
  2856. panic("corrupted stack end detected inside scheduler\n");
  2857. #endif
  2858. if (unlikely(in_atomic_preempt_off())) {
  2859. __schedule_bug(prev);
  2860. preempt_count_set(PREEMPT_DISABLED);
  2861. }
  2862. rcu_sleep_check();
  2863. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  2864. schedstat_inc(this_rq()->sched_count);
  2865. }
  2866. /*
  2867. * Pick up the highest-prio task:
  2868. */
  2869. static inline struct task_struct *
  2870. pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  2871. {
  2872. const struct sched_class *class;
  2873. struct task_struct *p;
  2874. /*
  2875. * Optimization: we know that if all tasks are in the fair class we can
  2876. * call that function directly, but only if the @prev task wasn't of a
  2877. * higher scheduling class, because otherwise those loose the
  2878. * opportunity to pull in more work from other CPUs.
  2879. */
  2880. if (likely((prev->sched_class == &idle_sched_class ||
  2881. prev->sched_class == &fair_sched_class) &&
  2882. rq->nr_running == rq->cfs.h_nr_running)) {
  2883. p = fair_sched_class.pick_next_task(rq, prev, rf);
  2884. if (unlikely(p == RETRY_TASK))
  2885. goto again;
  2886. /* Assumes fair_sched_class->next == idle_sched_class */
  2887. if (unlikely(!p))
  2888. p = idle_sched_class.pick_next_task(rq, prev, rf);
  2889. return p;
  2890. }
  2891. again:
  2892. for_each_class(class) {
  2893. p = class->pick_next_task(rq, prev, rf);
  2894. if (p) {
  2895. if (unlikely(p == RETRY_TASK))
  2896. goto again;
  2897. return p;
  2898. }
  2899. }
  2900. /* The idle class should always have a runnable task: */
  2901. BUG();
  2902. }
  2903. /*
  2904. * __schedule() is the main scheduler function.
  2905. *
  2906. * The main means of driving the scheduler and thus entering this function are:
  2907. *
  2908. * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
  2909. *
  2910. * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
  2911. * paths. For example, see arch/x86/entry_64.S.
  2912. *
  2913. * To drive preemption between tasks, the scheduler sets the flag in timer
  2914. * interrupt handler scheduler_tick().
  2915. *
  2916. * 3. Wakeups don't really cause entry into schedule(). They add a
  2917. * task to the run-queue and that's it.
  2918. *
  2919. * Now, if the new task added to the run-queue preempts the current
  2920. * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
  2921. * called on the nearest possible occasion:
  2922. *
  2923. * - If the kernel is preemptible (CONFIG_PREEMPT=y):
  2924. *
  2925. * - in syscall or exception context, at the next outmost
  2926. * preempt_enable(). (this might be as soon as the wake_up()'s
  2927. * spin_unlock()!)
  2928. *
  2929. * - in IRQ context, return from interrupt-handler to
  2930. * preemptible context
  2931. *
  2932. * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
  2933. * then at the next:
  2934. *
  2935. * - cond_resched() call
  2936. * - explicit schedule() call
  2937. * - return from syscall or exception to user-space
  2938. * - return from interrupt-handler to user-space
  2939. *
  2940. * WARNING: must be called with preemption disabled!
  2941. */
  2942. static void __sched notrace __schedule(bool preempt)
  2943. {
  2944. struct task_struct *prev, *next;
  2945. unsigned long *switch_count;
  2946. struct rq_flags rf;
  2947. struct rq *rq;
  2948. int cpu;
  2949. cpu = smp_processor_id();
  2950. rq = cpu_rq(cpu);
  2951. prev = rq->curr;
  2952. schedule_debug(prev);
  2953. if (sched_feat(HRTICK))
  2954. hrtick_clear(rq);
  2955. local_irq_disable();
  2956. rcu_note_context_switch(preempt);
  2957. /*
  2958. * Make sure that signal_pending_state()->signal_pending() below
  2959. * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
  2960. * done by the caller to avoid the race with signal_wake_up().
  2961. *
  2962. * The membarrier system call requires a full memory barrier
  2963. * after coming from user-space, before storing to rq->curr.
  2964. */
  2965. rq_lock(rq, &rf);
  2966. smp_mb__after_spinlock();
  2967. /* Promote REQ to ACT */
  2968. rq->clock_update_flags <<= 1;
  2969. update_rq_clock(rq);
  2970. switch_count = &prev->nivcsw;
  2971. if (!preempt && prev->state) {
  2972. if (unlikely(signal_pending_state(prev->state, prev))) {
  2973. prev->state = TASK_RUNNING;
  2974. } else {
  2975. deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
  2976. prev->on_rq = 0;
  2977. if (prev->in_iowait) {
  2978. atomic_inc(&rq->nr_iowait);
  2979. delayacct_blkio_start();
  2980. }
  2981. /*
  2982. * If a worker went to sleep, notify and ask workqueue
  2983. * whether it wants to wake up a task to maintain
  2984. * concurrency.
  2985. */
  2986. if (prev->flags & PF_WQ_WORKER) {
  2987. struct task_struct *to_wakeup;
  2988. to_wakeup = wq_worker_sleeping(prev);
  2989. if (to_wakeup)
  2990. try_to_wake_up_local(to_wakeup, &rf);
  2991. }
  2992. }
  2993. switch_count = &prev->nvcsw;
  2994. }
  2995. next = pick_next_task(rq, prev, &rf);
  2996. clear_tsk_need_resched(prev);
  2997. clear_preempt_need_resched();
  2998. if (likely(prev != next)) {
  2999. rq->nr_switches++;
  3000. rq->curr = next;
  3001. /*
  3002. * The membarrier system call requires each architecture
  3003. * to have a full memory barrier after updating
  3004. * rq->curr, before returning to user-space.
  3005. *
  3006. * Here are the schemes providing that barrier on the
  3007. * various architectures:
  3008. * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
  3009. * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
  3010. * - finish_lock_switch() for weakly-ordered
  3011. * architectures where spin_unlock is a full barrier,
  3012. * - switch_to() for arm64 (weakly-ordered, spin_unlock
  3013. * is a RELEASE barrier),
  3014. */
  3015. ++*switch_count;
  3016. trace_sched_switch(preempt, prev, next);
  3017. /* Also unlocks the rq: */
  3018. rq = context_switch(rq, prev, next, &rf);
  3019. } else {
  3020. rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
  3021. rq_unlock_irq(rq, &rf);
  3022. }
  3023. balance_callback(rq);
  3024. }
  3025. void __noreturn do_task_dead(void)
  3026. {
  3027. /* Causes final put_task_struct in finish_task_switch(): */
  3028. set_special_state(TASK_DEAD);
  3029. /* Tell freezer to ignore us: */
  3030. current->flags |= PF_NOFREEZE;
  3031. __schedule(false);
  3032. BUG();
  3033. /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
  3034. for (;;)
  3035. cpu_relax();
  3036. }
  3037. static inline void sched_submit_work(struct task_struct *tsk)
  3038. {
  3039. if (!tsk->state || tsk_is_pi_blocked(tsk))
  3040. return;
  3041. /*
  3042. * If we are going to sleep and we have plugged IO queued,
  3043. * make sure to submit it to avoid deadlocks.
  3044. */
  3045. if (blk_needs_flush_plug(tsk))
  3046. blk_schedule_flush_plug(tsk);
  3047. }
  3048. asmlinkage __visible void __sched schedule(void)
  3049. {
  3050. struct task_struct *tsk = current;
  3051. sched_submit_work(tsk);
  3052. do {
  3053. preempt_disable();
  3054. __schedule(false);
  3055. sched_preempt_enable_no_resched();
  3056. } while (need_resched());
  3057. }
  3058. EXPORT_SYMBOL(schedule);
  3059. /*
  3060. * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
  3061. * state (have scheduled out non-voluntarily) by making sure that all
  3062. * tasks have either left the run queue or have gone into user space.
  3063. * As idle tasks do not do either, they must not ever be preempted
  3064. * (schedule out non-voluntarily).
  3065. *
  3066. * schedule_idle() is similar to schedule_preempt_disable() except that it
  3067. * never enables preemption because it does not call sched_submit_work().
  3068. */
  3069. void __sched schedule_idle(void)
  3070. {
  3071. /*
  3072. * As this skips calling sched_submit_work(), which the idle task does
  3073. * regardless because that function is a nop when the task is in a
  3074. * TASK_RUNNING state, make sure this isn't used someplace that the
  3075. * current task can be in any other state. Note, idle is always in the
  3076. * TASK_RUNNING state.
  3077. */
  3078. WARN_ON_ONCE(current->state);
  3079. do {
  3080. __schedule(false);
  3081. } while (need_resched());
  3082. }
  3083. #ifdef CONFIG_CONTEXT_TRACKING
  3084. asmlinkage __visible void __sched schedule_user(void)
  3085. {
  3086. /*
  3087. * If we come here after a random call to set_need_resched(),
  3088. * or we have been woken up remotely but the IPI has not yet arrived,
  3089. * we haven't yet exited the RCU idle mode. Do it here manually until
  3090. * we find a better solution.
  3091. *
  3092. * NB: There are buggy callers of this function. Ideally we
  3093. * should warn if prev_state != CONTEXT_USER, but that will trigger
  3094. * too frequently to make sense yet.
  3095. */
  3096. enum ctx_state prev_state = exception_enter();
  3097. schedule();
  3098. exception_exit(prev_state);
  3099. }
  3100. #endif
  3101. /**
  3102. * schedule_preempt_disabled - called with preemption disabled
  3103. *
  3104. * Returns with preemption disabled. Note: preempt_count must be 1
  3105. */
  3106. void __sched schedule_preempt_disabled(void)
  3107. {
  3108. sched_preempt_enable_no_resched();
  3109. schedule();
  3110. preempt_disable();
  3111. }
  3112. static void __sched notrace preempt_schedule_common(void)
  3113. {
  3114. do {
  3115. /*
  3116. * Because the function tracer can trace preempt_count_sub()
  3117. * and it also uses preempt_enable/disable_notrace(), if
  3118. * NEED_RESCHED is set, the preempt_enable_notrace() called
  3119. * by the function tracer will call this function again and
  3120. * cause infinite recursion.
  3121. *
  3122. * Preemption must be disabled here before the function
  3123. * tracer can trace. Break up preempt_disable() into two
  3124. * calls. One to disable preemption without fear of being
  3125. * traced. The other to still record the preemption latency,
  3126. * which can also be traced by the function tracer.
  3127. */
  3128. preempt_disable_notrace();
  3129. preempt_latency_start(1);
  3130. __schedule(true);
  3131. preempt_latency_stop(1);
  3132. preempt_enable_no_resched_notrace();
  3133. /*
  3134. * Check again in case we missed a preemption opportunity
  3135. * between schedule and now.
  3136. */
  3137. } while (need_resched());
  3138. }
  3139. #ifdef CONFIG_PREEMPT
  3140. /*
  3141. * this is the entry point to schedule() from in-kernel preemption
  3142. * off of preempt_enable. Kernel preemptions off return from interrupt
  3143. * occur there and call schedule directly.
  3144. */
  3145. asmlinkage __visible void __sched notrace preempt_schedule(void)
  3146. {
  3147. /*
  3148. * If there is a non-zero preempt_count or interrupts are disabled,
  3149. * we do not want to preempt the current task. Just return..
  3150. */
  3151. if (likely(!preemptible()))
  3152. return;
  3153. preempt_schedule_common();
  3154. }
  3155. NOKPROBE_SYMBOL(preempt_schedule);
  3156. EXPORT_SYMBOL(preempt_schedule);
  3157. /**
  3158. * preempt_schedule_notrace - preempt_schedule called by tracing
  3159. *
  3160. * The tracing infrastructure uses preempt_enable_notrace to prevent
  3161. * recursion and tracing preempt enabling caused by the tracing
  3162. * infrastructure itself. But as tracing can happen in areas coming
  3163. * from userspace or just about to enter userspace, a preempt enable
  3164. * can occur before user_exit() is called. This will cause the scheduler
  3165. * to be called when the system is still in usermode.
  3166. *
  3167. * To prevent this, the preempt_enable_notrace will use this function
  3168. * instead of preempt_schedule() to exit user context if needed before
  3169. * calling the scheduler.
  3170. */
  3171. asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
  3172. {
  3173. enum ctx_state prev_ctx;
  3174. if (likely(!preemptible()))
  3175. return;
  3176. do {
  3177. /*
  3178. * Because the function tracer can trace preempt_count_sub()
  3179. * and it also uses preempt_enable/disable_notrace(), if
  3180. * NEED_RESCHED is set, the preempt_enable_notrace() called
  3181. * by the function tracer will call this function again and
  3182. * cause infinite recursion.
  3183. *
  3184. * Preemption must be disabled here before the function
  3185. * tracer can trace. Break up preempt_disable() into two
  3186. * calls. One to disable preemption without fear of being
  3187. * traced. The other to still record the preemption latency,
  3188. * which can also be traced by the function tracer.
  3189. */
  3190. preempt_disable_notrace();
  3191. preempt_latency_start(1);
  3192. /*
  3193. * Needs preempt disabled in case user_exit() is traced
  3194. * and the tracer calls preempt_enable_notrace() causing
  3195. * an infinite recursion.
  3196. */
  3197. prev_ctx = exception_enter();
  3198. __schedule(true);
  3199. exception_exit(prev_ctx);
  3200. preempt_latency_stop(1);
  3201. preempt_enable_no_resched_notrace();
  3202. } while (need_resched());
  3203. }
  3204. EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
  3205. #endif /* CONFIG_PREEMPT */
  3206. /*
  3207. * this is the entry point to schedule() from kernel preemption
  3208. * off of irq context.
  3209. * Note, that this is called and return with irqs disabled. This will
  3210. * protect us against recursive calling from irq.
  3211. */
  3212. asmlinkage __visible void __sched preempt_schedule_irq(void)
  3213. {
  3214. enum ctx_state prev_state;
  3215. /* Catch callers which need to be fixed */
  3216. BUG_ON(preempt_count() || !irqs_disabled());
  3217. prev_state = exception_enter();
  3218. do {
  3219. preempt_disable();
  3220. local_irq_enable();
  3221. __schedule(true);
  3222. local_irq_disable();
  3223. sched_preempt_enable_no_resched();
  3224. } while (need_resched());
  3225. exception_exit(prev_state);
  3226. }
  3227. int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
  3228. void *key)
  3229. {
  3230. return try_to_wake_up(curr->private, mode, wake_flags);
  3231. }
  3232. EXPORT_SYMBOL(default_wake_function);
  3233. #ifdef CONFIG_RT_MUTEXES
  3234. static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
  3235. {
  3236. if (pi_task)
  3237. prio = min(prio, pi_task->prio);
  3238. return prio;
  3239. }
  3240. static inline int rt_effective_prio(struct task_struct *p, int prio)
  3241. {
  3242. struct task_struct *pi_task = rt_mutex_get_top_task(p);
  3243. return __rt_effective_prio(pi_task, prio);
  3244. }
  3245. /*
  3246. * rt_mutex_setprio - set the current priority of a task
  3247. * @p: task to boost
  3248. * @pi_task: donor task
  3249. *
  3250. * This function changes the 'effective' priority of a task. It does
  3251. * not touch ->normal_prio like __setscheduler().
  3252. *
  3253. * Used by the rt_mutex code to implement priority inheritance
  3254. * logic. Call site only calls if the priority of the task changed.
  3255. */
  3256. void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
  3257. {
  3258. int prio, oldprio, queued, running, queue_flag =
  3259. DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  3260. const struct sched_class *prev_class;
  3261. struct rq_flags rf;
  3262. struct rq *rq;
  3263. /* XXX used to be waiter->prio, not waiter->task->prio */
  3264. prio = __rt_effective_prio(pi_task, p->normal_prio);
  3265. /*
  3266. * If nothing changed; bail early.
  3267. */
  3268. if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
  3269. return;
  3270. rq = __task_rq_lock(p, &rf);
  3271. update_rq_clock(rq);
  3272. /*
  3273. * Set under pi_lock && rq->lock, such that the value can be used under
  3274. * either lock.
  3275. *
  3276. * Note that there is loads of tricky to make this pointer cache work
  3277. * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
  3278. * ensure a task is de-boosted (pi_task is set to NULL) before the
  3279. * task is allowed to run again (and can exit). This ensures the pointer
  3280. * points to a blocked task -- which guaratees the task is present.
  3281. */
  3282. p->pi_top_task = pi_task;
  3283. /*
  3284. * For FIFO/RR we only need to set prio, if that matches we're done.
  3285. */
  3286. if (prio == p->prio && !dl_prio(prio))
  3287. goto out_unlock;
  3288. /*
  3289. * Idle task boosting is a nono in general. There is one
  3290. * exception, when PREEMPT_RT and NOHZ is active:
  3291. *
  3292. * The idle task calls get_next_timer_interrupt() and holds
  3293. * the timer wheel base->lock on the CPU and another CPU wants
  3294. * to access the timer (probably to cancel it). We can safely
  3295. * ignore the boosting request, as the idle CPU runs this code
  3296. * with interrupts disabled and will complete the lock
  3297. * protected section without being interrupted. So there is no
  3298. * real need to boost.
  3299. */
  3300. if (unlikely(p == rq->idle)) {
  3301. WARN_ON(p != rq->curr);
  3302. WARN_ON(p->pi_blocked_on);
  3303. goto out_unlock;
  3304. }
  3305. trace_sched_pi_setprio(p, pi_task);
  3306. oldprio = p->prio;
  3307. if (oldprio == prio)
  3308. queue_flag &= ~DEQUEUE_MOVE;
  3309. prev_class = p->sched_class;
  3310. queued = task_on_rq_queued(p);
  3311. running = task_current(rq, p);
  3312. if (queued)
  3313. dequeue_task(rq, p, queue_flag);
  3314. if (running)
  3315. put_prev_task(rq, p);
  3316. /*
  3317. * Boosting condition are:
  3318. * 1. -rt task is running and holds mutex A
  3319. * --> -dl task blocks on mutex A
  3320. *
  3321. * 2. -dl task is running and holds mutex A
  3322. * --> -dl task blocks on mutex A and could preempt the
  3323. * running task
  3324. */
  3325. if (dl_prio(prio)) {
  3326. if (!dl_prio(p->normal_prio) ||
  3327. (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
  3328. p->dl.dl_boosted = 1;
  3329. queue_flag |= ENQUEUE_REPLENISH;
  3330. } else
  3331. p->dl.dl_boosted = 0;
  3332. p->sched_class = &dl_sched_class;
  3333. } else if (rt_prio(prio)) {
  3334. if (dl_prio(oldprio))
  3335. p->dl.dl_boosted = 0;
  3336. if (oldprio < prio)
  3337. queue_flag |= ENQUEUE_HEAD;
  3338. p->sched_class = &rt_sched_class;
  3339. } else {
  3340. if (dl_prio(oldprio))
  3341. p->dl.dl_boosted = 0;
  3342. if (rt_prio(oldprio))
  3343. p->rt.timeout = 0;
  3344. p->sched_class = &fair_sched_class;
  3345. }
  3346. p->prio = prio;
  3347. if (queued)
  3348. enqueue_task(rq, p, queue_flag);
  3349. if (running)
  3350. set_curr_task(rq, p);
  3351. check_class_changed(rq, p, prev_class, oldprio);
  3352. out_unlock:
  3353. /* Avoid rq from going away on us: */
  3354. preempt_disable();
  3355. __task_rq_unlock(rq, &rf);
  3356. balance_callback(rq);
  3357. preempt_enable();
  3358. }
  3359. #else
  3360. static inline int rt_effective_prio(struct task_struct *p, int prio)
  3361. {
  3362. return prio;
  3363. }
  3364. #endif
  3365. void set_user_nice(struct task_struct *p, long nice)
  3366. {
  3367. bool queued, running;
  3368. int old_prio, delta;
  3369. struct rq_flags rf;
  3370. struct rq *rq;
  3371. if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
  3372. return;
  3373. /*
  3374. * We have to be careful, if called from sys_setpriority(),
  3375. * the task might be in the middle of scheduling on another CPU.
  3376. */
  3377. rq = task_rq_lock(p, &rf);
  3378. update_rq_clock(rq);
  3379. /*
  3380. * The RT priorities are set via sched_setscheduler(), but we still
  3381. * allow the 'normal' nice value to be set - but as expected
  3382. * it wont have any effect on scheduling until the task is
  3383. * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
  3384. */
  3385. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  3386. p->static_prio = NICE_TO_PRIO(nice);
  3387. goto out_unlock;
  3388. }
  3389. queued = task_on_rq_queued(p);
  3390. running = task_current(rq, p);
  3391. if (queued)
  3392. dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
  3393. if (running)
  3394. put_prev_task(rq, p);
  3395. p->static_prio = NICE_TO_PRIO(nice);
  3396. set_load_weight(p, true);
  3397. old_prio = p->prio;
  3398. p->prio = effective_prio(p);
  3399. delta = p->prio - old_prio;
  3400. if (queued) {
  3401. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  3402. /*
  3403. * If the task increased its priority or is running and
  3404. * lowered its priority, then reschedule its CPU:
  3405. */
  3406. if (delta < 0 || (delta > 0 && task_running(rq, p)))
  3407. resched_curr(rq);
  3408. }
  3409. if (running)
  3410. set_curr_task(rq, p);
  3411. out_unlock:
  3412. task_rq_unlock(rq, p, &rf);
  3413. }
  3414. EXPORT_SYMBOL(set_user_nice);
  3415. /*
  3416. * can_nice - check if a task can reduce its nice value
  3417. * @p: task
  3418. * @nice: nice value
  3419. */
  3420. int can_nice(const struct task_struct *p, const int nice)
  3421. {
  3422. /* Convert nice value [19,-20] to rlimit style value [1,40]: */
  3423. int nice_rlim = nice_to_rlimit(nice);
  3424. return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
  3425. capable(CAP_SYS_NICE));
  3426. }
  3427. EXPORT_SYMBOL_GPL(can_nice);
  3428. #ifdef __ARCH_WANT_SYS_NICE
  3429. /*
  3430. * sys_nice - change the priority of the current process.
  3431. * @increment: priority increment
  3432. *
  3433. * sys_setpriority is a more generic, but much slower function that
  3434. * does similar things.
  3435. */
  3436. SYSCALL_DEFINE1(nice, int, increment)
  3437. {
  3438. long nice, retval;
  3439. /*
  3440. * Setpriority might change our priority at the same moment.
  3441. * We don't have to worry. Conceptually one call occurs first
  3442. * and we have a single winner.
  3443. */
  3444. increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
  3445. nice = task_nice(current) + increment;
  3446. nice = clamp_val(nice, MIN_NICE, MAX_NICE);
  3447. if (increment < 0 && !can_nice(current, nice))
  3448. return -EPERM;
  3449. retval = security_task_setnice(current, nice);
  3450. if (retval)
  3451. return retval;
  3452. set_user_nice(current, nice);
  3453. return 0;
  3454. }
  3455. #endif
  3456. /**
  3457. * task_prio - return the priority value of a given task.
  3458. * @p: the task in question.
  3459. *
  3460. * Return: The priority value as seen by users in /proc.
  3461. * RT tasks are offset by -200. Normal tasks are centered
  3462. * around 0, value goes from -16 to +15.
  3463. */
  3464. int task_prio(const struct task_struct *p)
  3465. {
  3466. return p->prio - MAX_RT_PRIO;
  3467. }
  3468. /**
  3469. * idle_cpu - is a given CPU idle currently?
  3470. * @cpu: the processor in question.
  3471. *
  3472. * Return: 1 if the CPU is currently idle. 0 otherwise.
  3473. */
  3474. int idle_cpu(int cpu)
  3475. {
  3476. struct rq *rq = cpu_rq(cpu);
  3477. if (rq->curr != rq->idle)
  3478. return 0;
  3479. if (rq->nr_running)
  3480. return 0;
  3481. #ifdef CONFIG_SMP
  3482. if (!llist_empty(&rq->wake_list))
  3483. return 0;
  3484. #endif
  3485. return 1;
  3486. }
  3487. /**
  3488. * available_idle_cpu - is a given CPU idle for enqueuing work.
  3489. * @cpu: the CPU in question.
  3490. *
  3491. * Return: 1 if the CPU is currently idle. 0 otherwise.
  3492. */
  3493. int available_idle_cpu(int cpu)
  3494. {
  3495. if (!idle_cpu(cpu))
  3496. return 0;
  3497. if (vcpu_is_preempted(cpu))
  3498. return 0;
  3499. return 1;
  3500. }
  3501. /**
  3502. * idle_task - return the idle task for a given CPU.
  3503. * @cpu: the processor in question.
  3504. *
  3505. * Return: The idle task for the CPU @cpu.
  3506. */
  3507. struct task_struct *idle_task(int cpu)
  3508. {
  3509. return cpu_rq(cpu)->idle;
  3510. }
  3511. /**
  3512. * find_process_by_pid - find a process with a matching PID value.
  3513. * @pid: the pid in question.
  3514. *
  3515. * The task of @pid, if found. %NULL otherwise.
  3516. */
  3517. static struct task_struct *find_process_by_pid(pid_t pid)
  3518. {
  3519. return pid ? find_task_by_vpid(pid) : current;
  3520. }
  3521. /*
  3522. * sched_setparam() passes in -1 for its policy, to let the functions
  3523. * it calls know not to change it.
  3524. */
  3525. #define SETPARAM_POLICY -1
  3526. static void __setscheduler_params(struct task_struct *p,
  3527. const struct sched_attr *attr)
  3528. {
  3529. int policy = attr->sched_policy;
  3530. if (policy == SETPARAM_POLICY)
  3531. policy = p->policy;
  3532. p->policy = policy;
  3533. if (dl_policy(policy))
  3534. __setparam_dl(p, attr);
  3535. else if (fair_policy(policy))
  3536. p->static_prio = NICE_TO_PRIO(attr->sched_nice);
  3537. /*
  3538. * __sched_setscheduler() ensures attr->sched_priority == 0 when
  3539. * !rt_policy. Always setting this ensures that things like
  3540. * getparam()/getattr() don't report silly values for !rt tasks.
  3541. */
  3542. p->rt_priority = attr->sched_priority;
  3543. p->normal_prio = normal_prio(p);
  3544. set_load_weight(p, true);
  3545. }
  3546. /* Actually do priority change: must hold pi & rq lock. */
  3547. static void __setscheduler(struct rq *rq, struct task_struct *p,
  3548. const struct sched_attr *attr, bool keep_boost)
  3549. {
  3550. __setscheduler_params(p, attr);
  3551. /*
  3552. * Keep a potential priority boosting if called from
  3553. * sched_setscheduler().
  3554. */
  3555. p->prio = normal_prio(p);
  3556. if (keep_boost)
  3557. p->prio = rt_effective_prio(p, p->prio);
  3558. if (dl_prio(p->prio))
  3559. p->sched_class = &dl_sched_class;
  3560. else if (rt_prio(p->prio))
  3561. p->sched_class = &rt_sched_class;
  3562. else
  3563. p->sched_class = &fair_sched_class;
  3564. }
  3565. /*
  3566. * Check the target process has a UID that matches the current process's:
  3567. */
  3568. static bool check_same_owner(struct task_struct *p)
  3569. {
  3570. const struct cred *cred = current_cred(), *pcred;
  3571. bool match;
  3572. rcu_read_lock();
  3573. pcred = __task_cred(p);
  3574. match = (uid_eq(cred->euid, pcred->euid) ||
  3575. uid_eq(cred->euid, pcred->uid));
  3576. rcu_read_unlock();
  3577. return match;
  3578. }
  3579. static int __sched_setscheduler(struct task_struct *p,
  3580. const struct sched_attr *attr,
  3581. bool user, bool pi)
  3582. {
  3583. int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
  3584. MAX_RT_PRIO - 1 - attr->sched_priority;
  3585. int retval, oldprio, oldpolicy = -1, queued, running;
  3586. int new_effective_prio, policy = attr->sched_policy;
  3587. const struct sched_class *prev_class;
  3588. struct rq_flags rf;
  3589. int reset_on_fork;
  3590. int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  3591. struct rq *rq;
  3592. /* The pi code expects interrupts enabled */
  3593. BUG_ON(pi && in_interrupt());
  3594. recheck:
  3595. /* Double check policy once rq lock held: */
  3596. if (policy < 0) {
  3597. reset_on_fork = p->sched_reset_on_fork;
  3598. policy = oldpolicy = p->policy;
  3599. } else {
  3600. reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
  3601. if (!valid_policy(policy))
  3602. return -EINVAL;
  3603. }
  3604. if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
  3605. return -EINVAL;
  3606. /*
  3607. * Valid priorities for SCHED_FIFO and SCHED_RR are
  3608. * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
  3609. * SCHED_BATCH and SCHED_IDLE is 0.
  3610. */
  3611. if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
  3612. (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
  3613. return -EINVAL;
  3614. if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
  3615. (rt_policy(policy) != (attr->sched_priority != 0)))
  3616. return -EINVAL;
  3617. /*
  3618. * Allow unprivileged RT tasks to decrease priority:
  3619. */
  3620. if (user && !capable(CAP_SYS_NICE)) {
  3621. if (fair_policy(policy)) {
  3622. if (attr->sched_nice < task_nice(p) &&
  3623. !can_nice(p, attr->sched_nice))
  3624. return -EPERM;
  3625. }
  3626. if (rt_policy(policy)) {
  3627. unsigned long rlim_rtprio =
  3628. task_rlimit(p, RLIMIT_RTPRIO);
  3629. /* Can't set/change the rt policy: */
  3630. if (policy != p->policy && !rlim_rtprio)
  3631. return -EPERM;
  3632. /* Can't increase priority: */
  3633. if (attr->sched_priority > p->rt_priority &&
  3634. attr->sched_priority > rlim_rtprio)
  3635. return -EPERM;
  3636. }
  3637. /*
  3638. * Can't set/change SCHED_DEADLINE policy at all for now
  3639. * (safest behavior); in the future we would like to allow
  3640. * unprivileged DL tasks to increase their relative deadline
  3641. * or reduce their runtime (both ways reducing utilization)
  3642. */
  3643. if (dl_policy(policy))
  3644. return -EPERM;
  3645. /*
  3646. * Treat SCHED_IDLE as nice 20. Only allow a switch to
  3647. * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
  3648. */
  3649. if (idle_policy(p->policy) && !idle_policy(policy)) {
  3650. if (!can_nice(p, task_nice(p)))
  3651. return -EPERM;
  3652. }
  3653. /* Can't change other user's priorities: */
  3654. if (!check_same_owner(p))
  3655. return -EPERM;
  3656. /* Normal users shall not reset the sched_reset_on_fork flag: */
  3657. if (p->sched_reset_on_fork && !reset_on_fork)
  3658. return -EPERM;
  3659. }
  3660. if (user) {
  3661. if (attr->sched_flags & SCHED_FLAG_SUGOV)
  3662. return -EINVAL;
  3663. retval = security_task_setscheduler(p);
  3664. if (retval)
  3665. return retval;
  3666. }
  3667. /*
  3668. * Make sure no PI-waiters arrive (or leave) while we are
  3669. * changing the priority of the task:
  3670. *
  3671. * To be able to change p->policy safely, the appropriate
  3672. * runqueue lock must be held.
  3673. */
  3674. rq = task_rq_lock(p, &rf);
  3675. update_rq_clock(rq);
  3676. /*
  3677. * Changing the policy of the stop threads its a very bad idea:
  3678. */
  3679. if (p == rq->stop) {
  3680. task_rq_unlock(rq, p, &rf);
  3681. return -EINVAL;
  3682. }
  3683. /*
  3684. * If not changing anything there's no need to proceed further,
  3685. * but store a possible modification of reset_on_fork.
  3686. */
  3687. if (unlikely(policy == p->policy)) {
  3688. if (fair_policy(policy) && attr->sched_nice != task_nice(p))
  3689. goto change;
  3690. if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
  3691. goto change;
  3692. if (dl_policy(policy) && dl_param_changed(p, attr))
  3693. goto change;
  3694. p->sched_reset_on_fork = reset_on_fork;
  3695. task_rq_unlock(rq, p, &rf);
  3696. return 0;
  3697. }
  3698. change:
  3699. if (user) {
  3700. #ifdef CONFIG_RT_GROUP_SCHED
  3701. /*
  3702. * Do not allow realtime tasks into groups that have no runtime
  3703. * assigned.
  3704. */
  3705. if (rt_bandwidth_enabled() && rt_policy(policy) &&
  3706. task_group(p)->rt_bandwidth.rt_runtime == 0 &&
  3707. !task_group_is_autogroup(task_group(p))) {
  3708. task_rq_unlock(rq, p, &rf);
  3709. return -EPERM;
  3710. }
  3711. #endif
  3712. #ifdef CONFIG_SMP
  3713. if (dl_bandwidth_enabled() && dl_policy(policy) &&
  3714. !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
  3715. cpumask_t *span = rq->rd->span;
  3716. /*
  3717. * Don't allow tasks with an affinity mask smaller than
  3718. * the entire root_domain to become SCHED_DEADLINE. We
  3719. * will also fail if there's no bandwidth available.
  3720. */
  3721. if (!cpumask_subset(span, &p->cpus_allowed) ||
  3722. rq->rd->dl_bw.bw == 0) {
  3723. task_rq_unlock(rq, p, &rf);
  3724. return -EPERM;
  3725. }
  3726. }
  3727. #endif
  3728. }
  3729. /* Re-check policy now with rq lock held: */
  3730. if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
  3731. policy = oldpolicy = -1;
  3732. task_rq_unlock(rq, p, &rf);
  3733. goto recheck;
  3734. }
  3735. /*
  3736. * If setscheduling to SCHED_DEADLINE (or changing the parameters
  3737. * of a SCHED_DEADLINE task) we need to check if enough bandwidth
  3738. * is available.
  3739. */
  3740. if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
  3741. task_rq_unlock(rq, p, &rf);
  3742. return -EBUSY;
  3743. }
  3744. p->sched_reset_on_fork = reset_on_fork;
  3745. oldprio = p->prio;
  3746. if (pi) {
  3747. /*
  3748. * Take priority boosted tasks into account. If the new
  3749. * effective priority is unchanged, we just store the new
  3750. * normal parameters and do not touch the scheduler class and
  3751. * the runqueue. This will be done when the task deboost
  3752. * itself.
  3753. */
  3754. new_effective_prio = rt_effective_prio(p, newprio);
  3755. if (new_effective_prio == oldprio)
  3756. queue_flags &= ~DEQUEUE_MOVE;
  3757. }
  3758. queued = task_on_rq_queued(p);
  3759. running = task_current(rq, p);
  3760. if (queued)
  3761. dequeue_task(rq, p, queue_flags);
  3762. if (running)
  3763. put_prev_task(rq, p);
  3764. prev_class = p->sched_class;
  3765. __setscheduler(rq, p, attr, pi);
  3766. if (queued) {
  3767. /*
  3768. * We enqueue to tail when the priority of a task is
  3769. * increased (user space view).
  3770. */
  3771. if (oldprio < p->prio)
  3772. queue_flags |= ENQUEUE_HEAD;
  3773. enqueue_task(rq, p, queue_flags);
  3774. }
  3775. if (running)
  3776. set_curr_task(rq, p);
  3777. check_class_changed(rq, p, prev_class, oldprio);
  3778. /* Avoid rq from going away on us: */
  3779. preempt_disable();
  3780. task_rq_unlock(rq, p, &rf);
  3781. if (pi)
  3782. rt_mutex_adjust_pi(p);
  3783. /* Run balance callbacks after we've adjusted the PI chain: */
  3784. balance_callback(rq);
  3785. preempt_enable();
  3786. return 0;
  3787. }
  3788. static int _sched_setscheduler(struct task_struct *p, int policy,
  3789. const struct sched_param *param, bool check)
  3790. {
  3791. struct sched_attr attr = {
  3792. .sched_policy = policy,
  3793. .sched_priority = param->sched_priority,
  3794. .sched_nice = PRIO_TO_NICE(p->static_prio),
  3795. };
  3796. /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
  3797. if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
  3798. attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
  3799. policy &= ~SCHED_RESET_ON_FORK;
  3800. attr.sched_policy = policy;
  3801. }
  3802. return __sched_setscheduler(p, &attr, check, true);
  3803. }
  3804. /**
  3805. * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
  3806. * @p: the task in question.
  3807. * @policy: new policy.
  3808. * @param: structure containing the new RT priority.
  3809. *
  3810. * Return: 0 on success. An error code otherwise.
  3811. *
  3812. * NOTE that the task may be already dead.
  3813. */
  3814. int sched_setscheduler(struct task_struct *p, int policy,
  3815. const struct sched_param *param)
  3816. {
  3817. return _sched_setscheduler(p, policy, param, true);
  3818. }
  3819. EXPORT_SYMBOL_GPL(sched_setscheduler);
  3820. int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
  3821. {
  3822. return __sched_setscheduler(p, attr, true, true);
  3823. }
  3824. EXPORT_SYMBOL_GPL(sched_setattr);
  3825. int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
  3826. {
  3827. return __sched_setscheduler(p, attr, false, true);
  3828. }
  3829. /**
  3830. * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
  3831. * @p: the task in question.
  3832. * @policy: new policy.
  3833. * @param: structure containing the new RT priority.
  3834. *
  3835. * Just like sched_setscheduler, only don't bother checking if the
  3836. * current context has permission. For example, this is needed in
  3837. * stop_machine(): we create temporary high priority worker threads,
  3838. * but our caller might not have that capability.
  3839. *
  3840. * Return: 0 on success. An error code otherwise.
  3841. */
  3842. int sched_setscheduler_nocheck(struct task_struct *p, int policy,
  3843. const struct sched_param *param)
  3844. {
  3845. return _sched_setscheduler(p, policy, param, false);
  3846. }
  3847. EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
  3848. static int
  3849. do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
  3850. {
  3851. struct sched_param lparam;
  3852. struct task_struct *p;
  3853. int retval;
  3854. if (!param || pid < 0)
  3855. return -EINVAL;
  3856. if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
  3857. return -EFAULT;
  3858. rcu_read_lock();
  3859. retval = -ESRCH;
  3860. p = find_process_by_pid(pid);
  3861. if (p != NULL)
  3862. retval = sched_setscheduler(p, policy, &lparam);
  3863. rcu_read_unlock();
  3864. return retval;
  3865. }
  3866. /*
  3867. * Mimics kernel/events/core.c perf_copy_attr().
  3868. */
  3869. static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
  3870. {
  3871. u32 size;
  3872. int ret;
  3873. if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
  3874. return -EFAULT;
  3875. /* Zero the full structure, so that a short copy will be nice: */
  3876. memset(attr, 0, sizeof(*attr));
  3877. ret = get_user(size, &uattr->size);
  3878. if (ret)
  3879. return ret;
  3880. /* Bail out on silly large: */
  3881. if (size > PAGE_SIZE)
  3882. goto err_size;
  3883. /* ABI compatibility quirk: */
  3884. if (!size)
  3885. size = SCHED_ATTR_SIZE_VER0;
  3886. if (size < SCHED_ATTR_SIZE_VER0)
  3887. goto err_size;
  3888. /*
  3889. * If we're handed a bigger struct than we know of,
  3890. * ensure all the unknown bits are 0 - i.e. new
  3891. * user-space does not rely on any kernel feature
  3892. * extensions we dont know about yet.
  3893. */
  3894. if (size > sizeof(*attr)) {
  3895. unsigned char __user *addr;
  3896. unsigned char __user *end;
  3897. unsigned char val;
  3898. addr = (void __user *)uattr + sizeof(*attr);
  3899. end = (void __user *)uattr + size;
  3900. for (; addr < end; addr++) {
  3901. ret = get_user(val, addr);
  3902. if (ret)
  3903. return ret;
  3904. if (val)
  3905. goto err_size;
  3906. }
  3907. size = sizeof(*attr);
  3908. }
  3909. ret = copy_from_user(attr, uattr, size);
  3910. if (ret)
  3911. return -EFAULT;
  3912. /*
  3913. * XXX: Do we want to be lenient like existing syscalls; or do we want
  3914. * to be strict and return an error on out-of-bounds values?
  3915. */
  3916. attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
  3917. return 0;
  3918. err_size:
  3919. put_user(sizeof(*attr), &uattr->size);
  3920. return -E2BIG;
  3921. }
  3922. /**
  3923. * sys_sched_setscheduler - set/change the scheduler policy and RT priority
  3924. * @pid: the pid in question.
  3925. * @policy: new policy.
  3926. * @param: structure containing the new RT priority.
  3927. *
  3928. * Return: 0 on success. An error code otherwise.
  3929. */
  3930. SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
  3931. {
  3932. if (policy < 0)
  3933. return -EINVAL;
  3934. return do_sched_setscheduler(pid, policy, param);
  3935. }
  3936. /**
  3937. * sys_sched_setparam - set/change the RT priority of a thread
  3938. * @pid: the pid in question.
  3939. * @param: structure containing the new RT priority.
  3940. *
  3941. * Return: 0 on success. An error code otherwise.
  3942. */
  3943. SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
  3944. {
  3945. return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
  3946. }
  3947. /**
  3948. * sys_sched_setattr - same as above, but with extended sched_attr
  3949. * @pid: the pid in question.
  3950. * @uattr: structure containing the extended parameters.
  3951. * @flags: for future extension.
  3952. */
  3953. SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
  3954. unsigned int, flags)
  3955. {
  3956. struct sched_attr attr;
  3957. struct task_struct *p;
  3958. int retval;
  3959. if (!uattr || pid < 0 || flags)
  3960. return -EINVAL;
  3961. retval = sched_copy_attr(uattr, &attr);
  3962. if (retval)
  3963. return retval;
  3964. if ((int)attr.sched_policy < 0)
  3965. return -EINVAL;
  3966. rcu_read_lock();
  3967. retval = -ESRCH;
  3968. p = find_process_by_pid(pid);
  3969. if (p != NULL)
  3970. retval = sched_setattr(p, &attr);
  3971. rcu_read_unlock();
  3972. return retval;
  3973. }
  3974. /**
  3975. * sys_sched_getscheduler - get the policy (scheduling class) of a thread
  3976. * @pid: the pid in question.
  3977. *
  3978. * Return: On success, the policy of the thread. Otherwise, a negative error
  3979. * code.
  3980. */
  3981. SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
  3982. {
  3983. struct task_struct *p;
  3984. int retval;
  3985. if (pid < 0)
  3986. return -EINVAL;
  3987. retval = -ESRCH;
  3988. rcu_read_lock();
  3989. p = find_process_by_pid(pid);
  3990. if (p) {
  3991. retval = security_task_getscheduler(p);
  3992. if (!retval)
  3993. retval = p->policy
  3994. | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
  3995. }
  3996. rcu_read_unlock();
  3997. return retval;
  3998. }
  3999. /**
  4000. * sys_sched_getparam - get the RT priority of a thread
  4001. * @pid: the pid in question.
  4002. * @param: structure containing the RT priority.
  4003. *
  4004. * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
  4005. * code.
  4006. */
  4007. SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
  4008. {
  4009. struct sched_param lp = { .sched_priority = 0 };
  4010. struct task_struct *p;
  4011. int retval;
  4012. if (!param || pid < 0)
  4013. return -EINVAL;
  4014. rcu_read_lock();
  4015. p = find_process_by_pid(pid);
  4016. retval = -ESRCH;
  4017. if (!p)
  4018. goto out_unlock;
  4019. retval = security_task_getscheduler(p);
  4020. if (retval)
  4021. goto out_unlock;
  4022. if (task_has_rt_policy(p))
  4023. lp.sched_priority = p->rt_priority;
  4024. rcu_read_unlock();
  4025. /*
  4026. * This one might sleep, we cannot do it with a spinlock held ...
  4027. */
  4028. retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  4029. return retval;
  4030. out_unlock:
  4031. rcu_read_unlock();
  4032. return retval;
  4033. }
  4034. static int sched_read_attr(struct sched_attr __user *uattr,
  4035. struct sched_attr *attr,
  4036. unsigned int usize)
  4037. {
  4038. int ret;
  4039. if (!access_ok(VERIFY_WRITE, uattr, usize))
  4040. return -EFAULT;
  4041. /*
  4042. * If we're handed a smaller struct than we know of,
  4043. * ensure all the unknown bits are 0 - i.e. old
  4044. * user-space does not get uncomplete information.
  4045. */
  4046. if (usize < sizeof(*attr)) {
  4047. unsigned char *addr;
  4048. unsigned char *end;
  4049. addr = (void *)attr + usize;
  4050. end = (void *)attr + sizeof(*attr);
  4051. for (; addr < end; addr++) {
  4052. if (*addr)
  4053. return -EFBIG;
  4054. }
  4055. attr->size = usize;
  4056. }
  4057. ret = copy_to_user(uattr, attr, attr->size);
  4058. if (ret)
  4059. return -EFAULT;
  4060. return 0;
  4061. }
  4062. /**
  4063. * sys_sched_getattr - similar to sched_getparam, but with sched_attr
  4064. * @pid: the pid in question.
  4065. * @uattr: structure containing the extended parameters.
  4066. * @size: sizeof(attr) for fwd/bwd comp.
  4067. * @flags: for future extension.
  4068. */
  4069. SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
  4070. unsigned int, size, unsigned int, flags)
  4071. {
  4072. struct sched_attr attr = {
  4073. .size = sizeof(struct sched_attr),
  4074. };
  4075. struct task_struct *p;
  4076. int retval;
  4077. if (!uattr || pid < 0 || size > PAGE_SIZE ||
  4078. size < SCHED_ATTR_SIZE_VER0 || flags)
  4079. return -EINVAL;
  4080. rcu_read_lock();
  4081. p = find_process_by_pid(pid);
  4082. retval = -ESRCH;
  4083. if (!p)
  4084. goto out_unlock;
  4085. retval = security_task_getscheduler(p);
  4086. if (retval)
  4087. goto out_unlock;
  4088. attr.sched_policy = p->policy;
  4089. if (p->sched_reset_on_fork)
  4090. attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
  4091. if (task_has_dl_policy(p))
  4092. __getparam_dl(p, &attr);
  4093. else if (task_has_rt_policy(p))
  4094. attr.sched_priority = p->rt_priority;
  4095. else
  4096. attr.sched_nice = task_nice(p);
  4097. rcu_read_unlock();
  4098. retval = sched_read_attr(uattr, &attr, size);
  4099. return retval;
  4100. out_unlock:
  4101. rcu_read_unlock();
  4102. return retval;
  4103. }
  4104. long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
  4105. {
  4106. cpumask_var_t cpus_allowed, new_mask;
  4107. struct task_struct *p;
  4108. int retval;
  4109. rcu_read_lock();
  4110. p = find_process_by_pid(pid);
  4111. if (!p) {
  4112. rcu_read_unlock();
  4113. return -ESRCH;
  4114. }
  4115. /* Prevent p going away */
  4116. get_task_struct(p);
  4117. rcu_read_unlock();
  4118. if (p->flags & PF_NO_SETAFFINITY) {
  4119. retval = -EINVAL;
  4120. goto out_put_task;
  4121. }
  4122. if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
  4123. retval = -ENOMEM;
  4124. goto out_put_task;
  4125. }
  4126. if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
  4127. retval = -ENOMEM;
  4128. goto out_free_cpus_allowed;
  4129. }
  4130. retval = -EPERM;
  4131. if (!check_same_owner(p)) {
  4132. rcu_read_lock();
  4133. if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
  4134. rcu_read_unlock();
  4135. goto out_free_new_mask;
  4136. }
  4137. rcu_read_unlock();
  4138. }
  4139. retval = security_task_setscheduler(p);
  4140. if (retval)
  4141. goto out_free_new_mask;
  4142. cpuset_cpus_allowed(p, cpus_allowed);
  4143. cpumask_and(new_mask, in_mask, cpus_allowed);
  4144. /*
  4145. * Since bandwidth control happens on root_domain basis,
  4146. * if admission test is enabled, we only admit -deadline
  4147. * tasks allowed to run on all the CPUs in the task's
  4148. * root_domain.
  4149. */
  4150. #ifdef CONFIG_SMP
  4151. if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
  4152. rcu_read_lock();
  4153. if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
  4154. retval = -EBUSY;
  4155. rcu_read_unlock();
  4156. goto out_free_new_mask;
  4157. }
  4158. rcu_read_unlock();
  4159. }
  4160. #endif
  4161. again:
  4162. retval = __set_cpus_allowed_ptr(p, new_mask, true);
  4163. if (!retval) {
  4164. cpuset_cpus_allowed(p, cpus_allowed);
  4165. if (!cpumask_subset(new_mask, cpus_allowed)) {
  4166. /*
  4167. * We must have raced with a concurrent cpuset
  4168. * update. Just reset the cpus_allowed to the
  4169. * cpuset's cpus_allowed
  4170. */
  4171. cpumask_copy(new_mask, cpus_allowed);
  4172. goto again;
  4173. }
  4174. }
  4175. out_free_new_mask:
  4176. free_cpumask_var(new_mask);
  4177. out_free_cpus_allowed:
  4178. free_cpumask_var(cpus_allowed);
  4179. out_put_task:
  4180. put_task_struct(p);
  4181. return retval;
  4182. }
  4183. static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
  4184. struct cpumask *new_mask)
  4185. {
  4186. if (len < cpumask_size())
  4187. cpumask_clear(new_mask);
  4188. else if (len > cpumask_size())
  4189. len = cpumask_size();
  4190. return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
  4191. }
  4192. /**
  4193. * sys_sched_setaffinity - set the CPU affinity of a process
  4194. * @pid: pid of the process
  4195. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  4196. * @user_mask_ptr: user-space pointer to the new CPU mask
  4197. *
  4198. * Return: 0 on success. An error code otherwise.
  4199. */
  4200. SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
  4201. unsigned long __user *, user_mask_ptr)
  4202. {
  4203. cpumask_var_t new_mask;
  4204. int retval;
  4205. if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
  4206. return -ENOMEM;
  4207. retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
  4208. if (retval == 0)
  4209. retval = sched_setaffinity(pid, new_mask);
  4210. free_cpumask_var(new_mask);
  4211. return retval;
  4212. }
  4213. long sched_getaffinity(pid_t pid, struct cpumask *mask)
  4214. {
  4215. struct task_struct *p;
  4216. unsigned long flags;
  4217. int retval;
  4218. rcu_read_lock();
  4219. retval = -ESRCH;
  4220. p = find_process_by_pid(pid);
  4221. if (!p)
  4222. goto out_unlock;
  4223. retval = security_task_getscheduler(p);
  4224. if (retval)
  4225. goto out_unlock;
  4226. raw_spin_lock_irqsave(&p->pi_lock, flags);
  4227. cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
  4228. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  4229. out_unlock:
  4230. rcu_read_unlock();
  4231. return retval;
  4232. }
  4233. /**
  4234. * sys_sched_getaffinity - get the CPU affinity of a process
  4235. * @pid: pid of the process
  4236. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  4237. * @user_mask_ptr: user-space pointer to hold the current CPU mask
  4238. *
  4239. * Return: size of CPU mask copied to user_mask_ptr on success. An
  4240. * error code otherwise.
  4241. */
  4242. SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
  4243. unsigned long __user *, user_mask_ptr)
  4244. {
  4245. int ret;
  4246. cpumask_var_t mask;
  4247. if ((len * BITS_PER_BYTE) < nr_cpu_ids)
  4248. return -EINVAL;
  4249. if (len & (sizeof(unsigned long)-1))
  4250. return -EINVAL;
  4251. if (!alloc_cpumask_var(&mask, GFP_KERNEL))
  4252. return -ENOMEM;
  4253. ret = sched_getaffinity(pid, mask);
  4254. if (ret == 0) {
  4255. unsigned int retlen = min(len, cpumask_size());
  4256. if (copy_to_user(user_mask_ptr, mask, retlen))
  4257. ret = -EFAULT;
  4258. else
  4259. ret = retlen;
  4260. }
  4261. free_cpumask_var(mask);
  4262. return ret;
  4263. }
  4264. /**
  4265. * sys_sched_yield - yield the current processor to other threads.
  4266. *
  4267. * This function yields the current CPU to other tasks. If there are no
  4268. * other threads running on this CPU then this function will return.
  4269. *
  4270. * Return: 0.
  4271. */
  4272. static void do_sched_yield(void)
  4273. {
  4274. struct rq_flags rf;
  4275. struct rq *rq;
  4276. local_irq_disable();
  4277. rq = this_rq();
  4278. rq_lock(rq, &rf);
  4279. schedstat_inc(rq->yld_count);
  4280. current->sched_class->yield_task(rq);
  4281. /*
  4282. * Since we are going to call schedule() anyway, there's
  4283. * no need to preempt or enable interrupts:
  4284. */
  4285. preempt_disable();
  4286. rq_unlock(rq, &rf);
  4287. sched_preempt_enable_no_resched();
  4288. schedule();
  4289. }
  4290. SYSCALL_DEFINE0(sched_yield)
  4291. {
  4292. do_sched_yield();
  4293. return 0;
  4294. }
  4295. #ifndef CONFIG_PREEMPT
  4296. int __sched _cond_resched(void)
  4297. {
  4298. if (should_resched(0)) {
  4299. preempt_schedule_common();
  4300. return 1;
  4301. }
  4302. rcu_all_qs();
  4303. return 0;
  4304. }
  4305. EXPORT_SYMBOL(_cond_resched);
  4306. #endif
  4307. /*
  4308. * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
  4309. * call schedule, and on return reacquire the lock.
  4310. *
  4311. * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
  4312. * operations here to prevent schedule() from being called twice (once via
  4313. * spin_unlock(), once by hand).
  4314. */
  4315. int __cond_resched_lock(spinlock_t *lock)
  4316. {
  4317. int resched = should_resched(PREEMPT_LOCK_OFFSET);
  4318. int ret = 0;
  4319. lockdep_assert_held(lock);
  4320. if (spin_needbreak(lock) || resched) {
  4321. spin_unlock(lock);
  4322. if (resched)
  4323. preempt_schedule_common();
  4324. else
  4325. cpu_relax();
  4326. ret = 1;
  4327. spin_lock(lock);
  4328. }
  4329. return ret;
  4330. }
  4331. EXPORT_SYMBOL(__cond_resched_lock);
  4332. /**
  4333. * yield - yield the current processor to other threads.
  4334. *
  4335. * Do not ever use this function, there's a 99% chance you're doing it wrong.
  4336. *
  4337. * The scheduler is at all times free to pick the calling task as the most
  4338. * eligible task to run, if removing the yield() call from your code breaks
  4339. * it, its already broken.
  4340. *
  4341. * Typical broken usage is:
  4342. *
  4343. * while (!event)
  4344. * yield();
  4345. *
  4346. * where one assumes that yield() will let 'the other' process run that will
  4347. * make event true. If the current task is a SCHED_FIFO task that will never
  4348. * happen. Never use yield() as a progress guarantee!!
  4349. *
  4350. * If you want to use yield() to wait for something, use wait_event().
  4351. * If you want to use yield() to be 'nice' for others, use cond_resched().
  4352. * If you still want to use yield(), do not!
  4353. */
  4354. void __sched yield(void)
  4355. {
  4356. set_current_state(TASK_RUNNING);
  4357. do_sched_yield();
  4358. }
  4359. EXPORT_SYMBOL(yield);
  4360. /**
  4361. * yield_to - yield the current processor to another thread in
  4362. * your thread group, or accelerate that thread toward the
  4363. * processor it's on.
  4364. * @p: target task
  4365. * @preempt: whether task preemption is allowed or not
  4366. *
  4367. * It's the caller's job to ensure that the target task struct
  4368. * can't go away on us before we can do any checks.
  4369. *
  4370. * Return:
  4371. * true (>0) if we indeed boosted the target task.
  4372. * false (0) if we failed to boost the target.
  4373. * -ESRCH if there's no task to yield to.
  4374. */
  4375. int __sched yield_to(struct task_struct *p, bool preempt)
  4376. {
  4377. struct task_struct *curr = current;
  4378. struct rq *rq, *p_rq;
  4379. unsigned long flags;
  4380. int yielded = 0;
  4381. local_irq_save(flags);
  4382. rq = this_rq();
  4383. again:
  4384. p_rq = task_rq(p);
  4385. /*
  4386. * If we're the only runnable task on the rq and target rq also
  4387. * has only one task, there's absolutely no point in yielding.
  4388. */
  4389. if (rq->nr_running == 1 && p_rq->nr_running == 1) {
  4390. yielded = -ESRCH;
  4391. goto out_irq;
  4392. }
  4393. double_rq_lock(rq, p_rq);
  4394. if (task_rq(p) != p_rq) {
  4395. double_rq_unlock(rq, p_rq);
  4396. goto again;
  4397. }
  4398. if (!curr->sched_class->yield_to_task)
  4399. goto out_unlock;
  4400. if (curr->sched_class != p->sched_class)
  4401. goto out_unlock;
  4402. if (task_running(p_rq, p) || p->state)
  4403. goto out_unlock;
  4404. yielded = curr->sched_class->yield_to_task(rq, p, preempt);
  4405. if (yielded) {
  4406. schedstat_inc(rq->yld_count);
  4407. /*
  4408. * Make p's CPU reschedule; pick_next_entity takes care of
  4409. * fairness.
  4410. */
  4411. if (preempt && rq != p_rq)
  4412. resched_curr(p_rq);
  4413. }
  4414. out_unlock:
  4415. double_rq_unlock(rq, p_rq);
  4416. out_irq:
  4417. local_irq_restore(flags);
  4418. if (yielded > 0)
  4419. schedule();
  4420. return yielded;
  4421. }
  4422. EXPORT_SYMBOL_GPL(yield_to);
  4423. int io_schedule_prepare(void)
  4424. {
  4425. int old_iowait = current->in_iowait;
  4426. current->in_iowait = 1;
  4427. blk_schedule_flush_plug(current);
  4428. return old_iowait;
  4429. }
  4430. void io_schedule_finish(int token)
  4431. {
  4432. current->in_iowait = token;
  4433. }
  4434. /*
  4435. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  4436. * that process accounting knows that this is a task in IO wait state.
  4437. */
  4438. long __sched io_schedule_timeout(long timeout)
  4439. {
  4440. int token;
  4441. long ret;
  4442. token = io_schedule_prepare();
  4443. ret = schedule_timeout(timeout);
  4444. io_schedule_finish(token);
  4445. return ret;
  4446. }
  4447. EXPORT_SYMBOL(io_schedule_timeout);
  4448. void __sched io_schedule(void)
  4449. {
  4450. int token;
  4451. token = io_schedule_prepare();
  4452. schedule();
  4453. io_schedule_finish(token);
  4454. }
  4455. EXPORT_SYMBOL(io_schedule);
  4456. /**
  4457. * sys_sched_get_priority_max - return maximum RT priority.
  4458. * @policy: scheduling class.
  4459. *
  4460. * Return: On success, this syscall returns the maximum
  4461. * rt_priority that can be used by a given scheduling class.
  4462. * On failure, a negative error code is returned.
  4463. */
  4464. SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
  4465. {
  4466. int ret = -EINVAL;
  4467. switch (policy) {
  4468. case SCHED_FIFO:
  4469. case SCHED_RR:
  4470. ret = MAX_USER_RT_PRIO-1;
  4471. break;
  4472. case SCHED_DEADLINE:
  4473. case SCHED_NORMAL:
  4474. case SCHED_BATCH:
  4475. case SCHED_IDLE:
  4476. ret = 0;
  4477. break;
  4478. }
  4479. return ret;
  4480. }
  4481. /**
  4482. * sys_sched_get_priority_min - return minimum RT priority.
  4483. * @policy: scheduling class.
  4484. *
  4485. * Return: On success, this syscall returns the minimum
  4486. * rt_priority that can be used by a given scheduling class.
  4487. * On failure, a negative error code is returned.
  4488. */
  4489. SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
  4490. {
  4491. int ret = -EINVAL;
  4492. switch (policy) {
  4493. case SCHED_FIFO:
  4494. case SCHED_RR:
  4495. ret = 1;
  4496. break;
  4497. case SCHED_DEADLINE:
  4498. case SCHED_NORMAL:
  4499. case SCHED_BATCH:
  4500. case SCHED_IDLE:
  4501. ret = 0;
  4502. }
  4503. return ret;
  4504. }
  4505. static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
  4506. {
  4507. struct task_struct *p;
  4508. unsigned int time_slice;
  4509. struct rq_flags rf;
  4510. struct rq *rq;
  4511. int retval;
  4512. if (pid < 0)
  4513. return -EINVAL;
  4514. retval = -ESRCH;
  4515. rcu_read_lock();
  4516. p = find_process_by_pid(pid);
  4517. if (!p)
  4518. goto out_unlock;
  4519. retval = security_task_getscheduler(p);
  4520. if (retval)
  4521. goto out_unlock;
  4522. rq = task_rq_lock(p, &rf);
  4523. time_slice = 0;
  4524. if (p->sched_class->get_rr_interval)
  4525. time_slice = p->sched_class->get_rr_interval(rq, p);
  4526. task_rq_unlock(rq, p, &rf);
  4527. rcu_read_unlock();
  4528. jiffies_to_timespec64(time_slice, t);
  4529. return 0;
  4530. out_unlock:
  4531. rcu_read_unlock();
  4532. return retval;
  4533. }
  4534. /**
  4535. * sys_sched_rr_get_interval - return the default timeslice of a process.
  4536. * @pid: pid of the process.
  4537. * @interval: userspace pointer to the timeslice value.
  4538. *
  4539. * this syscall writes the default timeslice value of a given process
  4540. * into the user-space timespec buffer. A value of '0' means infinity.
  4541. *
  4542. * Return: On success, 0 and the timeslice is in @interval. Otherwise,
  4543. * an error code.
  4544. */
  4545. SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
  4546. struct timespec __user *, interval)
  4547. {
  4548. struct timespec64 t;
  4549. int retval = sched_rr_get_interval(pid, &t);
  4550. if (retval == 0)
  4551. retval = put_timespec64(&t, interval);
  4552. return retval;
  4553. }
  4554. #ifdef CONFIG_COMPAT
  4555. COMPAT_SYSCALL_DEFINE2(sched_rr_get_interval,
  4556. compat_pid_t, pid,
  4557. struct compat_timespec __user *, interval)
  4558. {
  4559. struct timespec64 t;
  4560. int retval = sched_rr_get_interval(pid, &t);
  4561. if (retval == 0)
  4562. retval = compat_put_timespec64(&t, interval);
  4563. return retval;
  4564. }
  4565. #endif
  4566. void sched_show_task(struct task_struct *p)
  4567. {
  4568. unsigned long free = 0;
  4569. int ppid;
  4570. if (!try_get_task_stack(p))
  4571. return;
  4572. printk(KERN_INFO "%-15.15s %c", p->comm, task_state_to_char(p));
  4573. if (p->state == TASK_RUNNING)
  4574. printk(KERN_CONT " running task ");
  4575. #ifdef CONFIG_DEBUG_STACK_USAGE
  4576. free = stack_not_used(p);
  4577. #endif
  4578. ppid = 0;
  4579. rcu_read_lock();
  4580. if (pid_alive(p))
  4581. ppid = task_pid_nr(rcu_dereference(p->real_parent));
  4582. rcu_read_unlock();
  4583. printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
  4584. task_pid_nr(p), ppid,
  4585. (unsigned long)task_thread_info(p)->flags);
  4586. print_worker_info(KERN_INFO, p);
  4587. show_stack(p, NULL);
  4588. put_task_stack(p);
  4589. }
  4590. EXPORT_SYMBOL_GPL(sched_show_task);
  4591. static inline bool
  4592. state_filter_match(unsigned long state_filter, struct task_struct *p)
  4593. {
  4594. /* no filter, everything matches */
  4595. if (!state_filter)
  4596. return true;
  4597. /* filter, but doesn't match */
  4598. if (!(p->state & state_filter))
  4599. return false;
  4600. /*
  4601. * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
  4602. * TASK_KILLABLE).
  4603. */
  4604. if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
  4605. return false;
  4606. return true;
  4607. }
  4608. void show_state_filter(unsigned long state_filter)
  4609. {
  4610. struct task_struct *g, *p;
  4611. #if BITS_PER_LONG == 32
  4612. printk(KERN_INFO
  4613. " task PC stack pid father\n");
  4614. #else
  4615. printk(KERN_INFO
  4616. " task PC stack pid father\n");
  4617. #endif
  4618. rcu_read_lock();
  4619. for_each_process_thread(g, p) {
  4620. /*
  4621. * reset the NMI-timeout, listing all files on a slow
  4622. * console might take a lot of time:
  4623. * Also, reset softlockup watchdogs on all CPUs, because
  4624. * another CPU might be blocked waiting for us to process
  4625. * an IPI.
  4626. */
  4627. touch_nmi_watchdog();
  4628. touch_all_softlockup_watchdogs();
  4629. if (state_filter_match(state_filter, p))
  4630. sched_show_task(p);
  4631. }
  4632. #ifdef CONFIG_SCHED_DEBUG
  4633. if (!state_filter)
  4634. sysrq_sched_debug_show();
  4635. #endif
  4636. rcu_read_unlock();
  4637. /*
  4638. * Only show locks if all tasks are dumped:
  4639. */
  4640. if (!state_filter)
  4641. debug_show_all_locks();
  4642. }
  4643. /**
  4644. * init_idle - set up an idle thread for a given CPU
  4645. * @idle: task in question
  4646. * @cpu: CPU the idle task belongs to
  4647. *
  4648. * NOTE: this function does not set the idle thread's NEED_RESCHED
  4649. * flag, to make booting more robust.
  4650. */
  4651. void init_idle(struct task_struct *idle, int cpu)
  4652. {
  4653. struct rq *rq = cpu_rq(cpu);
  4654. unsigned long flags;
  4655. __sched_fork(0, idle);
  4656. raw_spin_lock_irqsave(&idle->pi_lock, flags);
  4657. raw_spin_lock(&rq->lock);
  4658. idle->state = TASK_RUNNING;
  4659. idle->se.exec_start = sched_clock();
  4660. idle->flags |= PF_IDLE;
  4661. kasan_unpoison_task_stack(idle);
  4662. #ifdef CONFIG_SMP
  4663. /*
  4664. * Its possible that init_idle() gets called multiple times on a task,
  4665. * in that case do_set_cpus_allowed() will not do the right thing.
  4666. *
  4667. * And since this is boot we can forgo the serialization.
  4668. */
  4669. set_cpus_allowed_common(idle, cpumask_of(cpu));
  4670. #endif
  4671. /*
  4672. * We're having a chicken and egg problem, even though we are
  4673. * holding rq->lock, the CPU isn't yet set to this CPU so the
  4674. * lockdep check in task_group() will fail.
  4675. *
  4676. * Similar case to sched_fork(). / Alternatively we could
  4677. * use task_rq_lock() here and obtain the other rq->lock.
  4678. *
  4679. * Silence PROVE_RCU
  4680. */
  4681. rcu_read_lock();
  4682. __set_task_cpu(idle, cpu);
  4683. rcu_read_unlock();
  4684. rq->curr = rq->idle = idle;
  4685. idle->on_rq = TASK_ON_RQ_QUEUED;
  4686. #ifdef CONFIG_SMP
  4687. idle->on_cpu = 1;
  4688. #endif
  4689. raw_spin_unlock(&rq->lock);
  4690. raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
  4691. /* Set the preempt count _outside_ the spinlocks! */
  4692. init_idle_preempt_count(idle, cpu);
  4693. /*
  4694. * The idle tasks have their own, simple scheduling class:
  4695. */
  4696. idle->sched_class = &idle_sched_class;
  4697. ftrace_graph_init_idle_task(idle, cpu);
  4698. vtime_init_idle(idle, cpu);
  4699. #ifdef CONFIG_SMP
  4700. sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
  4701. #endif
  4702. }
  4703. #ifdef CONFIG_SMP
  4704. int cpuset_cpumask_can_shrink(const struct cpumask *cur,
  4705. const struct cpumask *trial)
  4706. {
  4707. int ret = 1;
  4708. if (!cpumask_weight(cur))
  4709. return ret;
  4710. ret = dl_cpuset_cpumask_can_shrink(cur, trial);
  4711. return ret;
  4712. }
  4713. int task_can_attach(struct task_struct *p,
  4714. const struct cpumask *cs_cpus_allowed)
  4715. {
  4716. int ret = 0;
  4717. /*
  4718. * Kthreads which disallow setaffinity shouldn't be moved
  4719. * to a new cpuset; we don't want to change their CPU
  4720. * affinity and isolating such threads by their set of
  4721. * allowed nodes is unnecessary. Thus, cpusets are not
  4722. * applicable for such threads. This prevents checking for
  4723. * success of set_cpus_allowed_ptr() on all attached tasks
  4724. * before cpus_allowed may be changed.
  4725. */
  4726. if (p->flags & PF_NO_SETAFFINITY) {
  4727. ret = -EINVAL;
  4728. goto out;
  4729. }
  4730. if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
  4731. cs_cpus_allowed))
  4732. ret = dl_task_can_attach(p, cs_cpus_allowed);
  4733. out:
  4734. return ret;
  4735. }
  4736. bool sched_smp_initialized __read_mostly;
  4737. #ifdef CONFIG_NUMA_BALANCING
  4738. /* Migrate current task p to target_cpu */
  4739. int migrate_task_to(struct task_struct *p, int target_cpu)
  4740. {
  4741. struct migration_arg arg = { p, target_cpu };
  4742. int curr_cpu = task_cpu(p);
  4743. if (curr_cpu == target_cpu)
  4744. return 0;
  4745. if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
  4746. return -EINVAL;
  4747. /* TODO: This is not properly updating schedstats */
  4748. trace_sched_move_numa(p, curr_cpu, target_cpu);
  4749. return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
  4750. }
  4751. /*
  4752. * Requeue a task on a given node and accurately track the number of NUMA
  4753. * tasks on the runqueues
  4754. */
  4755. void sched_setnuma(struct task_struct *p, int nid)
  4756. {
  4757. bool queued, running;
  4758. struct rq_flags rf;
  4759. struct rq *rq;
  4760. rq = task_rq_lock(p, &rf);
  4761. queued = task_on_rq_queued(p);
  4762. running = task_current(rq, p);
  4763. if (queued)
  4764. dequeue_task(rq, p, DEQUEUE_SAVE);
  4765. if (running)
  4766. put_prev_task(rq, p);
  4767. p->numa_preferred_nid = nid;
  4768. if (queued)
  4769. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  4770. if (running)
  4771. set_curr_task(rq, p);
  4772. task_rq_unlock(rq, p, &rf);
  4773. }
  4774. #endif /* CONFIG_NUMA_BALANCING */
  4775. #ifdef CONFIG_HOTPLUG_CPU
  4776. /*
  4777. * Ensure that the idle task is using init_mm right before its CPU goes
  4778. * offline.
  4779. */
  4780. void idle_task_exit(void)
  4781. {
  4782. struct mm_struct *mm = current->active_mm;
  4783. BUG_ON(cpu_online(smp_processor_id()));
  4784. if (mm != &init_mm) {
  4785. switch_mm(mm, &init_mm, current);
  4786. current->active_mm = &init_mm;
  4787. finish_arch_post_lock_switch();
  4788. }
  4789. mmdrop(mm);
  4790. }
  4791. /*
  4792. * Since this CPU is going 'away' for a while, fold any nr_active delta
  4793. * we might have. Assumes we're called after migrate_tasks() so that the
  4794. * nr_active count is stable. We need to take the teardown thread which
  4795. * is calling this into account, so we hand in adjust = 1 to the load
  4796. * calculation.
  4797. *
  4798. * Also see the comment "Global load-average calculations".
  4799. */
  4800. static void calc_load_migrate(struct rq *rq)
  4801. {
  4802. long delta = calc_load_fold_active(rq, 1);
  4803. if (delta)
  4804. atomic_long_add(delta, &calc_load_tasks);
  4805. }
  4806. static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
  4807. {
  4808. }
  4809. static const struct sched_class fake_sched_class = {
  4810. .put_prev_task = put_prev_task_fake,
  4811. };
  4812. static struct task_struct fake_task = {
  4813. /*
  4814. * Avoid pull_{rt,dl}_task()
  4815. */
  4816. .prio = MAX_PRIO + 1,
  4817. .sched_class = &fake_sched_class,
  4818. };
  4819. /*
  4820. * Migrate all tasks from the rq, sleeping tasks will be migrated by
  4821. * try_to_wake_up()->select_task_rq().
  4822. *
  4823. * Called with rq->lock held even though we'er in stop_machine() and
  4824. * there's no concurrency possible, we hold the required locks anyway
  4825. * because of lock validation efforts.
  4826. */
  4827. static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf)
  4828. {
  4829. struct rq *rq = dead_rq;
  4830. struct task_struct *next, *stop = rq->stop;
  4831. struct rq_flags orf = *rf;
  4832. int dest_cpu;
  4833. /*
  4834. * Fudge the rq selection such that the below task selection loop
  4835. * doesn't get stuck on the currently eligible stop task.
  4836. *
  4837. * We're currently inside stop_machine() and the rq is either stuck
  4838. * in the stop_machine_cpu_stop() loop, or we're executing this code,
  4839. * either way we should never end up calling schedule() until we're
  4840. * done here.
  4841. */
  4842. rq->stop = NULL;
  4843. /*
  4844. * put_prev_task() and pick_next_task() sched
  4845. * class method both need to have an up-to-date
  4846. * value of rq->clock[_task]
  4847. */
  4848. update_rq_clock(rq);
  4849. for (;;) {
  4850. /*
  4851. * There's this thread running, bail when that's the only
  4852. * remaining thread:
  4853. */
  4854. if (rq->nr_running == 1)
  4855. break;
  4856. /*
  4857. * pick_next_task() assumes pinned rq->lock:
  4858. */
  4859. next = pick_next_task(rq, &fake_task, rf);
  4860. BUG_ON(!next);
  4861. put_prev_task(rq, next);
  4862. /*
  4863. * Rules for changing task_struct::cpus_allowed are holding
  4864. * both pi_lock and rq->lock, such that holding either
  4865. * stabilizes the mask.
  4866. *
  4867. * Drop rq->lock is not quite as disastrous as it usually is
  4868. * because !cpu_active at this point, which means load-balance
  4869. * will not interfere. Also, stop-machine.
  4870. */
  4871. rq_unlock(rq, rf);
  4872. raw_spin_lock(&next->pi_lock);
  4873. rq_relock(rq, rf);
  4874. /*
  4875. * Since we're inside stop-machine, _nothing_ should have
  4876. * changed the task, WARN if weird stuff happened, because in
  4877. * that case the above rq->lock drop is a fail too.
  4878. */
  4879. if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
  4880. raw_spin_unlock(&next->pi_lock);
  4881. continue;
  4882. }
  4883. /* Find suitable destination for @next, with force if needed. */
  4884. dest_cpu = select_fallback_rq(dead_rq->cpu, next);
  4885. rq = __migrate_task(rq, rf, next, dest_cpu);
  4886. if (rq != dead_rq) {
  4887. rq_unlock(rq, rf);
  4888. rq = dead_rq;
  4889. *rf = orf;
  4890. rq_relock(rq, rf);
  4891. }
  4892. raw_spin_unlock(&next->pi_lock);
  4893. }
  4894. rq->stop = stop;
  4895. }
  4896. #endif /* CONFIG_HOTPLUG_CPU */
  4897. void set_rq_online(struct rq *rq)
  4898. {
  4899. if (!rq->online) {
  4900. const struct sched_class *class;
  4901. cpumask_set_cpu(rq->cpu, rq->rd->online);
  4902. rq->online = 1;
  4903. for_each_class(class) {
  4904. if (class->rq_online)
  4905. class->rq_online(rq);
  4906. }
  4907. }
  4908. }
  4909. void set_rq_offline(struct rq *rq)
  4910. {
  4911. if (rq->online) {
  4912. const struct sched_class *class;
  4913. for_each_class(class) {
  4914. if (class->rq_offline)
  4915. class->rq_offline(rq);
  4916. }
  4917. cpumask_clear_cpu(rq->cpu, rq->rd->online);
  4918. rq->online = 0;
  4919. }
  4920. }
  4921. /*
  4922. * used to mark begin/end of suspend/resume:
  4923. */
  4924. static int num_cpus_frozen;
  4925. /*
  4926. * Update cpusets according to cpu_active mask. If cpusets are
  4927. * disabled, cpuset_update_active_cpus() becomes a simple wrapper
  4928. * around partition_sched_domains().
  4929. *
  4930. * If we come here as part of a suspend/resume, don't touch cpusets because we
  4931. * want to restore it back to its original state upon resume anyway.
  4932. */
  4933. static void cpuset_cpu_active(void)
  4934. {
  4935. if (cpuhp_tasks_frozen) {
  4936. /*
  4937. * num_cpus_frozen tracks how many CPUs are involved in suspend
  4938. * resume sequence. As long as this is not the last online
  4939. * operation in the resume sequence, just build a single sched
  4940. * domain, ignoring cpusets.
  4941. */
  4942. partition_sched_domains(1, NULL, NULL);
  4943. if (--num_cpus_frozen)
  4944. return;
  4945. /*
  4946. * This is the last CPU online operation. So fall through and
  4947. * restore the original sched domains by considering the
  4948. * cpuset configurations.
  4949. */
  4950. cpuset_force_rebuild();
  4951. }
  4952. cpuset_update_active_cpus();
  4953. }
  4954. static int cpuset_cpu_inactive(unsigned int cpu)
  4955. {
  4956. if (!cpuhp_tasks_frozen) {
  4957. if (dl_cpu_busy(cpu))
  4958. return -EBUSY;
  4959. cpuset_update_active_cpus();
  4960. } else {
  4961. num_cpus_frozen++;
  4962. partition_sched_domains(1, NULL, NULL);
  4963. }
  4964. return 0;
  4965. }
  4966. int sched_cpu_activate(unsigned int cpu)
  4967. {
  4968. struct rq *rq = cpu_rq(cpu);
  4969. struct rq_flags rf;
  4970. #ifdef CONFIG_SCHED_SMT
  4971. /*
  4972. * When going up, increment the number of cores with SMT present.
  4973. */
  4974. if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
  4975. static_branch_inc_cpuslocked(&sched_smt_present);
  4976. #endif
  4977. set_cpu_active(cpu, true);
  4978. if (sched_smp_initialized) {
  4979. sched_domains_numa_masks_set(cpu);
  4980. cpuset_cpu_active();
  4981. }
  4982. /*
  4983. * Put the rq online, if not already. This happens:
  4984. *
  4985. * 1) In the early boot process, because we build the real domains
  4986. * after all CPUs have been brought up.
  4987. *
  4988. * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
  4989. * domains.
  4990. */
  4991. rq_lock_irqsave(rq, &rf);
  4992. if (rq->rd) {
  4993. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  4994. set_rq_online(rq);
  4995. }
  4996. rq_unlock_irqrestore(rq, &rf);
  4997. update_max_interval();
  4998. return 0;
  4999. }
  5000. int sched_cpu_deactivate(unsigned int cpu)
  5001. {
  5002. int ret;
  5003. set_cpu_active(cpu, false);
  5004. /*
  5005. * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
  5006. * users of this state to go away such that all new such users will
  5007. * observe it.
  5008. *
  5009. * Do sync before park smpboot threads to take care the rcu boost case.
  5010. */
  5011. synchronize_rcu_mult(call_rcu, call_rcu_sched);
  5012. #ifdef CONFIG_SCHED_SMT
  5013. /*
  5014. * When going down, decrement the number of cores with SMT present.
  5015. */
  5016. if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
  5017. static_branch_dec_cpuslocked(&sched_smt_present);
  5018. #endif
  5019. if (!sched_smp_initialized)
  5020. return 0;
  5021. ret = cpuset_cpu_inactive(cpu);
  5022. if (ret) {
  5023. set_cpu_active(cpu, true);
  5024. return ret;
  5025. }
  5026. sched_domains_numa_masks_clear(cpu);
  5027. return 0;
  5028. }
  5029. static void sched_rq_cpu_starting(unsigned int cpu)
  5030. {
  5031. struct rq *rq = cpu_rq(cpu);
  5032. rq->calc_load_update = calc_load_update;
  5033. update_max_interval();
  5034. }
  5035. int sched_cpu_starting(unsigned int cpu)
  5036. {
  5037. sched_rq_cpu_starting(cpu);
  5038. sched_tick_start(cpu);
  5039. return 0;
  5040. }
  5041. #ifdef CONFIG_HOTPLUG_CPU
  5042. int sched_cpu_dying(unsigned int cpu)
  5043. {
  5044. struct rq *rq = cpu_rq(cpu);
  5045. struct rq_flags rf;
  5046. /* Handle pending wakeups and then migrate everything off */
  5047. sched_ttwu_pending();
  5048. sched_tick_stop(cpu);
  5049. rq_lock_irqsave(rq, &rf);
  5050. if (rq->rd) {
  5051. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  5052. set_rq_offline(rq);
  5053. }
  5054. migrate_tasks(rq, &rf);
  5055. BUG_ON(rq->nr_running != 1);
  5056. rq_unlock_irqrestore(rq, &rf);
  5057. calc_load_migrate(rq);
  5058. update_max_interval();
  5059. nohz_balance_exit_idle(rq);
  5060. hrtick_clear(rq);
  5061. return 0;
  5062. }
  5063. #endif
  5064. void __init sched_init_smp(void)
  5065. {
  5066. sched_init_numa();
  5067. /*
  5068. * There's no userspace yet to cause hotplug operations; hence all the
  5069. * CPU masks are stable and all blatant races in the below code cannot
  5070. * happen. The hotplug lock is nevertheless taken to satisfy lockdep,
  5071. * but there won't be any contention on it.
  5072. */
  5073. cpus_read_lock();
  5074. mutex_lock(&sched_domains_mutex);
  5075. sched_init_domains(cpu_active_mask);
  5076. mutex_unlock(&sched_domains_mutex);
  5077. cpus_read_unlock();
  5078. /* Move init over to a non-isolated CPU */
  5079. if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
  5080. BUG();
  5081. sched_init_granularity();
  5082. init_sched_rt_class();
  5083. init_sched_dl_class();
  5084. sched_smp_initialized = true;
  5085. }
  5086. static int __init migration_init(void)
  5087. {
  5088. sched_rq_cpu_starting(smp_processor_id());
  5089. return 0;
  5090. }
  5091. early_initcall(migration_init);
  5092. #else
  5093. void __init sched_init_smp(void)
  5094. {
  5095. sched_init_granularity();
  5096. }
  5097. #endif /* CONFIG_SMP */
  5098. int in_sched_functions(unsigned long addr)
  5099. {
  5100. return in_lock_functions(addr) ||
  5101. (addr >= (unsigned long)__sched_text_start
  5102. && addr < (unsigned long)__sched_text_end);
  5103. }
  5104. #ifdef CONFIG_CGROUP_SCHED
  5105. /*
  5106. * Default task group.
  5107. * Every task in system belongs to this group at bootup.
  5108. */
  5109. struct task_group root_task_group;
  5110. LIST_HEAD(task_groups);
  5111. /* Cacheline aligned slab cache for task_group */
  5112. static struct kmem_cache *task_group_cache __read_mostly;
  5113. #endif
  5114. DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
  5115. DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
  5116. void __init sched_init(void)
  5117. {
  5118. int i, j;
  5119. unsigned long alloc_size = 0, ptr;
  5120. wait_bit_init();
  5121. #ifdef CONFIG_FAIR_GROUP_SCHED
  5122. alloc_size += 2 * nr_cpu_ids * sizeof(void **);
  5123. #endif
  5124. #ifdef CONFIG_RT_GROUP_SCHED
  5125. alloc_size += 2 * nr_cpu_ids * sizeof(void **);
  5126. #endif
  5127. if (alloc_size) {
  5128. ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
  5129. #ifdef CONFIG_FAIR_GROUP_SCHED
  5130. root_task_group.se = (struct sched_entity **)ptr;
  5131. ptr += nr_cpu_ids * sizeof(void **);
  5132. root_task_group.cfs_rq = (struct cfs_rq **)ptr;
  5133. ptr += nr_cpu_ids * sizeof(void **);
  5134. #endif /* CONFIG_FAIR_GROUP_SCHED */
  5135. #ifdef CONFIG_RT_GROUP_SCHED
  5136. root_task_group.rt_se = (struct sched_rt_entity **)ptr;
  5137. ptr += nr_cpu_ids * sizeof(void **);
  5138. root_task_group.rt_rq = (struct rt_rq **)ptr;
  5139. ptr += nr_cpu_ids * sizeof(void **);
  5140. #endif /* CONFIG_RT_GROUP_SCHED */
  5141. }
  5142. #ifdef CONFIG_CPUMASK_OFFSTACK
  5143. for_each_possible_cpu(i) {
  5144. per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
  5145. cpumask_size(), GFP_KERNEL, cpu_to_node(i));
  5146. per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
  5147. cpumask_size(), GFP_KERNEL, cpu_to_node(i));
  5148. }
  5149. #endif /* CONFIG_CPUMASK_OFFSTACK */
  5150. init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
  5151. init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
  5152. #ifdef CONFIG_SMP
  5153. init_defrootdomain();
  5154. #endif
  5155. #ifdef CONFIG_RT_GROUP_SCHED
  5156. init_rt_bandwidth(&root_task_group.rt_bandwidth,
  5157. global_rt_period(), global_rt_runtime());
  5158. #endif /* CONFIG_RT_GROUP_SCHED */
  5159. #ifdef CONFIG_CGROUP_SCHED
  5160. task_group_cache = KMEM_CACHE(task_group, 0);
  5161. list_add(&root_task_group.list, &task_groups);
  5162. INIT_LIST_HEAD(&root_task_group.children);
  5163. INIT_LIST_HEAD(&root_task_group.siblings);
  5164. autogroup_init(&init_task);
  5165. #endif /* CONFIG_CGROUP_SCHED */
  5166. for_each_possible_cpu(i) {
  5167. struct rq *rq;
  5168. rq = cpu_rq(i);
  5169. raw_spin_lock_init(&rq->lock);
  5170. rq->nr_running = 0;
  5171. rq->calc_load_active = 0;
  5172. rq->calc_load_update = jiffies + LOAD_FREQ;
  5173. init_cfs_rq(&rq->cfs);
  5174. init_rt_rq(&rq->rt);
  5175. init_dl_rq(&rq->dl);
  5176. #ifdef CONFIG_FAIR_GROUP_SCHED
  5177. root_task_group.shares = ROOT_TASK_GROUP_LOAD;
  5178. INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
  5179. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  5180. /*
  5181. * How much CPU bandwidth does root_task_group get?
  5182. *
  5183. * In case of task-groups formed thr' the cgroup filesystem, it
  5184. * gets 100% of the CPU resources in the system. This overall
  5185. * system CPU resource is divided among the tasks of
  5186. * root_task_group and its child task-groups in a fair manner,
  5187. * based on each entity's (task or task-group's) weight
  5188. * (se->load.weight).
  5189. *
  5190. * In other words, if root_task_group has 10 tasks of weight
  5191. * 1024) and two child groups A0 and A1 (of weight 1024 each),
  5192. * then A0's share of the CPU resource is:
  5193. *
  5194. * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
  5195. *
  5196. * We achieve this by letting root_task_group's tasks sit
  5197. * directly in rq->cfs (i.e root_task_group->se[] = NULL).
  5198. */
  5199. init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
  5200. init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
  5201. #endif /* CONFIG_FAIR_GROUP_SCHED */
  5202. rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
  5203. #ifdef CONFIG_RT_GROUP_SCHED
  5204. init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
  5205. #endif
  5206. for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
  5207. rq->cpu_load[j] = 0;
  5208. #ifdef CONFIG_SMP
  5209. rq->sd = NULL;
  5210. rq->rd = NULL;
  5211. rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
  5212. rq->balance_callback = NULL;
  5213. rq->active_balance = 0;
  5214. rq->next_balance = jiffies;
  5215. rq->push_cpu = 0;
  5216. rq->cpu = i;
  5217. rq->online = 0;
  5218. rq->idle_stamp = 0;
  5219. rq->avg_idle = 2*sysctl_sched_migration_cost;
  5220. rq->max_idle_balance_cost = sysctl_sched_migration_cost;
  5221. INIT_LIST_HEAD(&rq->cfs_tasks);
  5222. rq_attach_root(rq, &def_root_domain);
  5223. #ifdef CONFIG_NO_HZ_COMMON
  5224. rq->last_load_update_tick = jiffies;
  5225. rq->last_blocked_load_update_tick = jiffies;
  5226. atomic_set(&rq->nohz_flags, 0);
  5227. #endif
  5228. #endif /* CONFIG_SMP */
  5229. hrtick_rq_init(rq);
  5230. atomic_set(&rq->nr_iowait, 0);
  5231. }
  5232. set_load_weight(&init_task, false);
  5233. /*
  5234. * The boot idle thread does lazy MMU switching as well:
  5235. */
  5236. mmgrab(&init_mm);
  5237. enter_lazy_tlb(&init_mm, current);
  5238. /*
  5239. * Make us the idle thread. Technically, schedule() should not be
  5240. * called from this thread, however somewhere below it might be,
  5241. * but because we are the idle thread, we just pick up running again
  5242. * when this runqueue becomes "idle".
  5243. */
  5244. init_idle(current, smp_processor_id());
  5245. calc_load_update = jiffies + LOAD_FREQ;
  5246. #ifdef CONFIG_SMP
  5247. idle_thread_set_boot_cpu();
  5248. #endif
  5249. init_sched_fair_class();
  5250. init_schedstats();
  5251. scheduler_running = 1;
  5252. }
  5253. #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
  5254. static inline int preempt_count_equals(int preempt_offset)
  5255. {
  5256. int nested = preempt_count() + rcu_preempt_depth();
  5257. return (nested == preempt_offset);
  5258. }
  5259. void __might_sleep(const char *file, int line, int preempt_offset)
  5260. {
  5261. /*
  5262. * Blocking primitives will set (and therefore destroy) current->state,
  5263. * since we will exit with TASK_RUNNING make sure we enter with it,
  5264. * otherwise we will destroy state.
  5265. */
  5266. WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
  5267. "do not call blocking ops when !TASK_RUNNING; "
  5268. "state=%lx set at [<%p>] %pS\n",
  5269. current->state,
  5270. (void *)current->task_state_change,
  5271. (void *)current->task_state_change);
  5272. ___might_sleep(file, line, preempt_offset);
  5273. }
  5274. EXPORT_SYMBOL(__might_sleep);
  5275. void ___might_sleep(const char *file, int line, int preempt_offset)
  5276. {
  5277. /* Ratelimiting timestamp: */
  5278. static unsigned long prev_jiffy;
  5279. unsigned long preempt_disable_ip;
  5280. /* WARN_ON_ONCE() by default, no rate limit required: */
  5281. rcu_sleep_check();
  5282. if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
  5283. !is_idle_task(current)) ||
  5284. system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
  5285. oops_in_progress)
  5286. return;
  5287. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  5288. return;
  5289. prev_jiffy = jiffies;
  5290. /* Save this before calling printk(), since that will clobber it: */
  5291. preempt_disable_ip = get_preempt_disable_ip(current);
  5292. printk(KERN_ERR
  5293. "BUG: sleeping function called from invalid context at %s:%d\n",
  5294. file, line);
  5295. printk(KERN_ERR
  5296. "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
  5297. in_atomic(), irqs_disabled(),
  5298. current->pid, current->comm);
  5299. if (task_stack_end_corrupted(current))
  5300. printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
  5301. debug_show_held_locks(current);
  5302. if (irqs_disabled())
  5303. print_irqtrace_events(current);
  5304. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
  5305. && !preempt_count_equals(preempt_offset)) {
  5306. pr_err("Preemption disabled at:");
  5307. print_ip_sym(preempt_disable_ip);
  5308. pr_cont("\n");
  5309. }
  5310. dump_stack();
  5311. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  5312. }
  5313. EXPORT_SYMBOL(___might_sleep);
  5314. #endif
  5315. #ifdef CONFIG_MAGIC_SYSRQ
  5316. void normalize_rt_tasks(void)
  5317. {
  5318. struct task_struct *g, *p;
  5319. struct sched_attr attr = {
  5320. .sched_policy = SCHED_NORMAL,
  5321. };
  5322. read_lock(&tasklist_lock);
  5323. for_each_process_thread(g, p) {
  5324. /*
  5325. * Only normalize user tasks:
  5326. */
  5327. if (p->flags & PF_KTHREAD)
  5328. continue;
  5329. p->se.exec_start = 0;
  5330. schedstat_set(p->se.statistics.wait_start, 0);
  5331. schedstat_set(p->se.statistics.sleep_start, 0);
  5332. schedstat_set(p->se.statistics.block_start, 0);
  5333. if (!dl_task(p) && !rt_task(p)) {
  5334. /*
  5335. * Renice negative nice level userspace
  5336. * tasks back to 0:
  5337. */
  5338. if (task_nice(p) < 0)
  5339. set_user_nice(p, 0);
  5340. continue;
  5341. }
  5342. __sched_setscheduler(p, &attr, false, false);
  5343. }
  5344. read_unlock(&tasklist_lock);
  5345. }
  5346. #endif /* CONFIG_MAGIC_SYSRQ */
  5347. #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
  5348. /*
  5349. * These functions are only useful for the IA64 MCA handling, or kdb.
  5350. *
  5351. * They can only be called when the whole system has been
  5352. * stopped - every CPU needs to be quiescent, and no scheduling
  5353. * activity can take place. Using them for anything else would
  5354. * be a serious bug, and as a result, they aren't even visible
  5355. * under any other configuration.
  5356. */
  5357. /**
  5358. * curr_task - return the current task for a given CPU.
  5359. * @cpu: the processor in question.
  5360. *
  5361. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  5362. *
  5363. * Return: The current task for @cpu.
  5364. */
  5365. struct task_struct *curr_task(int cpu)
  5366. {
  5367. return cpu_curr(cpu);
  5368. }
  5369. #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
  5370. #ifdef CONFIG_IA64
  5371. /**
  5372. * set_curr_task - set the current task for a given CPU.
  5373. * @cpu: the processor in question.
  5374. * @p: the task pointer to set.
  5375. *
  5376. * Description: This function must only be used when non-maskable interrupts
  5377. * are serviced on a separate stack. It allows the architecture to switch the
  5378. * notion of the current task on a CPU in a non-blocking manner. This function
  5379. * must be called with all CPU's synchronized, and interrupts disabled, the
  5380. * and caller must save the original value of the current task (see
  5381. * curr_task() above) and restore that value before reenabling interrupts and
  5382. * re-starting the system.
  5383. *
  5384. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  5385. */
  5386. void ia64_set_curr_task(int cpu, struct task_struct *p)
  5387. {
  5388. cpu_curr(cpu) = p;
  5389. }
  5390. #endif
  5391. #ifdef CONFIG_CGROUP_SCHED
  5392. /* task_group_lock serializes the addition/removal of task groups */
  5393. static DEFINE_SPINLOCK(task_group_lock);
  5394. static void sched_free_group(struct task_group *tg)
  5395. {
  5396. free_fair_sched_group(tg);
  5397. free_rt_sched_group(tg);
  5398. autogroup_free(tg);
  5399. kmem_cache_free(task_group_cache, tg);
  5400. }
  5401. /* allocate runqueue etc for a new task group */
  5402. struct task_group *sched_create_group(struct task_group *parent)
  5403. {
  5404. struct task_group *tg;
  5405. tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
  5406. if (!tg)
  5407. return ERR_PTR(-ENOMEM);
  5408. if (!alloc_fair_sched_group(tg, parent))
  5409. goto err;
  5410. if (!alloc_rt_sched_group(tg, parent))
  5411. goto err;
  5412. return tg;
  5413. err:
  5414. sched_free_group(tg);
  5415. return ERR_PTR(-ENOMEM);
  5416. }
  5417. void sched_online_group(struct task_group *tg, struct task_group *parent)
  5418. {
  5419. unsigned long flags;
  5420. spin_lock_irqsave(&task_group_lock, flags);
  5421. list_add_rcu(&tg->list, &task_groups);
  5422. /* Root should already exist: */
  5423. WARN_ON(!parent);
  5424. tg->parent = parent;
  5425. INIT_LIST_HEAD(&tg->children);
  5426. list_add_rcu(&tg->siblings, &parent->children);
  5427. spin_unlock_irqrestore(&task_group_lock, flags);
  5428. online_fair_sched_group(tg);
  5429. }
  5430. /* rcu callback to free various structures associated with a task group */
  5431. static void sched_free_group_rcu(struct rcu_head *rhp)
  5432. {
  5433. /* Now it should be safe to free those cfs_rqs: */
  5434. sched_free_group(container_of(rhp, struct task_group, rcu));
  5435. }
  5436. void sched_destroy_group(struct task_group *tg)
  5437. {
  5438. /* Wait for possible concurrent references to cfs_rqs complete: */
  5439. call_rcu(&tg->rcu, sched_free_group_rcu);
  5440. }
  5441. void sched_offline_group(struct task_group *tg)
  5442. {
  5443. unsigned long flags;
  5444. /* End participation in shares distribution: */
  5445. unregister_fair_sched_group(tg);
  5446. spin_lock_irqsave(&task_group_lock, flags);
  5447. list_del_rcu(&tg->list);
  5448. list_del_rcu(&tg->siblings);
  5449. spin_unlock_irqrestore(&task_group_lock, flags);
  5450. }
  5451. static void sched_change_group(struct task_struct *tsk, int type)
  5452. {
  5453. struct task_group *tg;
  5454. /*
  5455. * All callers are synchronized by task_rq_lock(); we do not use RCU
  5456. * which is pointless here. Thus, we pass "true" to task_css_check()
  5457. * to prevent lockdep warnings.
  5458. */
  5459. tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
  5460. struct task_group, css);
  5461. tg = autogroup_task_group(tsk, tg);
  5462. tsk->sched_task_group = tg;
  5463. #ifdef CONFIG_FAIR_GROUP_SCHED
  5464. if (tsk->sched_class->task_change_group)
  5465. tsk->sched_class->task_change_group(tsk, type);
  5466. else
  5467. #endif
  5468. set_task_rq(tsk, task_cpu(tsk));
  5469. }
  5470. /*
  5471. * Change task's runqueue when it moves between groups.
  5472. *
  5473. * The caller of this function should have put the task in its new group by
  5474. * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
  5475. * its new group.
  5476. */
  5477. void sched_move_task(struct task_struct *tsk)
  5478. {
  5479. int queued, running, queue_flags =
  5480. DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  5481. struct rq_flags rf;
  5482. struct rq *rq;
  5483. rq = task_rq_lock(tsk, &rf);
  5484. update_rq_clock(rq);
  5485. running = task_current(rq, tsk);
  5486. queued = task_on_rq_queued(tsk);
  5487. if (queued)
  5488. dequeue_task(rq, tsk, queue_flags);
  5489. if (running)
  5490. put_prev_task(rq, tsk);
  5491. sched_change_group(tsk, TASK_MOVE_GROUP);
  5492. if (queued)
  5493. enqueue_task(rq, tsk, queue_flags);
  5494. if (running)
  5495. set_curr_task(rq, tsk);
  5496. task_rq_unlock(rq, tsk, &rf);
  5497. }
  5498. static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
  5499. {
  5500. return css ? container_of(css, struct task_group, css) : NULL;
  5501. }
  5502. static struct cgroup_subsys_state *
  5503. cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  5504. {
  5505. struct task_group *parent = css_tg(parent_css);
  5506. struct task_group *tg;
  5507. if (!parent) {
  5508. /* This is early initialization for the top cgroup */
  5509. return &root_task_group.css;
  5510. }
  5511. tg = sched_create_group(parent);
  5512. if (IS_ERR(tg))
  5513. return ERR_PTR(-ENOMEM);
  5514. return &tg->css;
  5515. }
  5516. /* Expose task group only after completing cgroup initialization */
  5517. static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
  5518. {
  5519. struct task_group *tg = css_tg(css);
  5520. struct task_group *parent = css_tg(css->parent);
  5521. if (parent)
  5522. sched_online_group(tg, parent);
  5523. return 0;
  5524. }
  5525. static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
  5526. {
  5527. struct task_group *tg = css_tg(css);
  5528. sched_offline_group(tg);
  5529. }
  5530. static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
  5531. {
  5532. struct task_group *tg = css_tg(css);
  5533. /*
  5534. * Relies on the RCU grace period between css_released() and this.
  5535. */
  5536. sched_free_group(tg);
  5537. }
  5538. /*
  5539. * This is called before wake_up_new_task(), therefore we really only
  5540. * have to set its group bits, all the other stuff does not apply.
  5541. */
  5542. static void cpu_cgroup_fork(struct task_struct *task)
  5543. {
  5544. struct rq_flags rf;
  5545. struct rq *rq;
  5546. rq = task_rq_lock(task, &rf);
  5547. update_rq_clock(rq);
  5548. sched_change_group(task, TASK_SET_GROUP);
  5549. task_rq_unlock(rq, task, &rf);
  5550. }
  5551. static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
  5552. {
  5553. struct task_struct *task;
  5554. struct cgroup_subsys_state *css;
  5555. int ret = 0;
  5556. cgroup_taskset_for_each(task, css, tset) {
  5557. #ifdef CONFIG_RT_GROUP_SCHED
  5558. if (!sched_rt_can_attach(css_tg(css), task))
  5559. return -EINVAL;
  5560. #endif
  5561. /*
  5562. * Serialize against wake_up_new_task() such that if its
  5563. * running, we're sure to observe its full state.
  5564. */
  5565. raw_spin_lock_irq(&task->pi_lock);
  5566. /*
  5567. * Avoid calling sched_move_task() before wake_up_new_task()
  5568. * has happened. This would lead to problems with PELT, due to
  5569. * move wanting to detach+attach while we're not attached yet.
  5570. */
  5571. if (task->state == TASK_NEW)
  5572. ret = -EINVAL;
  5573. raw_spin_unlock_irq(&task->pi_lock);
  5574. if (ret)
  5575. break;
  5576. }
  5577. return ret;
  5578. }
  5579. static void cpu_cgroup_attach(struct cgroup_taskset *tset)
  5580. {
  5581. struct task_struct *task;
  5582. struct cgroup_subsys_state *css;
  5583. cgroup_taskset_for_each(task, css, tset)
  5584. sched_move_task(task);
  5585. }
  5586. #ifdef CONFIG_FAIR_GROUP_SCHED
  5587. static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
  5588. struct cftype *cftype, u64 shareval)
  5589. {
  5590. if (shareval > scale_load_down(ULONG_MAX))
  5591. shareval = MAX_SHARES;
  5592. return sched_group_set_shares(css_tg(css), scale_load(shareval));
  5593. }
  5594. static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
  5595. struct cftype *cft)
  5596. {
  5597. struct task_group *tg = css_tg(css);
  5598. return (u64) scale_load_down(tg->shares);
  5599. }
  5600. #ifdef CONFIG_CFS_BANDWIDTH
  5601. static DEFINE_MUTEX(cfs_constraints_mutex);
  5602. const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
  5603. const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
  5604. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
  5605. static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
  5606. {
  5607. int i, ret = 0, runtime_enabled, runtime_was_enabled;
  5608. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  5609. if (tg == &root_task_group)
  5610. return -EINVAL;
  5611. /*
  5612. * Ensure we have at some amount of bandwidth every period. This is
  5613. * to prevent reaching a state of large arrears when throttled via
  5614. * entity_tick() resulting in prolonged exit starvation.
  5615. */
  5616. if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
  5617. return -EINVAL;
  5618. /*
  5619. * Likewise, bound things on the otherside by preventing insane quota
  5620. * periods. This also allows us to normalize in computing quota
  5621. * feasibility.
  5622. */
  5623. if (period > max_cfs_quota_period)
  5624. return -EINVAL;
  5625. /*
  5626. * Prevent race between setting of cfs_rq->runtime_enabled and
  5627. * unthrottle_offline_cfs_rqs().
  5628. */
  5629. get_online_cpus();
  5630. mutex_lock(&cfs_constraints_mutex);
  5631. ret = __cfs_schedulable(tg, period, quota);
  5632. if (ret)
  5633. goto out_unlock;
  5634. runtime_enabled = quota != RUNTIME_INF;
  5635. runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
  5636. /*
  5637. * If we need to toggle cfs_bandwidth_used, off->on must occur
  5638. * before making related changes, and on->off must occur afterwards
  5639. */
  5640. if (runtime_enabled && !runtime_was_enabled)
  5641. cfs_bandwidth_usage_inc();
  5642. raw_spin_lock_irq(&cfs_b->lock);
  5643. cfs_b->period = ns_to_ktime(period);
  5644. cfs_b->quota = quota;
  5645. __refill_cfs_bandwidth_runtime(cfs_b);
  5646. /* Restart the period timer (if active) to handle new period expiry: */
  5647. if (runtime_enabled)
  5648. start_cfs_bandwidth(cfs_b);
  5649. raw_spin_unlock_irq(&cfs_b->lock);
  5650. for_each_online_cpu(i) {
  5651. struct cfs_rq *cfs_rq = tg->cfs_rq[i];
  5652. struct rq *rq = cfs_rq->rq;
  5653. struct rq_flags rf;
  5654. rq_lock_irq(rq, &rf);
  5655. cfs_rq->runtime_enabled = runtime_enabled;
  5656. cfs_rq->runtime_remaining = 0;
  5657. if (cfs_rq->throttled)
  5658. unthrottle_cfs_rq(cfs_rq);
  5659. rq_unlock_irq(rq, &rf);
  5660. }
  5661. if (runtime_was_enabled && !runtime_enabled)
  5662. cfs_bandwidth_usage_dec();
  5663. out_unlock:
  5664. mutex_unlock(&cfs_constraints_mutex);
  5665. put_online_cpus();
  5666. return ret;
  5667. }
  5668. int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
  5669. {
  5670. u64 quota, period;
  5671. period = ktime_to_ns(tg->cfs_bandwidth.period);
  5672. if (cfs_quota_us < 0)
  5673. quota = RUNTIME_INF;
  5674. else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
  5675. quota = (u64)cfs_quota_us * NSEC_PER_USEC;
  5676. else
  5677. return -EINVAL;
  5678. return tg_set_cfs_bandwidth(tg, period, quota);
  5679. }
  5680. long tg_get_cfs_quota(struct task_group *tg)
  5681. {
  5682. u64 quota_us;
  5683. if (tg->cfs_bandwidth.quota == RUNTIME_INF)
  5684. return -1;
  5685. quota_us = tg->cfs_bandwidth.quota;
  5686. do_div(quota_us, NSEC_PER_USEC);
  5687. return quota_us;
  5688. }
  5689. int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
  5690. {
  5691. u64 quota, period;
  5692. if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
  5693. return -EINVAL;
  5694. period = (u64)cfs_period_us * NSEC_PER_USEC;
  5695. quota = tg->cfs_bandwidth.quota;
  5696. return tg_set_cfs_bandwidth(tg, period, quota);
  5697. }
  5698. long tg_get_cfs_period(struct task_group *tg)
  5699. {
  5700. u64 cfs_period_us;
  5701. cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
  5702. do_div(cfs_period_us, NSEC_PER_USEC);
  5703. return cfs_period_us;
  5704. }
  5705. static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
  5706. struct cftype *cft)
  5707. {
  5708. return tg_get_cfs_quota(css_tg(css));
  5709. }
  5710. static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
  5711. struct cftype *cftype, s64 cfs_quota_us)
  5712. {
  5713. return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
  5714. }
  5715. static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
  5716. struct cftype *cft)
  5717. {
  5718. return tg_get_cfs_period(css_tg(css));
  5719. }
  5720. static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
  5721. struct cftype *cftype, u64 cfs_period_us)
  5722. {
  5723. return tg_set_cfs_period(css_tg(css), cfs_period_us);
  5724. }
  5725. struct cfs_schedulable_data {
  5726. struct task_group *tg;
  5727. u64 period, quota;
  5728. };
  5729. /*
  5730. * normalize group quota/period to be quota/max_period
  5731. * note: units are usecs
  5732. */
  5733. static u64 normalize_cfs_quota(struct task_group *tg,
  5734. struct cfs_schedulable_data *d)
  5735. {
  5736. u64 quota, period;
  5737. if (tg == d->tg) {
  5738. period = d->period;
  5739. quota = d->quota;
  5740. } else {
  5741. period = tg_get_cfs_period(tg);
  5742. quota = tg_get_cfs_quota(tg);
  5743. }
  5744. /* note: these should typically be equivalent */
  5745. if (quota == RUNTIME_INF || quota == -1)
  5746. return RUNTIME_INF;
  5747. return to_ratio(period, quota);
  5748. }
  5749. static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
  5750. {
  5751. struct cfs_schedulable_data *d = data;
  5752. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  5753. s64 quota = 0, parent_quota = -1;
  5754. if (!tg->parent) {
  5755. quota = RUNTIME_INF;
  5756. } else {
  5757. struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
  5758. quota = normalize_cfs_quota(tg, d);
  5759. parent_quota = parent_b->hierarchical_quota;
  5760. /*
  5761. * Ensure max(child_quota) <= parent_quota. On cgroup2,
  5762. * always take the min. On cgroup1, only inherit when no
  5763. * limit is set:
  5764. */
  5765. if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
  5766. quota = min(quota, parent_quota);
  5767. } else {
  5768. if (quota == RUNTIME_INF)
  5769. quota = parent_quota;
  5770. else if (parent_quota != RUNTIME_INF && quota > parent_quota)
  5771. return -EINVAL;
  5772. }
  5773. }
  5774. cfs_b->hierarchical_quota = quota;
  5775. return 0;
  5776. }
  5777. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
  5778. {
  5779. int ret;
  5780. struct cfs_schedulable_data data = {
  5781. .tg = tg,
  5782. .period = period,
  5783. .quota = quota,
  5784. };
  5785. if (quota != RUNTIME_INF) {
  5786. do_div(data.period, NSEC_PER_USEC);
  5787. do_div(data.quota, NSEC_PER_USEC);
  5788. }
  5789. rcu_read_lock();
  5790. ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
  5791. rcu_read_unlock();
  5792. return ret;
  5793. }
  5794. static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
  5795. {
  5796. struct task_group *tg = css_tg(seq_css(sf));
  5797. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  5798. seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
  5799. seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
  5800. seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
  5801. if (schedstat_enabled() && tg != &root_task_group) {
  5802. u64 ws = 0;
  5803. int i;
  5804. for_each_possible_cpu(i)
  5805. ws += schedstat_val(tg->se[i]->statistics.wait_sum);
  5806. seq_printf(sf, "wait_sum %llu\n", ws);
  5807. }
  5808. return 0;
  5809. }
  5810. #endif /* CONFIG_CFS_BANDWIDTH */
  5811. #endif /* CONFIG_FAIR_GROUP_SCHED */
  5812. #ifdef CONFIG_RT_GROUP_SCHED
  5813. static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
  5814. struct cftype *cft, s64 val)
  5815. {
  5816. return sched_group_set_rt_runtime(css_tg(css), val);
  5817. }
  5818. static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
  5819. struct cftype *cft)
  5820. {
  5821. return sched_group_rt_runtime(css_tg(css));
  5822. }
  5823. static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
  5824. struct cftype *cftype, u64 rt_period_us)
  5825. {
  5826. return sched_group_set_rt_period(css_tg(css), rt_period_us);
  5827. }
  5828. static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
  5829. struct cftype *cft)
  5830. {
  5831. return sched_group_rt_period(css_tg(css));
  5832. }
  5833. #endif /* CONFIG_RT_GROUP_SCHED */
  5834. static struct cftype cpu_legacy_files[] = {
  5835. #ifdef CONFIG_FAIR_GROUP_SCHED
  5836. {
  5837. .name = "shares",
  5838. .read_u64 = cpu_shares_read_u64,
  5839. .write_u64 = cpu_shares_write_u64,
  5840. },
  5841. #endif
  5842. #ifdef CONFIG_CFS_BANDWIDTH
  5843. {
  5844. .name = "cfs_quota_us",
  5845. .read_s64 = cpu_cfs_quota_read_s64,
  5846. .write_s64 = cpu_cfs_quota_write_s64,
  5847. },
  5848. {
  5849. .name = "cfs_period_us",
  5850. .read_u64 = cpu_cfs_period_read_u64,
  5851. .write_u64 = cpu_cfs_period_write_u64,
  5852. },
  5853. {
  5854. .name = "stat",
  5855. .seq_show = cpu_cfs_stat_show,
  5856. },
  5857. #endif
  5858. #ifdef CONFIG_RT_GROUP_SCHED
  5859. {
  5860. .name = "rt_runtime_us",
  5861. .read_s64 = cpu_rt_runtime_read,
  5862. .write_s64 = cpu_rt_runtime_write,
  5863. },
  5864. {
  5865. .name = "rt_period_us",
  5866. .read_u64 = cpu_rt_period_read_uint,
  5867. .write_u64 = cpu_rt_period_write_uint,
  5868. },
  5869. #endif
  5870. { } /* Terminate */
  5871. };
  5872. static int cpu_extra_stat_show(struct seq_file *sf,
  5873. struct cgroup_subsys_state *css)
  5874. {
  5875. #ifdef CONFIG_CFS_BANDWIDTH
  5876. {
  5877. struct task_group *tg = css_tg(css);
  5878. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  5879. u64 throttled_usec;
  5880. throttled_usec = cfs_b->throttled_time;
  5881. do_div(throttled_usec, NSEC_PER_USEC);
  5882. seq_printf(sf, "nr_periods %d\n"
  5883. "nr_throttled %d\n"
  5884. "throttled_usec %llu\n",
  5885. cfs_b->nr_periods, cfs_b->nr_throttled,
  5886. throttled_usec);
  5887. }
  5888. #endif
  5889. return 0;
  5890. }
  5891. #ifdef CONFIG_FAIR_GROUP_SCHED
  5892. static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
  5893. struct cftype *cft)
  5894. {
  5895. struct task_group *tg = css_tg(css);
  5896. u64 weight = scale_load_down(tg->shares);
  5897. return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
  5898. }
  5899. static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
  5900. struct cftype *cft, u64 weight)
  5901. {
  5902. /*
  5903. * cgroup weight knobs should use the common MIN, DFL and MAX
  5904. * values which are 1, 100 and 10000 respectively. While it loses
  5905. * a bit of range on both ends, it maps pretty well onto the shares
  5906. * value used by scheduler and the round-trip conversions preserve
  5907. * the original value over the entire range.
  5908. */
  5909. if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
  5910. return -ERANGE;
  5911. weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
  5912. return sched_group_set_shares(css_tg(css), scale_load(weight));
  5913. }
  5914. static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
  5915. struct cftype *cft)
  5916. {
  5917. unsigned long weight = scale_load_down(css_tg(css)->shares);
  5918. int last_delta = INT_MAX;
  5919. int prio, delta;
  5920. /* find the closest nice value to the current weight */
  5921. for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
  5922. delta = abs(sched_prio_to_weight[prio] - weight);
  5923. if (delta >= last_delta)
  5924. break;
  5925. last_delta = delta;
  5926. }
  5927. return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
  5928. }
  5929. static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
  5930. struct cftype *cft, s64 nice)
  5931. {
  5932. unsigned long weight;
  5933. int idx;
  5934. if (nice < MIN_NICE || nice > MAX_NICE)
  5935. return -ERANGE;
  5936. idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
  5937. idx = array_index_nospec(idx, 40);
  5938. weight = sched_prio_to_weight[idx];
  5939. return sched_group_set_shares(css_tg(css), scale_load(weight));
  5940. }
  5941. #endif
  5942. static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
  5943. long period, long quota)
  5944. {
  5945. if (quota < 0)
  5946. seq_puts(sf, "max");
  5947. else
  5948. seq_printf(sf, "%ld", quota);
  5949. seq_printf(sf, " %ld\n", period);
  5950. }
  5951. /* caller should put the current value in *@periodp before calling */
  5952. static int __maybe_unused cpu_period_quota_parse(char *buf,
  5953. u64 *periodp, u64 *quotap)
  5954. {
  5955. char tok[21]; /* U64_MAX */
  5956. if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
  5957. return -EINVAL;
  5958. *periodp *= NSEC_PER_USEC;
  5959. if (sscanf(tok, "%llu", quotap))
  5960. *quotap *= NSEC_PER_USEC;
  5961. else if (!strcmp(tok, "max"))
  5962. *quotap = RUNTIME_INF;
  5963. else
  5964. return -EINVAL;
  5965. return 0;
  5966. }
  5967. #ifdef CONFIG_CFS_BANDWIDTH
  5968. static int cpu_max_show(struct seq_file *sf, void *v)
  5969. {
  5970. struct task_group *tg = css_tg(seq_css(sf));
  5971. cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
  5972. return 0;
  5973. }
  5974. static ssize_t cpu_max_write(struct kernfs_open_file *of,
  5975. char *buf, size_t nbytes, loff_t off)
  5976. {
  5977. struct task_group *tg = css_tg(of_css(of));
  5978. u64 period = tg_get_cfs_period(tg);
  5979. u64 quota;
  5980. int ret;
  5981. ret = cpu_period_quota_parse(buf, &period, &quota);
  5982. if (!ret)
  5983. ret = tg_set_cfs_bandwidth(tg, period, quota);
  5984. return ret ?: nbytes;
  5985. }
  5986. #endif
  5987. static struct cftype cpu_files[] = {
  5988. #ifdef CONFIG_FAIR_GROUP_SCHED
  5989. {
  5990. .name = "weight",
  5991. .flags = CFTYPE_NOT_ON_ROOT,
  5992. .read_u64 = cpu_weight_read_u64,
  5993. .write_u64 = cpu_weight_write_u64,
  5994. },
  5995. {
  5996. .name = "weight.nice",
  5997. .flags = CFTYPE_NOT_ON_ROOT,
  5998. .read_s64 = cpu_weight_nice_read_s64,
  5999. .write_s64 = cpu_weight_nice_write_s64,
  6000. },
  6001. #endif
  6002. #ifdef CONFIG_CFS_BANDWIDTH
  6003. {
  6004. .name = "max",
  6005. .flags = CFTYPE_NOT_ON_ROOT,
  6006. .seq_show = cpu_max_show,
  6007. .write = cpu_max_write,
  6008. },
  6009. #endif
  6010. { } /* terminate */
  6011. };
  6012. struct cgroup_subsys cpu_cgrp_subsys = {
  6013. .css_alloc = cpu_cgroup_css_alloc,
  6014. .css_online = cpu_cgroup_css_online,
  6015. .css_released = cpu_cgroup_css_released,
  6016. .css_free = cpu_cgroup_css_free,
  6017. .css_extra_stat_show = cpu_extra_stat_show,
  6018. .fork = cpu_cgroup_fork,
  6019. .can_attach = cpu_cgroup_can_attach,
  6020. .attach = cpu_cgroup_attach,
  6021. .legacy_cftypes = cpu_legacy_files,
  6022. .dfl_cftypes = cpu_files,
  6023. .early_init = true,
  6024. .threaded = true,
  6025. };
  6026. #endif /* CONFIG_CGROUP_SCHED */
  6027. void dump_cpu_task(int cpu)
  6028. {
  6029. pr_info("Task dump for CPU %d:\n", cpu);
  6030. sched_show_task(cpu_curr(cpu));
  6031. }
  6032. /*
  6033. * Nice levels are multiplicative, with a gentle 10% change for every
  6034. * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
  6035. * nice 1, it will get ~10% less CPU time than another CPU-bound task
  6036. * that remained on nice 0.
  6037. *
  6038. * The "10% effect" is relative and cumulative: from _any_ nice level,
  6039. * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
  6040. * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
  6041. * If a task goes up by ~10% and another task goes down by ~10% then
  6042. * the relative distance between them is ~25%.)
  6043. */
  6044. const int sched_prio_to_weight[40] = {
  6045. /* -20 */ 88761, 71755, 56483, 46273, 36291,
  6046. /* -15 */ 29154, 23254, 18705, 14949, 11916,
  6047. /* -10 */ 9548, 7620, 6100, 4904, 3906,
  6048. /* -5 */ 3121, 2501, 1991, 1586, 1277,
  6049. /* 0 */ 1024, 820, 655, 526, 423,
  6050. /* 5 */ 335, 272, 215, 172, 137,
  6051. /* 10 */ 110, 87, 70, 56, 45,
  6052. /* 15 */ 36, 29, 23, 18, 15,
  6053. };
  6054. /*
  6055. * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
  6056. *
  6057. * In cases where the weight does not change often, we can use the
  6058. * precalculated inverse to speed up arithmetics by turning divisions
  6059. * into multiplications:
  6060. */
  6061. const u32 sched_prio_to_wmult[40] = {
  6062. /* -20 */ 48388, 59856, 76040, 92818, 118348,
  6063. /* -15 */ 147320, 184698, 229616, 287308, 360437,
  6064. /* -10 */ 449829, 563644, 704093, 875809, 1099582,
  6065. /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
  6066. /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
  6067. /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
  6068. /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
  6069. /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
  6070. };
  6071. #undef CREATE_TRACE_POINTS