core.c 174 KB

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