core.c 166 KB

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