core.c 215 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759
  1. /*
  2. * kernel/sched/core.c
  3. *
  4. * Kernel scheduler and related syscalls
  5. *
  6. * Copyright (C) 1991-2002 Linus Torvalds
  7. *
  8. * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
  9. * make semaphores SMP safe
  10. * 1998-11-19 Implemented schedule_timeout() and related stuff
  11. * by Andrea Arcangeli
  12. * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
  13. * hybrid priority-list and round-robin design with
  14. * an array-switch method of distributing timeslices
  15. * and per-CPU runqueues. Cleanups and useful suggestions
  16. * by Davide Libenzi, preemptible kernel bits by Robert Love.
  17. * 2003-09-03 Interactivity tuning by Con Kolivas.
  18. * 2004-04-02 Scheduler domains code by Nick Piggin
  19. * 2007-04-15 Work begun on replacing all interactivity tuning with a
  20. * fair scheduling design by Con Kolivas.
  21. * 2007-05-05 Load balancing (smp-nice) and other improvements
  22. * by Peter Williams
  23. * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
  24. * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
  25. * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
  26. * Thomas Gleixner, Mike Kravetz
  27. */
  28. #include <linux/kasan.h>
  29. #include <linux/mm.h>
  30. #include <linux/module.h>
  31. #include <linux/nmi.h>
  32. #include <linux/init.h>
  33. #include <linux/uaccess.h>
  34. #include <linux/highmem.h>
  35. #include <linux/mmu_context.h>
  36. #include <linux/interrupt.h>
  37. #include <linux/capability.h>
  38. #include <linux/completion.h>
  39. #include <linux/kernel_stat.h>
  40. #include <linux/debug_locks.h>
  41. #include <linux/perf_event.h>
  42. #include <linux/security.h>
  43. #include <linux/notifier.h>
  44. #include <linux/profile.h>
  45. #include <linux/freezer.h>
  46. #include <linux/vmalloc.h>
  47. #include <linux/blkdev.h>
  48. #include <linux/delay.h>
  49. #include <linux/pid_namespace.h>
  50. #include <linux/smp.h>
  51. #include <linux/threads.h>
  52. #include <linux/timer.h>
  53. #include <linux/rcupdate.h>
  54. #include <linux/cpu.h>
  55. #include <linux/cpuset.h>
  56. #include <linux/percpu.h>
  57. #include <linux/proc_fs.h>
  58. #include <linux/seq_file.h>
  59. #include <linux/sysctl.h>
  60. #include <linux/syscalls.h>
  61. #include <linux/times.h>
  62. #include <linux/tsacct_kern.h>
  63. #include <linux/kprobes.h>
  64. #include <linux/delayacct.h>
  65. #include <linux/unistd.h>
  66. #include <linux/pagemap.h>
  67. #include <linux/hrtimer.h>
  68. #include <linux/tick.h>
  69. #include <linux/ctype.h>
  70. #include <linux/ftrace.h>
  71. #include <linux/slab.h>
  72. #include <linux/init_task.h>
  73. #include <linux/context_tracking.h>
  74. #include <linux/compiler.h>
  75. #include <linux/frame.h>
  76. #include <linux/prefetch.h>
  77. #include <asm/switch_to.h>
  78. #include <asm/tlb.h>
  79. #include <asm/irq_regs.h>
  80. #include <asm/mutex.h>
  81. #ifdef CONFIG_PARAVIRT
  82. #include <asm/paravirt.h>
  83. #endif
  84. #include "sched.h"
  85. #include "../workqueue_internal.h"
  86. #include "../smpboot.h"
  87. #define CREATE_TRACE_POINTS
  88. #include <trace/events/sched.h>
  89. DEFINE_MUTEX(sched_domains_mutex);
  90. DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
  91. static void update_rq_clock_task(struct rq *rq, s64 delta);
  92. void update_rq_clock(struct rq *rq)
  93. {
  94. s64 delta;
  95. lockdep_assert_held(&rq->lock);
  96. if (rq->clock_skip_update & RQCF_ACT_SKIP)
  97. return;
  98. delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
  99. if (delta < 0)
  100. return;
  101. rq->clock += delta;
  102. update_rq_clock_task(rq, delta);
  103. }
  104. /*
  105. * Debugging: various feature bits
  106. */
  107. #define SCHED_FEAT(name, enabled) \
  108. (1UL << __SCHED_FEAT_##name) * enabled |
  109. const_debug unsigned int sysctl_sched_features =
  110. #include "features.h"
  111. 0;
  112. #undef SCHED_FEAT
  113. /*
  114. * Number of tasks to iterate in a single balance run.
  115. * Limited because this is done with IRQs disabled.
  116. */
  117. const_debug unsigned int sysctl_sched_nr_migrate = 32;
  118. /*
  119. * period over which we average the RT time consumption, measured
  120. * in ms.
  121. *
  122. * default: 1s
  123. */
  124. const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
  125. /*
  126. * period over which we measure -rt task cpu usage in us.
  127. * default: 1s
  128. */
  129. unsigned int sysctl_sched_rt_period = 1000000;
  130. __read_mostly int scheduler_running;
  131. /*
  132. * part of the period that we allow rt tasks to run in us.
  133. * default: 0.95s
  134. */
  135. int sysctl_sched_rt_runtime = 950000;
  136. /* cpus with isolated domains */
  137. cpumask_var_t cpu_isolated_map;
  138. /*
  139. * this_rq_lock - lock this runqueue and disable interrupts.
  140. */
  141. static struct rq *this_rq_lock(void)
  142. __acquires(rq->lock)
  143. {
  144. struct rq *rq;
  145. local_irq_disable();
  146. rq = this_rq();
  147. raw_spin_lock(&rq->lock);
  148. return rq;
  149. }
  150. /*
  151. * __task_rq_lock - lock the rq @p resides on.
  152. */
  153. struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  154. __acquires(rq->lock)
  155. {
  156. struct rq *rq;
  157. lockdep_assert_held(&p->pi_lock);
  158. for (;;) {
  159. rq = task_rq(p);
  160. raw_spin_lock(&rq->lock);
  161. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  162. rf->cookie = lockdep_pin_lock(&rq->lock);
  163. return rq;
  164. }
  165. raw_spin_unlock(&rq->lock);
  166. while (unlikely(task_on_rq_migrating(p)))
  167. cpu_relax();
  168. }
  169. }
  170. /*
  171. * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
  172. */
  173. struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  174. __acquires(p->pi_lock)
  175. __acquires(rq->lock)
  176. {
  177. struct rq *rq;
  178. for (;;) {
  179. raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
  180. rq = task_rq(p);
  181. raw_spin_lock(&rq->lock);
  182. /*
  183. * move_queued_task() task_rq_lock()
  184. *
  185. * ACQUIRE (rq->lock)
  186. * [S] ->on_rq = MIGRATING [L] rq = task_rq()
  187. * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
  188. * [S] ->cpu = new_cpu [L] task_rq()
  189. * [L] ->on_rq
  190. * RELEASE (rq->lock)
  191. *
  192. * If we observe the old cpu in task_rq_lock, the acquire of
  193. * the old rq->lock will fully serialize against the stores.
  194. *
  195. * If we observe the new cpu in task_rq_lock, the acquire will
  196. * pair with the WMB to ensure we must then also see migrating.
  197. */
  198. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  199. rf->cookie = lockdep_pin_lock(&rq->lock);
  200. return rq;
  201. }
  202. raw_spin_unlock(&rq->lock);
  203. raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
  204. while (unlikely(task_on_rq_migrating(p)))
  205. cpu_relax();
  206. }
  207. }
  208. #ifdef CONFIG_SCHED_HRTICK
  209. /*
  210. * Use HR-timers to deliver accurate preemption points.
  211. */
  212. static void hrtick_clear(struct rq *rq)
  213. {
  214. if (hrtimer_active(&rq->hrtick_timer))
  215. hrtimer_cancel(&rq->hrtick_timer);
  216. }
  217. /*
  218. * High-resolution timer tick.
  219. * Runs from hardirq context with interrupts disabled.
  220. */
  221. static enum hrtimer_restart hrtick(struct hrtimer *timer)
  222. {
  223. struct rq *rq = container_of(timer, struct rq, hrtick_timer);
  224. WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
  225. raw_spin_lock(&rq->lock);
  226. update_rq_clock(rq);
  227. rq->curr->sched_class->task_tick(rq, rq->curr, 1);
  228. raw_spin_unlock(&rq->lock);
  229. return HRTIMER_NORESTART;
  230. }
  231. #ifdef CONFIG_SMP
  232. static void __hrtick_restart(struct rq *rq)
  233. {
  234. struct hrtimer *timer = &rq->hrtick_timer;
  235. hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
  236. }
  237. /*
  238. * called from hardirq (IPI) context
  239. */
  240. static void __hrtick_start(void *arg)
  241. {
  242. struct rq *rq = arg;
  243. raw_spin_lock(&rq->lock);
  244. __hrtick_restart(rq);
  245. rq->hrtick_csd_pending = 0;
  246. raw_spin_unlock(&rq->lock);
  247. }
  248. /*
  249. * Called to set the hrtick timer state.
  250. *
  251. * called with rq->lock held and irqs disabled
  252. */
  253. void hrtick_start(struct rq *rq, u64 delay)
  254. {
  255. struct hrtimer *timer = &rq->hrtick_timer;
  256. ktime_t time;
  257. s64 delta;
  258. /*
  259. * Don't schedule slices shorter than 10000ns, that just
  260. * doesn't make sense and can cause timer DoS.
  261. */
  262. delta = max_t(s64, delay, 10000LL);
  263. time = ktime_add_ns(timer->base->get_time(), delta);
  264. hrtimer_set_expires(timer, time);
  265. if (rq == this_rq()) {
  266. __hrtick_restart(rq);
  267. } else if (!rq->hrtick_csd_pending) {
  268. smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
  269. rq->hrtick_csd_pending = 1;
  270. }
  271. }
  272. #else
  273. /*
  274. * Called to set the hrtick timer state.
  275. *
  276. * called with rq->lock held and irqs disabled
  277. */
  278. void hrtick_start(struct rq *rq, u64 delay)
  279. {
  280. /*
  281. * Don't schedule slices shorter than 10000ns, that just
  282. * doesn't make sense. Rely on vruntime for fairness.
  283. */
  284. delay = max_t(u64, delay, 10000LL);
  285. hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
  286. HRTIMER_MODE_REL_PINNED);
  287. }
  288. #endif /* CONFIG_SMP */
  289. static void init_rq_hrtick(struct rq *rq)
  290. {
  291. #ifdef CONFIG_SMP
  292. rq->hrtick_csd_pending = 0;
  293. rq->hrtick_csd.flags = 0;
  294. rq->hrtick_csd.func = __hrtick_start;
  295. rq->hrtick_csd.info = rq;
  296. #endif
  297. hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  298. rq->hrtick_timer.function = hrtick;
  299. }
  300. #else /* CONFIG_SCHED_HRTICK */
  301. static inline void hrtick_clear(struct rq *rq)
  302. {
  303. }
  304. static inline void init_rq_hrtick(struct rq *rq)
  305. {
  306. }
  307. #endif /* CONFIG_SCHED_HRTICK */
  308. /*
  309. * cmpxchg based fetch_or, macro so it works for different integer types
  310. */
  311. #define fetch_or(ptr, mask) \
  312. ({ \
  313. typeof(ptr) _ptr = (ptr); \
  314. typeof(mask) _mask = (mask); \
  315. typeof(*_ptr) _old, _val = *_ptr; \
  316. \
  317. for (;;) { \
  318. _old = cmpxchg(_ptr, _val, _val | _mask); \
  319. if (_old == _val) \
  320. break; \
  321. _val = _old; \
  322. } \
  323. _old; \
  324. })
  325. #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
  326. /*
  327. * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
  328. * this avoids any races wrt polling state changes and thereby avoids
  329. * spurious IPIs.
  330. */
  331. static bool set_nr_and_not_polling(struct task_struct *p)
  332. {
  333. struct thread_info *ti = task_thread_info(p);
  334. return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
  335. }
  336. /*
  337. * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
  338. *
  339. * If this returns true, then the idle task promises to call
  340. * sched_ttwu_pending() and reschedule soon.
  341. */
  342. static bool set_nr_if_polling(struct task_struct *p)
  343. {
  344. struct thread_info *ti = task_thread_info(p);
  345. typeof(ti->flags) old, val = READ_ONCE(ti->flags);
  346. for (;;) {
  347. if (!(val & _TIF_POLLING_NRFLAG))
  348. return false;
  349. if (val & _TIF_NEED_RESCHED)
  350. return true;
  351. old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
  352. if (old == val)
  353. break;
  354. val = old;
  355. }
  356. return true;
  357. }
  358. #else
  359. static bool set_nr_and_not_polling(struct task_struct *p)
  360. {
  361. set_tsk_need_resched(p);
  362. return true;
  363. }
  364. #ifdef CONFIG_SMP
  365. static bool set_nr_if_polling(struct task_struct *p)
  366. {
  367. return false;
  368. }
  369. #endif
  370. #endif
  371. void wake_q_add(struct wake_q_head *head, struct task_struct *task)
  372. {
  373. struct wake_q_node *node = &task->wake_q;
  374. /*
  375. * Atomically grab the task, if ->wake_q is !nil already it means
  376. * its already queued (either by us or someone else) and will get the
  377. * wakeup due to that.
  378. *
  379. * This cmpxchg() implies a full barrier, which pairs with the write
  380. * barrier implied by the wakeup in wake_up_q().
  381. */
  382. if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
  383. return;
  384. get_task_struct(task);
  385. /*
  386. * The head is context local, there can be no concurrency.
  387. */
  388. *head->lastp = node;
  389. head->lastp = &node->next;
  390. }
  391. void wake_up_q(struct wake_q_head *head)
  392. {
  393. struct wake_q_node *node = head->first;
  394. while (node != WAKE_Q_TAIL) {
  395. struct task_struct *task;
  396. task = container_of(node, struct task_struct, wake_q);
  397. BUG_ON(!task);
  398. /* task can safely be re-inserted now */
  399. node = node->next;
  400. task->wake_q.next = NULL;
  401. /*
  402. * wake_up_process() implies a wmb() to pair with the queueing
  403. * in wake_q_add() so as not to miss wakeups.
  404. */
  405. wake_up_process(task);
  406. put_task_struct(task);
  407. }
  408. }
  409. /*
  410. * resched_curr - mark rq's current task 'to be rescheduled now'.
  411. *
  412. * On UP this means the setting of the need_resched flag, on SMP it
  413. * might also involve a cross-CPU call to trigger the scheduler on
  414. * the target CPU.
  415. */
  416. void resched_curr(struct rq *rq)
  417. {
  418. struct task_struct *curr = rq->curr;
  419. int cpu;
  420. lockdep_assert_held(&rq->lock);
  421. if (test_tsk_need_resched(curr))
  422. return;
  423. cpu = cpu_of(rq);
  424. if (cpu == smp_processor_id()) {
  425. set_tsk_need_resched(curr);
  426. set_preempt_need_resched();
  427. return;
  428. }
  429. if (set_nr_and_not_polling(curr))
  430. smp_send_reschedule(cpu);
  431. else
  432. trace_sched_wake_idle_without_ipi(cpu);
  433. }
  434. void resched_cpu(int cpu)
  435. {
  436. struct rq *rq = cpu_rq(cpu);
  437. unsigned long flags;
  438. if (!raw_spin_trylock_irqsave(&rq->lock, flags))
  439. return;
  440. resched_curr(rq);
  441. raw_spin_unlock_irqrestore(&rq->lock, flags);
  442. }
  443. #ifdef CONFIG_SMP
  444. #ifdef CONFIG_NO_HZ_COMMON
  445. /*
  446. * In the semi idle case, use the nearest busy cpu for migrating timers
  447. * from an idle cpu. This is good for power-savings.
  448. *
  449. * We don't do similar optimization for completely idle system, as
  450. * selecting an idle cpu will add more delays to the timers than intended
  451. * (as that cpu's timer base may not be uptodate wrt jiffies etc).
  452. */
  453. int get_nohz_timer_target(void)
  454. {
  455. int i, cpu = smp_processor_id();
  456. struct sched_domain *sd;
  457. if (!idle_cpu(cpu) && is_housekeeping_cpu(cpu))
  458. return cpu;
  459. rcu_read_lock();
  460. for_each_domain(cpu, sd) {
  461. for_each_cpu(i, sched_domain_span(sd)) {
  462. if (cpu == i)
  463. continue;
  464. if (!idle_cpu(i) && is_housekeeping_cpu(i)) {
  465. cpu = i;
  466. goto unlock;
  467. }
  468. }
  469. }
  470. if (!is_housekeeping_cpu(cpu))
  471. cpu = housekeeping_any_cpu();
  472. unlock:
  473. rcu_read_unlock();
  474. return cpu;
  475. }
  476. /*
  477. * When add_timer_on() enqueues a timer into the timer wheel of an
  478. * idle CPU then this timer might expire before the next timer event
  479. * which is scheduled to wake up that CPU. In case of a completely
  480. * idle system the next event might even be infinite time into the
  481. * future. wake_up_idle_cpu() ensures that the CPU is woken up and
  482. * leaves the inner idle loop so the newly added timer is taken into
  483. * account when the CPU goes back to idle and evaluates the timer
  484. * wheel for the next timer event.
  485. */
  486. static void wake_up_idle_cpu(int cpu)
  487. {
  488. struct rq *rq = cpu_rq(cpu);
  489. if (cpu == smp_processor_id())
  490. return;
  491. if (set_nr_and_not_polling(rq->idle))
  492. smp_send_reschedule(cpu);
  493. else
  494. trace_sched_wake_idle_without_ipi(cpu);
  495. }
  496. static bool wake_up_full_nohz_cpu(int cpu)
  497. {
  498. /*
  499. * We just need the target to call irq_exit() and re-evaluate
  500. * the next tick. The nohz full kick at least implies that.
  501. * If needed we can still optimize that later with an
  502. * empty IRQ.
  503. */
  504. if (tick_nohz_full_cpu(cpu)) {
  505. if (cpu != smp_processor_id() ||
  506. tick_nohz_tick_stopped())
  507. tick_nohz_full_kick_cpu(cpu);
  508. return true;
  509. }
  510. return false;
  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. update_rq_clock(rq);
  643. if (!(flags & ENQUEUE_RESTORE))
  644. sched_info_queued(rq, p);
  645. p->sched_class->enqueue_task(rq, p, flags);
  646. }
  647. static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
  648. {
  649. update_rq_clock(rq);
  650. if (!(flags & DEQUEUE_SAVE))
  651. sched_info_dequeued(rq, p);
  652. p->sched_class->dequeue_task(rq, p, flags);
  653. }
  654. void activate_task(struct rq *rq, struct task_struct *p, int flags)
  655. {
  656. if (task_contributes_to_load(p))
  657. rq->nr_uninterruptible--;
  658. enqueue_task(rq, p, flags);
  659. }
  660. void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
  661. {
  662. if (task_contributes_to_load(p))
  663. rq->nr_uninterruptible++;
  664. dequeue_task(rq, p, flags);
  665. }
  666. static void update_rq_clock_task(struct rq *rq, s64 delta)
  667. {
  668. /*
  669. * In theory, the compile should just see 0 here, and optimize out the call
  670. * to sched_rt_avg_update. But I don't trust it...
  671. */
  672. #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
  673. s64 steal = 0, irq_delta = 0;
  674. #endif
  675. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  676. irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
  677. /*
  678. * Since irq_time is only updated on {soft,}irq_exit, we might run into
  679. * this case when a previous update_rq_clock() happened inside a
  680. * {soft,}irq region.
  681. *
  682. * When this happens, we stop ->clock_task and only update the
  683. * prev_irq_time stamp to account for the part that fit, so that a next
  684. * update will consume the rest. This ensures ->clock_task is
  685. * monotonic.
  686. *
  687. * It does however cause some slight miss-attribution of {soft,}irq
  688. * time, a more accurate solution would be to update the irq_time using
  689. * the current rq->clock timestamp, except that would require using
  690. * atomic ops.
  691. */
  692. if (irq_delta > delta)
  693. irq_delta = delta;
  694. rq->prev_irq_time += irq_delta;
  695. delta -= irq_delta;
  696. #endif
  697. #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
  698. if (static_key_false((&paravirt_steal_rq_enabled))) {
  699. steal = paravirt_steal_clock(cpu_of(rq));
  700. steal -= rq->prev_steal_time_rq;
  701. if (unlikely(steal > delta))
  702. steal = delta;
  703. rq->prev_steal_time_rq += steal;
  704. delta -= steal;
  705. }
  706. #endif
  707. rq->clock_task += delta;
  708. #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
  709. if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
  710. sched_rt_avg_update(rq, irq_delta + steal);
  711. #endif
  712. }
  713. void sched_set_stop_task(int cpu, struct task_struct *stop)
  714. {
  715. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  716. struct task_struct *old_stop = cpu_rq(cpu)->stop;
  717. if (stop) {
  718. /*
  719. * Make it appear like a SCHED_FIFO task, its something
  720. * userspace knows about and won't get confused about.
  721. *
  722. * Also, it will make PI more or less work without too
  723. * much confusion -- but then, stop work should not
  724. * rely on PI working anyway.
  725. */
  726. sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
  727. stop->sched_class = &stop_sched_class;
  728. }
  729. cpu_rq(cpu)->stop = stop;
  730. if (old_stop) {
  731. /*
  732. * Reset it back to a normal scheduling class so that
  733. * it can die in pieces.
  734. */
  735. old_stop->sched_class = &rt_sched_class;
  736. }
  737. }
  738. /*
  739. * __normal_prio - return the priority that is based on the static prio
  740. */
  741. static inline int __normal_prio(struct task_struct *p)
  742. {
  743. return p->static_prio;
  744. }
  745. /*
  746. * Calculate the expected normal priority: i.e. priority
  747. * without taking RT-inheritance into account. Might be
  748. * boosted by interactivity modifiers. Changes upon fork,
  749. * setprio syscalls, and whenever the interactivity
  750. * estimator recalculates.
  751. */
  752. static inline int normal_prio(struct task_struct *p)
  753. {
  754. int prio;
  755. if (task_has_dl_policy(p))
  756. prio = MAX_DL_PRIO-1;
  757. else if (task_has_rt_policy(p))
  758. prio = MAX_RT_PRIO-1 - p->rt_priority;
  759. else
  760. prio = __normal_prio(p);
  761. return prio;
  762. }
  763. /*
  764. * Calculate the current priority, i.e. the priority
  765. * taken into account by the scheduler. This value might
  766. * be boosted by RT tasks, or might be boosted by
  767. * interactivity modifiers. Will be RT if the task got
  768. * RT-boosted. If not then it returns p->normal_prio.
  769. */
  770. static int effective_prio(struct task_struct *p)
  771. {
  772. p->normal_prio = normal_prio(p);
  773. /*
  774. * If we are RT tasks or we were boosted to RT priority,
  775. * keep the priority unchanged. Otherwise, update priority
  776. * to the normal priority:
  777. */
  778. if (!rt_prio(p->prio))
  779. return p->normal_prio;
  780. return p->prio;
  781. }
  782. /**
  783. * task_curr - is this task currently executing on a CPU?
  784. * @p: the task in question.
  785. *
  786. * Return: 1 if the task is currently executing. 0 otherwise.
  787. */
  788. inline int task_curr(const struct task_struct *p)
  789. {
  790. return cpu_curr(task_cpu(p)) == p;
  791. }
  792. /*
  793. * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
  794. * use the balance_callback list if you want balancing.
  795. *
  796. * this means any call to check_class_changed() must be followed by a call to
  797. * balance_callback().
  798. */
  799. static inline void check_class_changed(struct rq *rq, struct task_struct *p,
  800. const struct sched_class *prev_class,
  801. int oldprio)
  802. {
  803. if (prev_class != p->sched_class) {
  804. if (prev_class->switched_from)
  805. prev_class->switched_from(rq, p);
  806. p->sched_class->switched_to(rq, p);
  807. } else if (oldprio != p->prio || dl_task(p))
  808. p->sched_class->prio_changed(rq, p, oldprio);
  809. }
  810. void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
  811. {
  812. const struct sched_class *class;
  813. if (p->sched_class == rq->curr->sched_class) {
  814. rq->curr->sched_class->check_preempt_curr(rq, p, flags);
  815. } else {
  816. for_each_class(class) {
  817. if (class == rq->curr->sched_class)
  818. break;
  819. if (class == p->sched_class) {
  820. resched_curr(rq);
  821. break;
  822. }
  823. }
  824. }
  825. /*
  826. * A queue event has occurred, and we're going to schedule. In
  827. * this case, we can save a useless back to back clock update.
  828. */
  829. if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
  830. rq_clock_skip_update(rq, true);
  831. }
  832. #ifdef CONFIG_SMP
  833. /*
  834. * This is how migration works:
  835. *
  836. * 1) we invoke migration_cpu_stop() on the target CPU using
  837. * stop_one_cpu().
  838. * 2) stopper starts to run (implicitly forcing the migrated thread
  839. * off the CPU)
  840. * 3) it checks whether the migrated task is still in the wrong runqueue.
  841. * 4) if it's in the wrong runqueue then the migration thread removes
  842. * it and puts it into the right queue.
  843. * 5) stopper completes and stop_one_cpu() returns and the migration
  844. * is done.
  845. */
  846. /*
  847. * move_queued_task - move a queued task to new rq.
  848. *
  849. * Returns (locked) new rq. Old rq's lock is released.
  850. */
  851. static struct rq *move_queued_task(struct rq *rq, struct task_struct *p, int new_cpu)
  852. {
  853. lockdep_assert_held(&rq->lock);
  854. p->on_rq = TASK_ON_RQ_MIGRATING;
  855. dequeue_task(rq, p, 0);
  856. set_task_cpu(p, new_cpu);
  857. raw_spin_unlock(&rq->lock);
  858. rq = cpu_rq(new_cpu);
  859. raw_spin_lock(&rq->lock);
  860. BUG_ON(task_cpu(p) != new_cpu);
  861. enqueue_task(rq, p, 0);
  862. p->on_rq = TASK_ON_RQ_QUEUED;
  863. check_preempt_curr(rq, p, 0);
  864. return rq;
  865. }
  866. struct migration_arg {
  867. struct task_struct *task;
  868. int dest_cpu;
  869. };
  870. /*
  871. * Move (not current) task off this cpu, onto dest cpu. We're doing
  872. * this because either it can't run here any more (set_cpus_allowed()
  873. * away from this CPU, or CPU going down), or because we're
  874. * attempting to rebalance this task on exec (sched_exec).
  875. *
  876. * So we race with normal scheduler movements, but that's OK, as long
  877. * as the task is no longer on this CPU.
  878. */
  879. static struct rq *__migrate_task(struct rq *rq, struct task_struct *p, int dest_cpu)
  880. {
  881. if (unlikely(!cpu_active(dest_cpu)))
  882. return rq;
  883. /* Affinity changed (again). */
  884. if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
  885. return rq;
  886. rq = move_queued_task(rq, p, dest_cpu);
  887. return rq;
  888. }
  889. /*
  890. * migration_cpu_stop - this will be executed by a highprio stopper thread
  891. * and performs thread migration by bumping thread off CPU then
  892. * 'pushing' onto another runqueue.
  893. */
  894. static int migration_cpu_stop(void *data)
  895. {
  896. struct migration_arg *arg = data;
  897. struct task_struct *p = arg->task;
  898. struct rq *rq = this_rq();
  899. /*
  900. * The original target cpu might have gone down and we might
  901. * be on another cpu but it doesn't matter.
  902. */
  903. local_irq_disable();
  904. /*
  905. * We need to explicitly wake pending tasks before running
  906. * __migrate_task() such that we will not miss enforcing cpus_allowed
  907. * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
  908. */
  909. sched_ttwu_pending();
  910. raw_spin_lock(&p->pi_lock);
  911. raw_spin_lock(&rq->lock);
  912. /*
  913. * If task_rq(p) != rq, it cannot be migrated here, because we're
  914. * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
  915. * we're holding p->pi_lock.
  916. */
  917. if (task_rq(p) == rq) {
  918. if (task_on_rq_queued(p))
  919. rq = __migrate_task(rq, p, arg->dest_cpu);
  920. else
  921. p->wake_cpu = arg->dest_cpu;
  922. }
  923. raw_spin_unlock(&rq->lock);
  924. raw_spin_unlock(&p->pi_lock);
  925. local_irq_enable();
  926. return 0;
  927. }
  928. /*
  929. * sched_class::set_cpus_allowed must do the below, but is not required to
  930. * actually call this function.
  931. */
  932. void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
  933. {
  934. cpumask_copy(&p->cpus_allowed, new_mask);
  935. p->nr_cpus_allowed = cpumask_weight(new_mask);
  936. }
  937. void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
  938. {
  939. struct rq *rq = task_rq(p);
  940. bool queued, running;
  941. lockdep_assert_held(&p->pi_lock);
  942. queued = task_on_rq_queued(p);
  943. running = task_current(rq, p);
  944. if (queued) {
  945. /*
  946. * Because __kthread_bind() calls this on blocked tasks without
  947. * holding rq->lock.
  948. */
  949. lockdep_assert_held(&rq->lock);
  950. dequeue_task(rq, p, DEQUEUE_SAVE);
  951. }
  952. if (running)
  953. put_prev_task(rq, p);
  954. p->sched_class->set_cpus_allowed(p, new_mask);
  955. if (running)
  956. p->sched_class->set_curr_task(rq);
  957. if (queued)
  958. enqueue_task(rq, p, ENQUEUE_RESTORE);
  959. }
  960. /*
  961. * Change a given task's CPU affinity. Migrate the thread to a
  962. * proper CPU and schedule it away if the CPU it's executing on
  963. * is removed from the allowed bitmask.
  964. *
  965. * NOTE: the caller must have a valid reference to the task, the
  966. * task must not exit() & deallocate itself prematurely. The
  967. * call is not atomic; no spinlocks may be held.
  968. */
  969. static int __set_cpus_allowed_ptr(struct task_struct *p,
  970. const struct cpumask *new_mask, bool check)
  971. {
  972. const struct cpumask *cpu_valid_mask = cpu_active_mask;
  973. unsigned int dest_cpu;
  974. struct rq_flags rf;
  975. struct rq *rq;
  976. int ret = 0;
  977. rq = task_rq_lock(p, &rf);
  978. if (p->flags & PF_KTHREAD) {
  979. /*
  980. * Kernel threads are allowed on online && !active CPUs
  981. */
  982. cpu_valid_mask = cpu_online_mask;
  983. }
  984. /*
  985. * Must re-check here, to close a race against __kthread_bind(),
  986. * sched_setaffinity() is not guaranteed to observe the flag.
  987. */
  988. if (check && (p->flags & PF_NO_SETAFFINITY)) {
  989. ret = -EINVAL;
  990. goto out;
  991. }
  992. if (cpumask_equal(&p->cpus_allowed, new_mask))
  993. goto out;
  994. if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
  995. ret = -EINVAL;
  996. goto out;
  997. }
  998. do_set_cpus_allowed(p, new_mask);
  999. if (p->flags & PF_KTHREAD) {
  1000. /*
  1001. * For kernel threads that do indeed end up on online &&
  1002. * !active we want to ensure they are strict per-cpu threads.
  1003. */
  1004. WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
  1005. !cpumask_intersects(new_mask, cpu_active_mask) &&
  1006. p->nr_cpus_allowed != 1);
  1007. }
  1008. /* Can the task run on the task's current CPU? If so, we're done */
  1009. if (cpumask_test_cpu(task_cpu(p), new_mask))
  1010. goto out;
  1011. dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
  1012. if (task_running(rq, p) || p->state == TASK_WAKING) {
  1013. struct migration_arg arg = { p, dest_cpu };
  1014. /* Need help from migration thread: drop lock and wait. */
  1015. task_rq_unlock(rq, p, &rf);
  1016. stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
  1017. tlb_migrate_finish(p->mm);
  1018. return 0;
  1019. } else if (task_on_rq_queued(p)) {
  1020. /*
  1021. * OK, since we're going to drop the lock immediately
  1022. * afterwards anyway.
  1023. */
  1024. lockdep_unpin_lock(&rq->lock, rf.cookie);
  1025. rq = move_queued_task(rq, p, dest_cpu);
  1026. lockdep_repin_lock(&rq->lock, rf.cookie);
  1027. }
  1028. out:
  1029. task_rq_unlock(rq, p, &rf);
  1030. return ret;
  1031. }
  1032. int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
  1033. {
  1034. return __set_cpus_allowed_ptr(p, new_mask, false);
  1035. }
  1036. EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
  1037. void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
  1038. {
  1039. #ifdef CONFIG_SCHED_DEBUG
  1040. /*
  1041. * We should never call set_task_cpu() on a blocked task,
  1042. * ttwu() will sort out the placement.
  1043. */
  1044. WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
  1045. !p->on_rq);
  1046. /*
  1047. * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
  1048. * because schedstat_wait_{start,end} rebase migrating task's wait_start
  1049. * time relying on p->on_rq.
  1050. */
  1051. WARN_ON_ONCE(p->state == TASK_RUNNING &&
  1052. p->sched_class == &fair_sched_class &&
  1053. (p->on_rq && !task_on_rq_migrating(p)));
  1054. #ifdef CONFIG_LOCKDEP
  1055. /*
  1056. * The caller should hold either p->pi_lock or rq->lock, when changing
  1057. * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
  1058. *
  1059. * sched_move_task() holds both and thus holding either pins the cgroup,
  1060. * see task_group().
  1061. *
  1062. * Furthermore, all task_rq users should acquire both locks, see
  1063. * task_rq_lock().
  1064. */
  1065. WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
  1066. lockdep_is_held(&task_rq(p)->lock)));
  1067. #endif
  1068. #endif
  1069. trace_sched_migrate_task(p, new_cpu);
  1070. if (task_cpu(p) != new_cpu) {
  1071. if (p->sched_class->migrate_task_rq)
  1072. p->sched_class->migrate_task_rq(p);
  1073. p->se.nr_migrations++;
  1074. perf_event_task_migrate(p);
  1075. }
  1076. __set_task_cpu(p, new_cpu);
  1077. }
  1078. static void __migrate_swap_task(struct task_struct *p, int cpu)
  1079. {
  1080. if (task_on_rq_queued(p)) {
  1081. struct rq *src_rq, *dst_rq;
  1082. src_rq = task_rq(p);
  1083. dst_rq = cpu_rq(cpu);
  1084. p->on_rq = TASK_ON_RQ_MIGRATING;
  1085. deactivate_task(src_rq, p, 0);
  1086. set_task_cpu(p, cpu);
  1087. activate_task(dst_rq, p, 0);
  1088. p->on_rq = TASK_ON_RQ_QUEUED;
  1089. check_preempt_curr(dst_rq, p, 0);
  1090. } else {
  1091. /*
  1092. * Task isn't running anymore; make it appear like we migrated
  1093. * it before it went to sleep. This means on wakeup we make the
  1094. * previous cpu our target instead of where it really is.
  1095. */
  1096. p->wake_cpu = cpu;
  1097. }
  1098. }
  1099. struct migration_swap_arg {
  1100. struct task_struct *src_task, *dst_task;
  1101. int src_cpu, dst_cpu;
  1102. };
  1103. static int migrate_swap_stop(void *data)
  1104. {
  1105. struct migration_swap_arg *arg = data;
  1106. struct rq *src_rq, *dst_rq;
  1107. int ret = -EAGAIN;
  1108. if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
  1109. return -EAGAIN;
  1110. src_rq = cpu_rq(arg->src_cpu);
  1111. dst_rq = cpu_rq(arg->dst_cpu);
  1112. double_raw_lock(&arg->src_task->pi_lock,
  1113. &arg->dst_task->pi_lock);
  1114. double_rq_lock(src_rq, dst_rq);
  1115. if (task_cpu(arg->dst_task) != arg->dst_cpu)
  1116. goto unlock;
  1117. if (task_cpu(arg->src_task) != arg->src_cpu)
  1118. goto unlock;
  1119. if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
  1120. goto unlock;
  1121. if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
  1122. goto unlock;
  1123. __migrate_swap_task(arg->src_task, arg->dst_cpu);
  1124. __migrate_swap_task(arg->dst_task, arg->src_cpu);
  1125. ret = 0;
  1126. unlock:
  1127. double_rq_unlock(src_rq, dst_rq);
  1128. raw_spin_unlock(&arg->dst_task->pi_lock);
  1129. raw_spin_unlock(&arg->src_task->pi_lock);
  1130. return ret;
  1131. }
  1132. /*
  1133. * Cross migrate two tasks
  1134. */
  1135. int migrate_swap(struct task_struct *cur, struct task_struct *p)
  1136. {
  1137. struct migration_swap_arg arg;
  1138. int ret = -EINVAL;
  1139. arg = (struct migration_swap_arg){
  1140. .src_task = cur,
  1141. .src_cpu = task_cpu(cur),
  1142. .dst_task = p,
  1143. .dst_cpu = task_cpu(p),
  1144. };
  1145. if (arg.src_cpu == arg.dst_cpu)
  1146. goto out;
  1147. /*
  1148. * These three tests are all lockless; this is OK since all of them
  1149. * will be re-checked with proper locks held further down the line.
  1150. */
  1151. if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
  1152. goto out;
  1153. if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
  1154. goto out;
  1155. if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
  1156. goto out;
  1157. trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
  1158. ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
  1159. out:
  1160. return ret;
  1161. }
  1162. /*
  1163. * wait_task_inactive - wait for a thread to unschedule.
  1164. *
  1165. * If @match_state is nonzero, it's the @p->state value just checked and
  1166. * not expected to change. If it changes, i.e. @p might have woken up,
  1167. * then return zero. When we succeed in waiting for @p to be off its CPU,
  1168. * we return a positive number (its total switch count). If a second call
  1169. * a short while later returns the same number, the caller can be sure that
  1170. * @p has remained unscheduled the whole time.
  1171. *
  1172. * The caller must ensure that the task *will* unschedule sometime soon,
  1173. * else this function might spin for a *long* time. This function can't
  1174. * be called with interrupts off, or it may introduce deadlock with
  1175. * smp_call_function() if an IPI is sent by the same process we are
  1176. * waiting to become inactive.
  1177. */
  1178. unsigned long wait_task_inactive(struct task_struct *p, long match_state)
  1179. {
  1180. int running, queued;
  1181. struct rq_flags rf;
  1182. unsigned long ncsw;
  1183. struct rq *rq;
  1184. for (;;) {
  1185. /*
  1186. * We do the initial early heuristics without holding
  1187. * any task-queue locks at all. We'll only try to get
  1188. * the runqueue lock when things look like they will
  1189. * work out!
  1190. */
  1191. rq = task_rq(p);
  1192. /*
  1193. * If the task is actively running on another CPU
  1194. * still, just relax and busy-wait without holding
  1195. * any locks.
  1196. *
  1197. * NOTE! Since we don't hold any locks, it's not
  1198. * even sure that "rq" stays as the right runqueue!
  1199. * But we don't care, since "task_running()" will
  1200. * return false if the runqueue has changed and p
  1201. * is actually now running somewhere else!
  1202. */
  1203. while (task_running(rq, p)) {
  1204. if (match_state && unlikely(p->state != match_state))
  1205. return 0;
  1206. cpu_relax();
  1207. }
  1208. /*
  1209. * Ok, time to look more closely! We need the rq
  1210. * lock now, to be *sure*. If we're wrong, we'll
  1211. * just go back and repeat.
  1212. */
  1213. rq = task_rq_lock(p, &rf);
  1214. trace_sched_wait_task(p);
  1215. running = task_running(rq, p);
  1216. queued = task_on_rq_queued(p);
  1217. ncsw = 0;
  1218. if (!match_state || p->state == match_state)
  1219. ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
  1220. task_rq_unlock(rq, p, &rf);
  1221. /*
  1222. * If it changed from the expected state, bail out now.
  1223. */
  1224. if (unlikely(!ncsw))
  1225. break;
  1226. /*
  1227. * Was it really running after all now that we
  1228. * checked with the proper locks actually held?
  1229. *
  1230. * Oops. Go back and try again..
  1231. */
  1232. if (unlikely(running)) {
  1233. cpu_relax();
  1234. continue;
  1235. }
  1236. /*
  1237. * It's not enough that it's not actively running,
  1238. * it must be off the runqueue _entirely_, and not
  1239. * preempted!
  1240. *
  1241. * So if it was still runnable (but just not actively
  1242. * running right now), it's preempted, and we should
  1243. * yield - it could be a while.
  1244. */
  1245. if (unlikely(queued)) {
  1246. ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
  1247. set_current_state(TASK_UNINTERRUPTIBLE);
  1248. schedule_hrtimeout(&to, HRTIMER_MODE_REL);
  1249. continue;
  1250. }
  1251. /*
  1252. * Ahh, all good. It wasn't running, and it wasn't
  1253. * runnable, which means that it will never become
  1254. * running in the future either. We're all done!
  1255. */
  1256. break;
  1257. }
  1258. return ncsw;
  1259. }
  1260. /***
  1261. * kick_process - kick a running thread to enter/exit the kernel
  1262. * @p: the to-be-kicked thread
  1263. *
  1264. * Cause a process which is running on another CPU to enter
  1265. * kernel-mode, without any delay. (to get signals handled.)
  1266. *
  1267. * NOTE: this function doesn't have to take the runqueue lock,
  1268. * because all it wants to ensure is that the remote task enters
  1269. * the kernel. If the IPI races and the task has been migrated
  1270. * to another CPU then no harm is done and the purpose has been
  1271. * achieved as well.
  1272. */
  1273. void kick_process(struct task_struct *p)
  1274. {
  1275. int cpu;
  1276. preempt_disable();
  1277. cpu = task_cpu(p);
  1278. if ((cpu != smp_processor_id()) && task_curr(p))
  1279. smp_send_reschedule(cpu);
  1280. preempt_enable();
  1281. }
  1282. EXPORT_SYMBOL_GPL(kick_process);
  1283. /*
  1284. * ->cpus_allowed is protected by both rq->lock and p->pi_lock
  1285. *
  1286. * A few notes on cpu_active vs cpu_online:
  1287. *
  1288. * - cpu_active must be a subset of cpu_online
  1289. *
  1290. * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
  1291. * see __set_cpus_allowed_ptr(). At this point the newly online
  1292. * cpu isn't yet part of the sched domains, and balancing will not
  1293. * see it.
  1294. *
  1295. * - on cpu-down we clear cpu_active() to mask the sched domains and
  1296. * avoid the load balancer to place new tasks on the to be removed
  1297. * cpu. Existing tasks will remain running there and will be taken
  1298. * off.
  1299. *
  1300. * This means that fallback selection must not select !active CPUs.
  1301. * And can assume that any active CPU must be online. Conversely
  1302. * select_task_rq() below may allow selection of !active CPUs in order
  1303. * to satisfy the above rules.
  1304. */
  1305. static int select_fallback_rq(int cpu, struct task_struct *p)
  1306. {
  1307. int nid = cpu_to_node(cpu);
  1308. const struct cpumask *nodemask = NULL;
  1309. enum { cpuset, possible, fail } state = cpuset;
  1310. int dest_cpu;
  1311. /*
  1312. * If the node that the cpu is on has been offlined, cpu_to_node()
  1313. * will return -1. There is no cpu on the node, and we should
  1314. * select the cpu on the other node.
  1315. */
  1316. if (nid != -1) {
  1317. nodemask = cpumask_of_node(nid);
  1318. /* Look for allowed, online CPU in same node. */
  1319. for_each_cpu(dest_cpu, nodemask) {
  1320. if (!cpu_active(dest_cpu))
  1321. continue;
  1322. if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
  1323. return dest_cpu;
  1324. }
  1325. }
  1326. for (;;) {
  1327. /* Any allowed, online CPU? */
  1328. for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
  1329. if (!(p->flags & PF_KTHREAD) && !cpu_active(dest_cpu))
  1330. continue;
  1331. if (!cpu_online(dest_cpu))
  1332. continue;
  1333. goto out;
  1334. }
  1335. /* No more Mr. Nice Guy. */
  1336. switch (state) {
  1337. case cpuset:
  1338. if (IS_ENABLED(CONFIG_CPUSETS)) {
  1339. cpuset_cpus_allowed_fallback(p);
  1340. state = possible;
  1341. break;
  1342. }
  1343. /* fall-through */
  1344. case possible:
  1345. do_set_cpus_allowed(p, cpu_possible_mask);
  1346. state = fail;
  1347. break;
  1348. case fail:
  1349. BUG();
  1350. break;
  1351. }
  1352. }
  1353. out:
  1354. if (state != cpuset) {
  1355. /*
  1356. * Don't tell them about moving exiting tasks or
  1357. * kernel threads (both mm NULL), since they never
  1358. * leave kernel.
  1359. */
  1360. if (p->mm && printk_ratelimit()) {
  1361. printk_deferred("process %d (%s) no longer affine to cpu%d\n",
  1362. task_pid_nr(p), p->comm, cpu);
  1363. }
  1364. }
  1365. return dest_cpu;
  1366. }
  1367. /*
  1368. * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
  1369. */
  1370. static inline
  1371. int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
  1372. {
  1373. lockdep_assert_held(&p->pi_lock);
  1374. if (tsk_nr_cpus_allowed(p) > 1)
  1375. cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
  1376. else
  1377. cpu = cpumask_any(tsk_cpus_allowed(p));
  1378. /*
  1379. * In order not to call set_task_cpu() on a blocking task we need
  1380. * to rely on ttwu() to place the task on a valid ->cpus_allowed
  1381. * cpu.
  1382. *
  1383. * Since this is common to all placement strategies, this lives here.
  1384. *
  1385. * [ this allows ->select_task() to simply return task_cpu(p) and
  1386. * not worry about this generic constraint ]
  1387. */
  1388. if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
  1389. !cpu_online(cpu)))
  1390. cpu = select_fallback_rq(task_cpu(p), p);
  1391. return cpu;
  1392. }
  1393. static void update_avg(u64 *avg, u64 sample)
  1394. {
  1395. s64 diff = sample - *avg;
  1396. *avg += diff >> 3;
  1397. }
  1398. #else
  1399. static inline int __set_cpus_allowed_ptr(struct task_struct *p,
  1400. const struct cpumask *new_mask, bool check)
  1401. {
  1402. return set_cpus_allowed_ptr(p, new_mask);
  1403. }
  1404. #endif /* CONFIG_SMP */
  1405. static void
  1406. ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
  1407. {
  1408. struct rq *rq;
  1409. if (!schedstat_enabled())
  1410. return;
  1411. rq = this_rq();
  1412. #ifdef CONFIG_SMP
  1413. if (cpu == rq->cpu) {
  1414. schedstat_inc(rq->ttwu_local);
  1415. schedstat_inc(p->se.statistics.nr_wakeups_local);
  1416. } else {
  1417. struct sched_domain *sd;
  1418. schedstat_inc(p->se.statistics.nr_wakeups_remote);
  1419. rcu_read_lock();
  1420. for_each_domain(rq->cpu, sd) {
  1421. if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
  1422. schedstat_inc(sd->ttwu_wake_remote);
  1423. break;
  1424. }
  1425. }
  1426. rcu_read_unlock();
  1427. }
  1428. if (wake_flags & WF_MIGRATED)
  1429. schedstat_inc(p->se.statistics.nr_wakeups_migrate);
  1430. #endif /* CONFIG_SMP */
  1431. schedstat_inc(rq->ttwu_count);
  1432. schedstat_inc(p->se.statistics.nr_wakeups);
  1433. if (wake_flags & WF_SYNC)
  1434. schedstat_inc(p->se.statistics.nr_wakeups_sync);
  1435. }
  1436. static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
  1437. {
  1438. activate_task(rq, p, en_flags);
  1439. p->on_rq = TASK_ON_RQ_QUEUED;
  1440. /* if a worker is waking up, notify workqueue */
  1441. if (p->flags & PF_WQ_WORKER)
  1442. wq_worker_waking_up(p, cpu_of(rq));
  1443. }
  1444. /*
  1445. * Mark the task runnable and perform wakeup-preemption.
  1446. */
  1447. static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
  1448. struct pin_cookie cookie)
  1449. {
  1450. check_preempt_curr(rq, p, wake_flags);
  1451. p->state = TASK_RUNNING;
  1452. trace_sched_wakeup(p);
  1453. #ifdef CONFIG_SMP
  1454. if (p->sched_class->task_woken) {
  1455. /*
  1456. * Our task @p is fully woken up and running; so its safe to
  1457. * drop the rq->lock, hereafter rq is only used for statistics.
  1458. */
  1459. lockdep_unpin_lock(&rq->lock, cookie);
  1460. p->sched_class->task_woken(rq, p);
  1461. lockdep_repin_lock(&rq->lock, cookie);
  1462. }
  1463. if (rq->idle_stamp) {
  1464. u64 delta = rq_clock(rq) - rq->idle_stamp;
  1465. u64 max = 2*rq->max_idle_balance_cost;
  1466. update_avg(&rq->avg_idle, delta);
  1467. if (rq->avg_idle > max)
  1468. rq->avg_idle = max;
  1469. rq->idle_stamp = 0;
  1470. }
  1471. #endif
  1472. }
  1473. static void
  1474. ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
  1475. struct pin_cookie cookie)
  1476. {
  1477. int en_flags = ENQUEUE_WAKEUP;
  1478. lockdep_assert_held(&rq->lock);
  1479. #ifdef CONFIG_SMP
  1480. if (p->sched_contributes_to_load)
  1481. rq->nr_uninterruptible--;
  1482. if (wake_flags & WF_MIGRATED)
  1483. en_flags |= ENQUEUE_MIGRATED;
  1484. #endif
  1485. ttwu_activate(rq, p, en_flags);
  1486. ttwu_do_wakeup(rq, p, wake_flags, cookie);
  1487. }
  1488. /*
  1489. * Called in case the task @p isn't fully descheduled from its runqueue,
  1490. * in this case we must do a remote wakeup. Its a 'light' wakeup though,
  1491. * since all we need to do is flip p->state to TASK_RUNNING, since
  1492. * the task is still ->on_rq.
  1493. */
  1494. static int ttwu_remote(struct task_struct *p, int wake_flags)
  1495. {
  1496. struct rq_flags rf;
  1497. struct rq *rq;
  1498. int ret = 0;
  1499. rq = __task_rq_lock(p, &rf);
  1500. if (task_on_rq_queued(p)) {
  1501. /* check_preempt_curr() may use rq clock */
  1502. update_rq_clock(rq);
  1503. ttwu_do_wakeup(rq, p, wake_flags, rf.cookie);
  1504. ret = 1;
  1505. }
  1506. __task_rq_unlock(rq, &rf);
  1507. return ret;
  1508. }
  1509. #ifdef CONFIG_SMP
  1510. void sched_ttwu_pending(void)
  1511. {
  1512. struct rq *rq = this_rq();
  1513. struct llist_node *llist = llist_del_all(&rq->wake_list);
  1514. struct pin_cookie cookie;
  1515. struct task_struct *p;
  1516. unsigned long flags;
  1517. if (!llist)
  1518. return;
  1519. raw_spin_lock_irqsave(&rq->lock, flags);
  1520. cookie = lockdep_pin_lock(&rq->lock);
  1521. while (llist) {
  1522. int wake_flags = 0;
  1523. p = llist_entry(llist, struct task_struct, wake_entry);
  1524. llist = llist_next(llist);
  1525. if (p->sched_remote_wakeup)
  1526. wake_flags = WF_MIGRATED;
  1527. ttwu_do_activate(rq, p, wake_flags, cookie);
  1528. }
  1529. lockdep_unpin_lock(&rq->lock, cookie);
  1530. raw_spin_unlock_irqrestore(&rq->lock, flags);
  1531. }
  1532. void scheduler_ipi(void)
  1533. {
  1534. /*
  1535. * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
  1536. * TIF_NEED_RESCHED remotely (for the first time) will also send
  1537. * this IPI.
  1538. */
  1539. preempt_fold_need_resched();
  1540. if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
  1541. return;
  1542. /*
  1543. * Not all reschedule IPI handlers call irq_enter/irq_exit, since
  1544. * traditionally all their work was done from the interrupt return
  1545. * path. Now that we actually do some work, we need to make sure
  1546. * we do call them.
  1547. *
  1548. * Some archs already do call them, luckily irq_enter/exit nest
  1549. * properly.
  1550. *
  1551. * Arguably we should visit all archs and update all handlers,
  1552. * however a fair share of IPIs are still resched only so this would
  1553. * somewhat pessimize the simple resched case.
  1554. */
  1555. irq_enter();
  1556. sched_ttwu_pending();
  1557. /*
  1558. * Check if someone kicked us for doing the nohz idle load balance.
  1559. */
  1560. if (unlikely(got_nohz_idle_kick())) {
  1561. this_rq()->idle_balance = 1;
  1562. raise_softirq_irqoff(SCHED_SOFTIRQ);
  1563. }
  1564. irq_exit();
  1565. }
  1566. static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
  1567. {
  1568. struct rq *rq = cpu_rq(cpu);
  1569. p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
  1570. if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
  1571. if (!set_nr_if_polling(rq->idle))
  1572. smp_send_reschedule(cpu);
  1573. else
  1574. trace_sched_wake_idle_without_ipi(cpu);
  1575. }
  1576. }
  1577. void wake_up_if_idle(int cpu)
  1578. {
  1579. struct rq *rq = cpu_rq(cpu);
  1580. unsigned long flags;
  1581. rcu_read_lock();
  1582. if (!is_idle_task(rcu_dereference(rq->curr)))
  1583. goto out;
  1584. if (set_nr_if_polling(rq->idle)) {
  1585. trace_sched_wake_idle_without_ipi(cpu);
  1586. } else {
  1587. raw_spin_lock_irqsave(&rq->lock, flags);
  1588. if (is_idle_task(rq->curr))
  1589. smp_send_reschedule(cpu);
  1590. /* Else cpu is not in idle, do nothing here */
  1591. raw_spin_unlock_irqrestore(&rq->lock, flags);
  1592. }
  1593. out:
  1594. rcu_read_unlock();
  1595. }
  1596. bool cpus_share_cache(int this_cpu, int that_cpu)
  1597. {
  1598. return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
  1599. }
  1600. #endif /* CONFIG_SMP */
  1601. static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
  1602. {
  1603. struct rq *rq = cpu_rq(cpu);
  1604. struct pin_cookie cookie;
  1605. #if defined(CONFIG_SMP)
  1606. if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
  1607. sched_clock_cpu(cpu); /* sync clocks x-cpu */
  1608. ttwu_queue_remote(p, cpu, wake_flags);
  1609. return;
  1610. }
  1611. #endif
  1612. raw_spin_lock(&rq->lock);
  1613. cookie = lockdep_pin_lock(&rq->lock);
  1614. ttwu_do_activate(rq, p, wake_flags, cookie);
  1615. lockdep_unpin_lock(&rq->lock, cookie);
  1616. raw_spin_unlock(&rq->lock);
  1617. }
  1618. /*
  1619. * Notes on Program-Order guarantees on SMP systems.
  1620. *
  1621. * MIGRATION
  1622. *
  1623. * The basic program-order guarantee on SMP systems is that when a task [t]
  1624. * migrates, all its activity on its old cpu [c0] happens-before any subsequent
  1625. * execution on its new cpu [c1].
  1626. *
  1627. * For migration (of runnable tasks) this is provided by the following means:
  1628. *
  1629. * A) UNLOCK of the rq(c0)->lock scheduling out task t
  1630. * B) migration for t is required to synchronize *both* rq(c0)->lock and
  1631. * rq(c1)->lock (if not at the same time, then in that order).
  1632. * C) LOCK of the rq(c1)->lock scheduling in task
  1633. *
  1634. * Transitivity guarantees that B happens after A and C after B.
  1635. * Note: we only require RCpc transitivity.
  1636. * Note: the cpu doing B need not be c0 or c1
  1637. *
  1638. * Example:
  1639. *
  1640. * CPU0 CPU1 CPU2
  1641. *
  1642. * LOCK rq(0)->lock
  1643. * sched-out X
  1644. * sched-in Y
  1645. * UNLOCK rq(0)->lock
  1646. *
  1647. * LOCK rq(0)->lock // orders against CPU0
  1648. * dequeue X
  1649. * UNLOCK rq(0)->lock
  1650. *
  1651. * LOCK rq(1)->lock
  1652. * enqueue X
  1653. * UNLOCK rq(1)->lock
  1654. *
  1655. * LOCK rq(1)->lock // orders against CPU2
  1656. * sched-out Z
  1657. * sched-in X
  1658. * UNLOCK rq(1)->lock
  1659. *
  1660. *
  1661. * BLOCKING -- aka. SLEEP + WAKEUP
  1662. *
  1663. * For blocking we (obviously) need to provide the same guarantee as for
  1664. * migration. However the means are completely different as there is no lock
  1665. * chain to provide order. Instead we do:
  1666. *
  1667. * 1) smp_store_release(X->on_cpu, 0)
  1668. * 2) smp_cond_load_acquire(!X->on_cpu)
  1669. *
  1670. * Example:
  1671. *
  1672. * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
  1673. *
  1674. * LOCK rq(0)->lock LOCK X->pi_lock
  1675. * dequeue X
  1676. * sched-out X
  1677. * smp_store_release(X->on_cpu, 0);
  1678. *
  1679. * smp_cond_load_acquire(&X->on_cpu, !VAL);
  1680. * X->state = WAKING
  1681. * set_task_cpu(X,2)
  1682. *
  1683. * LOCK rq(2)->lock
  1684. * enqueue X
  1685. * X->state = RUNNING
  1686. * UNLOCK rq(2)->lock
  1687. *
  1688. * LOCK rq(2)->lock // orders against CPU1
  1689. * sched-out Z
  1690. * sched-in X
  1691. * UNLOCK rq(2)->lock
  1692. *
  1693. * UNLOCK X->pi_lock
  1694. * UNLOCK rq(0)->lock
  1695. *
  1696. *
  1697. * However; for wakeups there is a second guarantee we must provide, namely we
  1698. * must observe the state that lead to our wakeup. That is, not only must our
  1699. * task observe its own prior state, it must also observe the stores prior to
  1700. * its wakeup.
  1701. *
  1702. * This means that any means of doing remote wakeups must order the CPU doing
  1703. * the wakeup against the CPU the task is going to end up running on. This,
  1704. * however, is already required for the regular Program-Order guarantee above,
  1705. * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
  1706. *
  1707. */
  1708. /**
  1709. * try_to_wake_up - wake up a thread
  1710. * @p: the thread to be awakened
  1711. * @state: the mask of task states that can be woken
  1712. * @wake_flags: wake modifier flags (WF_*)
  1713. *
  1714. * Put it on the run-queue if it's not already there. The "current"
  1715. * thread is always on the run-queue (except when the actual
  1716. * re-schedule is in progress), and as such you're allowed to do
  1717. * the simpler "current->state = TASK_RUNNING" to mark yourself
  1718. * runnable without the overhead of this.
  1719. *
  1720. * Return: %true if @p was woken up, %false if it was already running.
  1721. * or @state didn't match @p's state.
  1722. */
  1723. static int
  1724. try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
  1725. {
  1726. unsigned long flags;
  1727. int cpu, success = 0;
  1728. /*
  1729. * If we are going to wake up a thread waiting for CONDITION we
  1730. * need to ensure that CONDITION=1 done by the caller can not be
  1731. * reordered with p->state check below. This pairs with mb() in
  1732. * set_current_state() the waiting thread does.
  1733. */
  1734. smp_mb__before_spinlock();
  1735. raw_spin_lock_irqsave(&p->pi_lock, flags);
  1736. if (!(p->state & state))
  1737. goto out;
  1738. trace_sched_waking(p);
  1739. success = 1; /* we're going to change ->state */
  1740. cpu = task_cpu(p);
  1741. /*
  1742. * Ensure we load p->on_rq _after_ p->state, otherwise it would
  1743. * be possible to, falsely, observe p->on_rq == 0 and get stuck
  1744. * in smp_cond_load_acquire() below.
  1745. *
  1746. * sched_ttwu_pending() try_to_wake_up()
  1747. * [S] p->on_rq = 1; [L] P->state
  1748. * UNLOCK rq->lock -----.
  1749. * \
  1750. * +--- RMB
  1751. * schedule() /
  1752. * LOCK rq->lock -----'
  1753. * UNLOCK rq->lock
  1754. *
  1755. * [task p]
  1756. * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
  1757. *
  1758. * Pairs with the UNLOCK+LOCK on rq->lock from the
  1759. * last wakeup of our task and the schedule that got our task
  1760. * current.
  1761. */
  1762. smp_rmb();
  1763. if (p->on_rq && ttwu_remote(p, wake_flags))
  1764. goto stat;
  1765. #ifdef CONFIG_SMP
  1766. /*
  1767. * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
  1768. * possible to, falsely, observe p->on_cpu == 0.
  1769. *
  1770. * One must be running (->on_cpu == 1) in order to remove oneself
  1771. * from the runqueue.
  1772. *
  1773. * [S] ->on_cpu = 1; [L] ->on_rq
  1774. * UNLOCK rq->lock
  1775. * RMB
  1776. * LOCK rq->lock
  1777. * [S] ->on_rq = 0; [L] ->on_cpu
  1778. *
  1779. * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
  1780. * from the consecutive calls to schedule(); the first switching to our
  1781. * task, the second putting it to sleep.
  1782. */
  1783. smp_rmb();
  1784. /*
  1785. * If the owning (remote) cpu is still in the middle of schedule() with
  1786. * this task as prev, wait until its done referencing the task.
  1787. *
  1788. * Pairs with the smp_store_release() in finish_lock_switch().
  1789. *
  1790. * This ensures that tasks getting woken will be fully ordered against
  1791. * their previous state and preserve Program Order.
  1792. */
  1793. smp_cond_load_acquire(&p->on_cpu, !VAL);
  1794. p->sched_contributes_to_load = !!task_contributes_to_load(p);
  1795. p->state = TASK_WAKING;
  1796. cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
  1797. if (task_cpu(p) != cpu) {
  1798. wake_flags |= WF_MIGRATED;
  1799. set_task_cpu(p, cpu);
  1800. }
  1801. #endif /* CONFIG_SMP */
  1802. ttwu_queue(p, cpu, wake_flags);
  1803. stat:
  1804. ttwu_stat(p, cpu, wake_flags);
  1805. out:
  1806. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  1807. return success;
  1808. }
  1809. /**
  1810. * try_to_wake_up_local - try to wake up a local task with rq lock held
  1811. * @p: the thread to be awakened
  1812. * @cookie: context's cookie for pinning
  1813. *
  1814. * Put @p on the run-queue if it's not already there. The caller must
  1815. * ensure that this_rq() is locked, @p is bound to this_rq() and not
  1816. * the current task.
  1817. */
  1818. static void try_to_wake_up_local(struct task_struct *p, struct pin_cookie cookie)
  1819. {
  1820. struct rq *rq = task_rq(p);
  1821. if (WARN_ON_ONCE(rq != this_rq()) ||
  1822. WARN_ON_ONCE(p == current))
  1823. return;
  1824. lockdep_assert_held(&rq->lock);
  1825. if (!raw_spin_trylock(&p->pi_lock)) {
  1826. /*
  1827. * This is OK, because current is on_cpu, which avoids it being
  1828. * picked for load-balance and preemption/IRQs are still
  1829. * disabled avoiding further scheduler activity on it and we've
  1830. * not yet picked a replacement task.
  1831. */
  1832. lockdep_unpin_lock(&rq->lock, cookie);
  1833. raw_spin_unlock(&rq->lock);
  1834. raw_spin_lock(&p->pi_lock);
  1835. raw_spin_lock(&rq->lock);
  1836. lockdep_repin_lock(&rq->lock, cookie);
  1837. }
  1838. if (!(p->state & TASK_NORMAL))
  1839. goto out;
  1840. trace_sched_waking(p);
  1841. if (!task_on_rq_queued(p))
  1842. ttwu_activate(rq, p, ENQUEUE_WAKEUP);
  1843. ttwu_do_wakeup(rq, p, 0, cookie);
  1844. ttwu_stat(p, smp_processor_id(), 0);
  1845. out:
  1846. raw_spin_unlock(&p->pi_lock);
  1847. }
  1848. /**
  1849. * wake_up_process - Wake up a specific process
  1850. * @p: The process to be woken up.
  1851. *
  1852. * Attempt to wake up the nominated process and move it to the set of runnable
  1853. * processes.
  1854. *
  1855. * Return: 1 if the process was woken up, 0 if it was already running.
  1856. *
  1857. * It may be assumed that this function implies a write memory barrier before
  1858. * changing the task state if and only if any tasks are woken up.
  1859. */
  1860. int wake_up_process(struct task_struct *p)
  1861. {
  1862. return try_to_wake_up(p, TASK_NORMAL, 0);
  1863. }
  1864. EXPORT_SYMBOL(wake_up_process);
  1865. int wake_up_state(struct task_struct *p, unsigned int state)
  1866. {
  1867. return try_to_wake_up(p, state, 0);
  1868. }
  1869. /*
  1870. * This function clears the sched_dl_entity static params.
  1871. */
  1872. void __dl_clear_params(struct task_struct *p)
  1873. {
  1874. struct sched_dl_entity *dl_se = &p->dl;
  1875. dl_se->dl_runtime = 0;
  1876. dl_se->dl_deadline = 0;
  1877. dl_se->dl_period = 0;
  1878. dl_se->flags = 0;
  1879. dl_se->dl_bw = 0;
  1880. dl_se->dl_throttled = 0;
  1881. dl_se->dl_yielded = 0;
  1882. }
  1883. /*
  1884. * Perform scheduler related setup for a newly forked process p.
  1885. * p is forked by current.
  1886. *
  1887. * __sched_fork() is basic setup used by init_idle() too:
  1888. */
  1889. static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
  1890. {
  1891. p->on_rq = 0;
  1892. p->se.on_rq = 0;
  1893. p->se.exec_start = 0;
  1894. p->se.sum_exec_runtime = 0;
  1895. p->se.prev_sum_exec_runtime = 0;
  1896. p->se.nr_migrations = 0;
  1897. p->se.vruntime = 0;
  1898. INIT_LIST_HEAD(&p->se.group_node);
  1899. #ifdef CONFIG_FAIR_GROUP_SCHED
  1900. p->se.cfs_rq = NULL;
  1901. #endif
  1902. #ifdef CONFIG_SCHEDSTATS
  1903. /* Even if schedstat is disabled, there should not be garbage */
  1904. memset(&p->se.statistics, 0, sizeof(p->se.statistics));
  1905. #endif
  1906. RB_CLEAR_NODE(&p->dl.rb_node);
  1907. init_dl_task_timer(&p->dl);
  1908. __dl_clear_params(p);
  1909. INIT_LIST_HEAD(&p->rt.run_list);
  1910. p->rt.timeout = 0;
  1911. p->rt.time_slice = sched_rr_timeslice;
  1912. p->rt.on_rq = 0;
  1913. p->rt.on_list = 0;
  1914. #ifdef CONFIG_PREEMPT_NOTIFIERS
  1915. INIT_HLIST_HEAD(&p->preempt_notifiers);
  1916. #endif
  1917. #ifdef CONFIG_NUMA_BALANCING
  1918. if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
  1919. p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  1920. p->mm->numa_scan_seq = 0;
  1921. }
  1922. if (clone_flags & CLONE_VM)
  1923. p->numa_preferred_nid = current->numa_preferred_nid;
  1924. else
  1925. p->numa_preferred_nid = -1;
  1926. p->node_stamp = 0ULL;
  1927. p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
  1928. p->numa_scan_period = sysctl_numa_balancing_scan_delay;
  1929. p->numa_work.next = &p->numa_work;
  1930. p->numa_faults = NULL;
  1931. p->last_task_numa_placement = 0;
  1932. p->last_sum_exec_runtime = 0;
  1933. p->numa_group = NULL;
  1934. #endif /* CONFIG_NUMA_BALANCING */
  1935. }
  1936. DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
  1937. #ifdef CONFIG_NUMA_BALANCING
  1938. void set_numabalancing_state(bool enabled)
  1939. {
  1940. if (enabled)
  1941. static_branch_enable(&sched_numa_balancing);
  1942. else
  1943. static_branch_disable(&sched_numa_balancing);
  1944. }
  1945. #ifdef CONFIG_PROC_SYSCTL
  1946. int sysctl_numa_balancing(struct ctl_table *table, int write,
  1947. void __user *buffer, size_t *lenp, loff_t *ppos)
  1948. {
  1949. struct ctl_table t;
  1950. int err;
  1951. int state = static_branch_likely(&sched_numa_balancing);
  1952. if (write && !capable(CAP_SYS_ADMIN))
  1953. return -EPERM;
  1954. t = *table;
  1955. t.data = &state;
  1956. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  1957. if (err < 0)
  1958. return err;
  1959. if (write)
  1960. set_numabalancing_state(state);
  1961. return err;
  1962. }
  1963. #endif
  1964. #endif
  1965. #ifdef CONFIG_SCHEDSTATS
  1966. DEFINE_STATIC_KEY_FALSE(sched_schedstats);
  1967. static bool __initdata __sched_schedstats = false;
  1968. static void set_schedstats(bool enabled)
  1969. {
  1970. if (enabled)
  1971. static_branch_enable(&sched_schedstats);
  1972. else
  1973. static_branch_disable(&sched_schedstats);
  1974. }
  1975. void force_schedstat_enabled(void)
  1976. {
  1977. if (!schedstat_enabled()) {
  1978. pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
  1979. static_branch_enable(&sched_schedstats);
  1980. }
  1981. }
  1982. static int __init setup_schedstats(char *str)
  1983. {
  1984. int ret = 0;
  1985. if (!str)
  1986. goto out;
  1987. /*
  1988. * This code is called before jump labels have been set up, so we can't
  1989. * change the static branch directly just yet. Instead set a temporary
  1990. * variable so init_schedstats() can do it later.
  1991. */
  1992. if (!strcmp(str, "enable")) {
  1993. __sched_schedstats = true;
  1994. ret = 1;
  1995. } else if (!strcmp(str, "disable")) {
  1996. __sched_schedstats = false;
  1997. ret = 1;
  1998. }
  1999. out:
  2000. if (!ret)
  2001. pr_warn("Unable to parse schedstats=\n");
  2002. return ret;
  2003. }
  2004. __setup("schedstats=", setup_schedstats);
  2005. static void __init init_schedstats(void)
  2006. {
  2007. set_schedstats(__sched_schedstats);
  2008. }
  2009. #ifdef CONFIG_PROC_SYSCTL
  2010. int sysctl_schedstats(struct ctl_table *table, int write,
  2011. void __user *buffer, size_t *lenp, loff_t *ppos)
  2012. {
  2013. struct ctl_table t;
  2014. int err;
  2015. int state = static_branch_likely(&sched_schedstats);
  2016. if (write && !capable(CAP_SYS_ADMIN))
  2017. return -EPERM;
  2018. t = *table;
  2019. t.data = &state;
  2020. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  2021. if (err < 0)
  2022. return err;
  2023. if (write)
  2024. set_schedstats(state);
  2025. return err;
  2026. }
  2027. #endif /* CONFIG_PROC_SYSCTL */
  2028. #else /* !CONFIG_SCHEDSTATS */
  2029. static inline void init_schedstats(void) {}
  2030. #endif /* CONFIG_SCHEDSTATS */
  2031. /*
  2032. * fork()/clone()-time setup:
  2033. */
  2034. int sched_fork(unsigned long clone_flags, struct task_struct *p)
  2035. {
  2036. unsigned long flags;
  2037. int cpu = get_cpu();
  2038. __sched_fork(clone_flags, p);
  2039. /*
  2040. * We mark the process as NEW here. This guarantees that
  2041. * nobody will actually run it, and a signal or other external
  2042. * event cannot wake it up and insert it on the runqueue either.
  2043. */
  2044. p->state = TASK_NEW;
  2045. /*
  2046. * Make sure we do not leak PI boosting priority to the child.
  2047. */
  2048. p->prio = current->normal_prio;
  2049. /*
  2050. * Revert to default priority/policy on fork if requested.
  2051. */
  2052. if (unlikely(p->sched_reset_on_fork)) {
  2053. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  2054. p->policy = SCHED_NORMAL;
  2055. p->static_prio = NICE_TO_PRIO(0);
  2056. p->rt_priority = 0;
  2057. } else if (PRIO_TO_NICE(p->static_prio) < 0)
  2058. p->static_prio = NICE_TO_PRIO(0);
  2059. p->prio = p->normal_prio = __normal_prio(p);
  2060. set_load_weight(p);
  2061. /*
  2062. * We don't need the reset flag anymore after the fork. It has
  2063. * fulfilled its duty:
  2064. */
  2065. p->sched_reset_on_fork = 0;
  2066. }
  2067. if (dl_prio(p->prio)) {
  2068. put_cpu();
  2069. return -EAGAIN;
  2070. } else if (rt_prio(p->prio)) {
  2071. p->sched_class = &rt_sched_class;
  2072. } else {
  2073. p->sched_class = &fair_sched_class;
  2074. }
  2075. init_entity_runnable_average(&p->se);
  2076. /*
  2077. * The child is not yet in the pid-hash so no cgroup attach races,
  2078. * and the cgroup is pinned to this child due to cgroup_fork()
  2079. * is ran before sched_fork().
  2080. *
  2081. * Silence PROVE_RCU.
  2082. */
  2083. raw_spin_lock_irqsave(&p->pi_lock, flags);
  2084. /*
  2085. * We're setting the cpu for the first time, we don't migrate,
  2086. * so use __set_task_cpu().
  2087. */
  2088. __set_task_cpu(p, cpu);
  2089. if (p->sched_class->task_fork)
  2090. p->sched_class->task_fork(p);
  2091. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  2092. #ifdef CONFIG_SCHED_INFO
  2093. if (likely(sched_info_on()))
  2094. memset(&p->sched_info, 0, sizeof(p->sched_info));
  2095. #endif
  2096. #if defined(CONFIG_SMP)
  2097. p->on_cpu = 0;
  2098. #endif
  2099. init_task_preempt_count(p);
  2100. #ifdef CONFIG_SMP
  2101. plist_node_init(&p->pushable_tasks, MAX_PRIO);
  2102. RB_CLEAR_NODE(&p->pushable_dl_tasks);
  2103. #endif
  2104. put_cpu();
  2105. return 0;
  2106. }
  2107. unsigned long to_ratio(u64 period, u64 runtime)
  2108. {
  2109. if (runtime == RUNTIME_INF)
  2110. return 1ULL << 20;
  2111. /*
  2112. * Doing this here saves a lot of checks in all
  2113. * the calling paths, and returning zero seems
  2114. * safe for them anyway.
  2115. */
  2116. if (period == 0)
  2117. return 0;
  2118. return div64_u64(runtime << 20, period);
  2119. }
  2120. #ifdef CONFIG_SMP
  2121. inline struct dl_bw *dl_bw_of(int i)
  2122. {
  2123. RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
  2124. "sched RCU must be held");
  2125. return &cpu_rq(i)->rd->dl_bw;
  2126. }
  2127. static inline int dl_bw_cpus(int i)
  2128. {
  2129. struct root_domain *rd = cpu_rq(i)->rd;
  2130. int cpus = 0;
  2131. RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held(),
  2132. "sched RCU must be held");
  2133. for_each_cpu_and(i, rd->span, cpu_active_mask)
  2134. cpus++;
  2135. return cpus;
  2136. }
  2137. #else
  2138. inline struct dl_bw *dl_bw_of(int i)
  2139. {
  2140. return &cpu_rq(i)->dl.dl_bw;
  2141. }
  2142. static inline int dl_bw_cpus(int i)
  2143. {
  2144. return 1;
  2145. }
  2146. #endif
  2147. /*
  2148. * We must be sure that accepting a new task (or allowing changing the
  2149. * parameters of an existing one) is consistent with the bandwidth
  2150. * constraints. If yes, this function also accordingly updates the currently
  2151. * allocated bandwidth to reflect the new situation.
  2152. *
  2153. * This function is called while holding p's rq->lock.
  2154. *
  2155. * XXX we should delay bw change until the task's 0-lag point, see
  2156. * __setparam_dl().
  2157. */
  2158. static int dl_overflow(struct task_struct *p, int policy,
  2159. const struct sched_attr *attr)
  2160. {
  2161. struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
  2162. u64 period = attr->sched_period ?: attr->sched_deadline;
  2163. u64 runtime = attr->sched_runtime;
  2164. u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
  2165. int cpus, err = -1;
  2166. /* !deadline task may carry old deadline bandwidth */
  2167. if (new_bw == p->dl.dl_bw && task_has_dl_policy(p))
  2168. return 0;
  2169. /*
  2170. * Either if a task, enters, leave, or stays -deadline but changes
  2171. * its parameters, we may need to update accordingly the total
  2172. * allocated bandwidth of the container.
  2173. */
  2174. raw_spin_lock(&dl_b->lock);
  2175. cpus = dl_bw_cpus(task_cpu(p));
  2176. if (dl_policy(policy) && !task_has_dl_policy(p) &&
  2177. !__dl_overflow(dl_b, cpus, 0, new_bw)) {
  2178. __dl_add(dl_b, new_bw);
  2179. err = 0;
  2180. } else if (dl_policy(policy) && task_has_dl_policy(p) &&
  2181. !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
  2182. __dl_clear(dl_b, p->dl.dl_bw);
  2183. __dl_add(dl_b, new_bw);
  2184. err = 0;
  2185. } else if (!dl_policy(policy) && task_has_dl_policy(p)) {
  2186. __dl_clear(dl_b, p->dl.dl_bw);
  2187. err = 0;
  2188. }
  2189. raw_spin_unlock(&dl_b->lock);
  2190. return err;
  2191. }
  2192. extern void init_dl_bw(struct dl_bw *dl_b);
  2193. /*
  2194. * wake_up_new_task - wake up a newly created task for the first time.
  2195. *
  2196. * This function will do some initial scheduler statistics housekeeping
  2197. * that must be done for every newly created context, then puts the task
  2198. * on the runqueue and wakes it.
  2199. */
  2200. void wake_up_new_task(struct task_struct *p)
  2201. {
  2202. struct rq_flags rf;
  2203. struct rq *rq;
  2204. raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
  2205. p->state = TASK_RUNNING;
  2206. #ifdef CONFIG_SMP
  2207. /*
  2208. * Fork balancing, do it here and not earlier because:
  2209. * - cpus_allowed can change in the fork path
  2210. * - any previously selected cpu might disappear through hotplug
  2211. *
  2212. * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
  2213. * as we're not fully set-up yet.
  2214. */
  2215. __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
  2216. #endif
  2217. rq = __task_rq_lock(p, &rf);
  2218. post_init_entity_util_avg(&p->se);
  2219. activate_task(rq, p, 0);
  2220. p->on_rq = TASK_ON_RQ_QUEUED;
  2221. trace_sched_wakeup_new(p);
  2222. check_preempt_curr(rq, p, WF_FORK);
  2223. #ifdef CONFIG_SMP
  2224. if (p->sched_class->task_woken) {
  2225. /*
  2226. * Nothing relies on rq->lock after this, so its fine to
  2227. * drop it.
  2228. */
  2229. lockdep_unpin_lock(&rq->lock, rf.cookie);
  2230. p->sched_class->task_woken(rq, p);
  2231. lockdep_repin_lock(&rq->lock, rf.cookie);
  2232. }
  2233. #endif
  2234. task_rq_unlock(rq, p, &rf);
  2235. }
  2236. #ifdef CONFIG_PREEMPT_NOTIFIERS
  2237. static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
  2238. void preempt_notifier_inc(void)
  2239. {
  2240. static_key_slow_inc(&preempt_notifier_key);
  2241. }
  2242. EXPORT_SYMBOL_GPL(preempt_notifier_inc);
  2243. void preempt_notifier_dec(void)
  2244. {
  2245. static_key_slow_dec(&preempt_notifier_key);
  2246. }
  2247. EXPORT_SYMBOL_GPL(preempt_notifier_dec);
  2248. /**
  2249. * preempt_notifier_register - tell me when current is being preempted & rescheduled
  2250. * @notifier: notifier struct to register
  2251. */
  2252. void preempt_notifier_register(struct preempt_notifier *notifier)
  2253. {
  2254. if (!static_key_false(&preempt_notifier_key))
  2255. WARN(1, "registering preempt_notifier while notifiers disabled\n");
  2256. hlist_add_head(&notifier->link, &current->preempt_notifiers);
  2257. }
  2258. EXPORT_SYMBOL_GPL(preempt_notifier_register);
  2259. /**
  2260. * preempt_notifier_unregister - no longer interested in preemption notifications
  2261. * @notifier: notifier struct to unregister
  2262. *
  2263. * This is *not* safe to call from within a preemption notifier.
  2264. */
  2265. void preempt_notifier_unregister(struct preempt_notifier *notifier)
  2266. {
  2267. hlist_del(&notifier->link);
  2268. }
  2269. EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
  2270. static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
  2271. {
  2272. struct preempt_notifier *notifier;
  2273. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  2274. notifier->ops->sched_in(notifier, raw_smp_processor_id());
  2275. }
  2276. static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  2277. {
  2278. if (static_key_false(&preempt_notifier_key))
  2279. __fire_sched_in_preempt_notifiers(curr);
  2280. }
  2281. static void
  2282. __fire_sched_out_preempt_notifiers(struct task_struct *curr,
  2283. struct task_struct *next)
  2284. {
  2285. struct preempt_notifier *notifier;
  2286. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  2287. notifier->ops->sched_out(notifier, next);
  2288. }
  2289. static __always_inline void
  2290. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  2291. struct task_struct *next)
  2292. {
  2293. if (static_key_false(&preempt_notifier_key))
  2294. __fire_sched_out_preempt_notifiers(curr, next);
  2295. }
  2296. #else /* !CONFIG_PREEMPT_NOTIFIERS */
  2297. static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  2298. {
  2299. }
  2300. static inline void
  2301. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  2302. struct task_struct *next)
  2303. {
  2304. }
  2305. #endif /* CONFIG_PREEMPT_NOTIFIERS */
  2306. /**
  2307. * prepare_task_switch - prepare to switch tasks
  2308. * @rq: the runqueue preparing to switch
  2309. * @prev: the current task that is being switched out
  2310. * @next: the task we are going to switch to.
  2311. *
  2312. * This is called with the rq lock held and interrupts off. It must
  2313. * be paired with a subsequent finish_task_switch after the context
  2314. * switch.
  2315. *
  2316. * prepare_task_switch sets up locking and calls architecture specific
  2317. * hooks.
  2318. */
  2319. static inline void
  2320. prepare_task_switch(struct rq *rq, struct task_struct *prev,
  2321. struct task_struct *next)
  2322. {
  2323. sched_info_switch(rq, prev, next);
  2324. perf_event_task_sched_out(prev, next);
  2325. fire_sched_out_preempt_notifiers(prev, next);
  2326. prepare_lock_switch(rq, next);
  2327. prepare_arch_switch(next);
  2328. }
  2329. /**
  2330. * finish_task_switch - clean up after a task-switch
  2331. * @prev: the thread we just switched away from.
  2332. *
  2333. * finish_task_switch must be called after the context switch, paired
  2334. * with a prepare_task_switch call before the context switch.
  2335. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  2336. * and do any other architecture-specific cleanup actions.
  2337. *
  2338. * Note that we may have delayed dropping an mm in context_switch(). If
  2339. * so, we finish that here outside of the runqueue lock. (Doing it
  2340. * with the lock held can cause deadlocks; see schedule() for
  2341. * details.)
  2342. *
  2343. * The context switch have flipped the stack from under us and restored the
  2344. * local variables which were saved when this task called schedule() in the
  2345. * past. prev == current is still correct but we need to recalculate this_rq
  2346. * because prev may have moved to another CPU.
  2347. */
  2348. static struct rq *finish_task_switch(struct task_struct *prev)
  2349. __releases(rq->lock)
  2350. {
  2351. struct rq *rq = this_rq();
  2352. struct mm_struct *mm = rq->prev_mm;
  2353. long prev_state;
  2354. /*
  2355. * The previous task will have left us with a preempt_count of 2
  2356. * because it left us after:
  2357. *
  2358. * schedule()
  2359. * preempt_disable(); // 1
  2360. * __schedule()
  2361. * raw_spin_lock_irq(&rq->lock) // 2
  2362. *
  2363. * Also, see FORK_PREEMPT_COUNT.
  2364. */
  2365. if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
  2366. "corrupted preempt_count: %s/%d/0x%x\n",
  2367. current->comm, current->pid, preempt_count()))
  2368. preempt_count_set(FORK_PREEMPT_COUNT);
  2369. rq->prev_mm = NULL;
  2370. /*
  2371. * A task struct has one reference for the use as "current".
  2372. * If a task dies, then it sets TASK_DEAD in tsk->state and calls
  2373. * schedule one last time. The schedule call will never return, and
  2374. * the scheduled task must drop that reference.
  2375. *
  2376. * We must observe prev->state before clearing prev->on_cpu (in
  2377. * finish_lock_switch), otherwise a concurrent wakeup can get prev
  2378. * running on another CPU and we could rave with its RUNNING -> DEAD
  2379. * transition, resulting in a double drop.
  2380. */
  2381. prev_state = prev->state;
  2382. vtime_task_switch(prev);
  2383. perf_event_task_sched_in(prev, current);
  2384. finish_lock_switch(rq, prev);
  2385. finish_arch_post_lock_switch();
  2386. fire_sched_in_preempt_notifiers(current);
  2387. if (mm)
  2388. mmdrop(mm);
  2389. if (unlikely(prev_state == TASK_DEAD)) {
  2390. if (prev->sched_class->task_dead)
  2391. prev->sched_class->task_dead(prev);
  2392. /*
  2393. * Remove function-return probe instances associated with this
  2394. * task and put them back on the free list.
  2395. */
  2396. kprobe_flush_task(prev);
  2397. put_task_struct(prev);
  2398. }
  2399. tick_nohz_task_switch();
  2400. return rq;
  2401. }
  2402. #ifdef CONFIG_SMP
  2403. /* rq->lock is NOT held, but preemption is disabled */
  2404. static void __balance_callback(struct rq *rq)
  2405. {
  2406. struct callback_head *head, *next;
  2407. void (*func)(struct rq *rq);
  2408. unsigned long flags;
  2409. raw_spin_lock_irqsave(&rq->lock, flags);
  2410. head = rq->balance_callback;
  2411. rq->balance_callback = NULL;
  2412. while (head) {
  2413. func = (void (*)(struct rq *))head->func;
  2414. next = head->next;
  2415. head->next = NULL;
  2416. head = next;
  2417. func(rq);
  2418. }
  2419. raw_spin_unlock_irqrestore(&rq->lock, flags);
  2420. }
  2421. static inline void balance_callback(struct rq *rq)
  2422. {
  2423. if (unlikely(rq->balance_callback))
  2424. __balance_callback(rq);
  2425. }
  2426. #else
  2427. static inline void balance_callback(struct rq *rq)
  2428. {
  2429. }
  2430. #endif
  2431. /**
  2432. * schedule_tail - first thing a freshly forked thread must call.
  2433. * @prev: the thread we just switched away from.
  2434. */
  2435. asmlinkage __visible void schedule_tail(struct task_struct *prev)
  2436. __releases(rq->lock)
  2437. {
  2438. struct rq *rq;
  2439. /*
  2440. * New tasks start with FORK_PREEMPT_COUNT, see there and
  2441. * finish_task_switch() for details.
  2442. *
  2443. * finish_task_switch() will drop rq->lock() and lower preempt_count
  2444. * and the preempt_enable() will end up enabling preemption (on
  2445. * PREEMPT_COUNT kernels).
  2446. */
  2447. rq = finish_task_switch(prev);
  2448. balance_callback(rq);
  2449. preempt_enable();
  2450. if (current->set_child_tid)
  2451. put_user(task_pid_vnr(current), current->set_child_tid);
  2452. }
  2453. /*
  2454. * context_switch - switch to the new MM and the new thread's register state.
  2455. */
  2456. static __always_inline struct rq *
  2457. context_switch(struct rq *rq, struct task_struct *prev,
  2458. struct task_struct *next, struct pin_cookie cookie)
  2459. {
  2460. struct mm_struct *mm, *oldmm;
  2461. prepare_task_switch(rq, prev, next);
  2462. mm = next->mm;
  2463. oldmm = prev->active_mm;
  2464. /*
  2465. * For paravirt, this is coupled with an exit in switch_to to
  2466. * combine the page table reload and the switch backend into
  2467. * one hypercall.
  2468. */
  2469. arch_start_context_switch(prev);
  2470. if (!mm) {
  2471. next->active_mm = oldmm;
  2472. atomic_inc(&oldmm->mm_count);
  2473. enter_lazy_tlb(oldmm, next);
  2474. } else
  2475. switch_mm_irqs_off(oldmm, mm, next);
  2476. if (!prev->mm) {
  2477. prev->active_mm = NULL;
  2478. rq->prev_mm = oldmm;
  2479. }
  2480. /*
  2481. * Since the runqueue lock will be released by the next
  2482. * task (which is an invalid locking op but in the case
  2483. * of the scheduler it's an obvious special-case), so we
  2484. * do an early lockdep release here:
  2485. */
  2486. lockdep_unpin_lock(&rq->lock, cookie);
  2487. spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
  2488. /* Here we just switch the register state and the stack. */
  2489. switch_to(prev, next, prev);
  2490. barrier();
  2491. return finish_task_switch(prev);
  2492. }
  2493. /*
  2494. * nr_running and nr_context_switches:
  2495. *
  2496. * externally visible scheduler statistics: current number of runnable
  2497. * threads, total number of context switches performed since bootup.
  2498. */
  2499. unsigned long nr_running(void)
  2500. {
  2501. unsigned long i, sum = 0;
  2502. for_each_online_cpu(i)
  2503. sum += cpu_rq(i)->nr_running;
  2504. return sum;
  2505. }
  2506. /*
  2507. * Check if only the current task is running on the cpu.
  2508. *
  2509. * Caution: this function does not check that the caller has disabled
  2510. * preemption, thus the result might have a time-of-check-to-time-of-use
  2511. * race. The caller is responsible to use it correctly, for example:
  2512. *
  2513. * - from a non-preemptable section (of course)
  2514. *
  2515. * - from a thread that is bound to a single CPU
  2516. *
  2517. * - in a loop with very short iterations (e.g. a polling loop)
  2518. */
  2519. bool single_task_running(void)
  2520. {
  2521. return raw_rq()->nr_running == 1;
  2522. }
  2523. EXPORT_SYMBOL(single_task_running);
  2524. unsigned long long nr_context_switches(void)
  2525. {
  2526. int i;
  2527. unsigned long long sum = 0;
  2528. for_each_possible_cpu(i)
  2529. sum += cpu_rq(i)->nr_switches;
  2530. return sum;
  2531. }
  2532. unsigned long nr_iowait(void)
  2533. {
  2534. unsigned long i, sum = 0;
  2535. for_each_possible_cpu(i)
  2536. sum += atomic_read(&cpu_rq(i)->nr_iowait);
  2537. return sum;
  2538. }
  2539. unsigned long nr_iowait_cpu(int cpu)
  2540. {
  2541. struct rq *this = cpu_rq(cpu);
  2542. return atomic_read(&this->nr_iowait);
  2543. }
  2544. void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
  2545. {
  2546. struct rq *rq = this_rq();
  2547. *nr_waiters = atomic_read(&rq->nr_iowait);
  2548. *load = rq->load.weight;
  2549. }
  2550. #ifdef CONFIG_SMP
  2551. /*
  2552. * sched_exec - execve() is a valuable balancing opportunity, because at
  2553. * this point the task has the smallest effective memory and cache footprint.
  2554. */
  2555. void sched_exec(void)
  2556. {
  2557. struct task_struct *p = current;
  2558. unsigned long flags;
  2559. int dest_cpu;
  2560. raw_spin_lock_irqsave(&p->pi_lock, flags);
  2561. dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
  2562. if (dest_cpu == smp_processor_id())
  2563. goto unlock;
  2564. if (likely(cpu_active(dest_cpu))) {
  2565. struct migration_arg arg = { p, dest_cpu };
  2566. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  2567. stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
  2568. return;
  2569. }
  2570. unlock:
  2571. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  2572. }
  2573. #endif
  2574. DEFINE_PER_CPU(struct kernel_stat, kstat);
  2575. DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
  2576. EXPORT_PER_CPU_SYMBOL(kstat);
  2577. EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
  2578. /*
  2579. * The function fair_sched_class.update_curr accesses the struct curr
  2580. * and its field curr->exec_start; when called from task_sched_runtime(),
  2581. * we observe a high rate of cache misses in practice.
  2582. * Prefetching this data results in improved performance.
  2583. */
  2584. static inline void prefetch_curr_exec_start(struct task_struct *p)
  2585. {
  2586. #ifdef CONFIG_FAIR_GROUP_SCHED
  2587. struct sched_entity *curr = (&p->se)->cfs_rq->curr;
  2588. #else
  2589. struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
  2590. #endif
  2591. prefetch(curr);
  2592. prefetch(&curr->exec_start);
  2593. }
  2594. /*
  2595. * Return accounted runtime for the task.
  2596. * In case the task is currently running, return the runtime plus current's
  2597. * pending runtime that have not been accounted yet.
  2598. */
  2599. unsigned long long task_sched_runtime(struct task_struct *p)
  2600. {
  2601. struct rq_flags rf;
  2602. struct rq *rq;
  2603. u64 ns;
  2604. #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
  2605. /*
  2606. * 64-bit doesn't need locks to atomically read a 64bit value.
  2607. * So we have a optimization chance when the task's delta_exec is 0.
  2608. * Reading ->on_cpu is racy, but this is ok.
  2609. *
  2610. * If we race with it leaving cpu, we'll take a lock. So we're correct.
  2611. * If we race with it entering cpu, unaccounted time is 0. This is
  2612. * indistinguishable from the read occurring a few cycles earlier.
  2613. * If we see ->on_cpu without ->on_rq, the task is leaving, and has
  2614. * been accounted, so we're correct here as well.
  2615. */
  2616. if (!p->on_cpu || !task_on_rq_queued(p))
  2617. return p->se.sum_exec_runtime;
  2618. #endif
  2619. rq = task_rq_lock(p, &rf);
  2620. /*
  2621. * Must be ->curr _and_ ->on_rq. If dequeued, we would
  2622. * project cycles that may never be accounted to this
  2623. * thread, breaking clock_gettime().
  2624. */
  2625. if (task_current(rq, p) && task_on_rq_queued(p)) {
  2626. prefetch_curr_exec_start(p);
  2627. update_rq_clock(rq);
  2628. p->sched_class->update_curr(rq);
  2629. }
  2630. ns = p->se.sum_exec_runtime;
  2631. task_rq_unlock(rq, p, &rf);
  2632. return ns;
  2633. }
  2634. /*
  2635. * This function gets called by the timer code, with HZ frequency.
  2636. * We call it with interrupts disabled.
  2637. */
  2638. void scheduler_tick(void)
  2639. {
  2640. int cpu = smp_processor_id();
  2641. struct rq *rq = cpu_rq(cpu);
  2642. struct task_struct *curr = rq->curr;
  2643. sched_clock_tick();
  2644. raw_spin_lock(&rq->lock);
  2645. update_rq_clock(rq);
  2646. curr->sched_class->task_tick(rq, curr, 0);
  2647. cpu_load_update_active(rq);
  2648. calc_global_load_tick(rq);
  2649. raw_spin_unlock(&rq->lock);
  2650. perf_event_task_tick();
  2651. #ifdef CONFIG_SMP
  2652. rq->idle_balance = idle_cpu(cpu);
  2653. trigger_load_balance(rq);
  2654. #endif
  2655. rq_last_tick_reset(rq);
  2656. }
  2657. #ifdef CONFIG_NO_HZ_FULL
  2658. /**
  2659. * scheduler_tick_max_deferment
  2660. *
  2661. * Keep at least one tick per second when a single
  2662. * active task is running because the scheduler doesn't
  2663. * yet completely support full dynticks environment.
  2664. *
  2665. * This makes sure that uptime, CFS vruntime, load
  2666. * balancing, etc... continue to move forward, even
  2667. * with a very low granularity.
  2668. *
  2669. * Return: Maximum deferment in nanoseconds.
  2670. */
  2671. u64 scheduler_tick_max_deferment(void)
  2672. {
  2673. struct rq *rq = this_rq();
  2674. unsigned long next, now = READ_ONCE(jiffies);
  2675. next = rq->last_sched_tick + HZ;
  2676. if (time_before_eq(next, now))
  2677. return 0;
  2678. return jiffies_to_nsecs(next - now);
  2679. }
  2680. #endif
  2681. #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
  2682. defined(CONFIG_PREEMPT_TRACER))
  2683. /*
  2684. * If the value passed in is equal to the current preempt count
  2685. * then we just disabled preemption. Start timing the latency.
  2686. */
  2687. static inline void preempt_latency_start(int val)
  2688. {
  2689. if (preempt_count() == val) {
  2690. unsigned long ip = get_lock_parent_ip();
  2691. #ifdef CONFIG_DEBUG_PREEMPT
  2692. current->preempt_disable_ip = ip;
  2693. #endif
  2694. trace_preempt_off(CALLER_ADDR0, ip);
  2695. }
  2696. }
  2697. void preempt_count_add(int val)
  2698. {
  2699. #ifdef CONFIG_DEBUG_PREEMPT
  2700. /*
  2701. * Underflow?
  2702. */
  2703. if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
  2704. return;
  2705. #endif
  2706. __preempt_count_add(val);
  2707. #ifdef CONFIG_DEBUG_PREEMPT
  2708. /*
  2709. * Spinlock count overflowing soon?
  2710. */
  2711. DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
  2712. PREEMPT_MASK - 10);
  2713. #endif
  2714. preempt_latency_start(val);
  2715. }
  2716. EXPORT_SYMBOL(preempt_count_add);
  2717. NOKPROBE_SYMBOL(preempt_count_add);
  2718. /*
  2719. * If the value passed in equals to the current preempt count
  2720. * then we just enabled preemption. Stop timing the latency.
  2721. */
  2722. static inline void preempt_latency_stop(int val)
  2723. {
  2724. if (preempt_count() == val)
  2725. trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
  2726. }
  2727. void preempt_count_sub(int val)
  2728. {
  2729. #ifdef CONFIG_DEBUG_PREEMPT
  2730. /*
  2731. * Underflow?
  2732. */
  2733. if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
  2734. return;
  2735. /*
  2736. * Is the spinlock portion underflowing?
  2737. */
  2738. if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
  2739. !(preempt_count() & PREEMPT_MASK)))
  2740. return;
  2741. #endif
  2742. preempt_latency_stop(val);
  2743. __preempt_count_sub(val);
  2744. }
  2745. EXPORT_SYMBOL(preempt_count_sub);
  2746. NOKPROBE_SYMBOL(preempt_count_sub);
  2747. #else
  2748. static inline void preempt_latency_start(int val) { }
  2749. static inline void preempt_latency_stop(int val) { }
  2750. #endif
  2751. /*
  2752. * Print scheduling while atomic bug:
  2753. */
  2754. static noinline void __schedule_bug(struct task_struct *prev)
  2755. {
  2756. /* Save this before calling printk(), since that will clobber it */
  2757. unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
  2758. if (oops_in_progress)
  2759. return;
  2760. printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
  2761. prev->comm, prev->pid, preempt_count());
  2762. debug_show_held_locks(prev);
  2763. print_modules();
  2764. if (irqs_disabled())
  2765. print_irqtrace_events(prev);
  2766. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
  2767. && in_atomic_preempt_off()) {
  2768. pr_err("Preemption disabled at:");
  2769. print_ip_sym(preempt_disable_ip);
  2770. pr_cont("\n");
  2771. }
  2772. if (panic_on_warn)
  2773. panic("scheduling while atomic\n");
  2774. dump_stack();
  2775. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  2776. }
  2777. /*
  2778. * Various schedule()-time debugging checks and statistics:
  2779. */
  2780. static inline void schedule_debug(struct task_struct *prev)
  2781. {
  2782. #ifdef CONFIG_SCHED_STACK_END_CHECK
  2783. if (task_stack_end_corrupted(prev))
  2784. panic("corrupted stack end detected inside scheduler\n");
  2785. #endif
  2786. if (unlikely(in_atomic_preempt_off())) {
  2787. __schedule_bug(prev);
  2788. preempt_count_set(PREEMPT_DISABLED);
  2789. }
  2790. rcu_sleep_check();
  2791. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  2792. schedstat_inc(this_rq()->sched_count);
  2793. }
  2794. /*
  2795. * Pick up the highest-prio task:
  2796. */
  2797. static inline struct task_struct *
  2798. pick_next_task(struct rq *rq, struct task_struct *prev, struct pin_cookie cookie)
  2799. {
  2800. const struct sched_class *class = &fair_sched_class;
  2801. struct task_struct *p;
  2802. /*
  2803. * Optimization: we know that if all tasks are in
  2804. * the fair class we can call that function directly:
  2805. */
  2806. if (likely(prev->sched_class == class &&
  2807. rq->nr_running == rq->cfs.h_nr_running)) {
  2808. p = fair_sched_class.pick_next_task(rq, prev, cookie);
  2809. if (unlikely(p == RETRY_TASK))
  2810. goto again;
  2811. /* assumes fair_sched_class->next == idle_sched_class */
  2812. if (unlikely(!p))
  2813. p = idle_sched_class.pick_next_task(rq, prev, cookie);
  2814. return p;
  2815. }
  2816. again:
  2817. for_each_class(class) {
  2818. p = class->pick_next_task(rq, prev, cookie);
  2819. if (p) {
  2820. if (unlikely(p == RETRY_TASK))
  2821. goto again;
  2822. return p;
  2823. }
  2824. }
  2825. BUG(); /* the idle class will always have a runnable task */
  2826. }
  2827. /*
  2828. * __schedule() is the main scheduler function.
  2829. *
  2830. * The main means of driving the scheduler and thus entering this function are:
  2831. *
  2832. * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
  2833. *
  2834. * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
  2835. * paths. For example, see arch/x86/entry_64.S.
  2836. *
  2837. * To drive preemption between tasks, the scheduler sets the flag in timer
  2838. * interrupt handler scheduler_tick().
  2839. *
  2840. * 3. Wakeups don't really cause entry into schedule(). They add a
  2841. * task to the run-queue and that's it.
  2842. *
  2843. * Now, if the new task added to the run-queue preempts the current
  2844. * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
  2845. * called on the nearest possible occasion:
  2846. *
  2847. * - If the kernel is preemptible (CONFIG_PREEMPT=y):
  2848. *
  2849. * - in syscall or exception context, at the next outmost
  2850. * preempt_enable(). (this might be as soon as the wake_up()'s
  2851. * spin_unlock()!)
  2852. *
  2853. * - in IRQ context, return from interrupt-handler to
  2854. * preemptible context
  2855. *
  2856. * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
  2857. * then at the next:
  2858. *
  2859. * - cond_resched() call
  2860. * - explicit schedule() call
  2861. * - return from syscall or exception to user-space
  2862. * - return from interrupt-handler to user-space
  2863. *
  2864. * WARNING: must be called with preemption disabled!
  2865. */
  2866. static void __sched notrace __schedule(bool preempt)
  2867. {
  2868. struct task_struct *prev, *next;
  2869. unsigned long *switch_count;
  2870. struct pin_cookie cookie;
  2871. struct rq *rq;
  2872. int cpu;
  2873. cpu = smp_processor_id();
  2874. rq = cpu_rq(cpu);
  2875. prev = rq->curr;
  2876. schedule_debug(prev);
  2877. if (sched_feat(HRTICK))
  2878. hrtick_clear(rq);
  2879. local_irq_disable();
  2880. rcu_note_context_switch();
  2881. /*
  2882. * Make sure that signal_pending_state()->signal_pending() below
  2883. * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
  2884. * done by the caller to avoid the race with signal_wake_up().
  2885. */
  2886. smp_mb__before_spinlock();
  2887. raw_spin_lock(&rq->lock);
  2888. cookie = lockdep_pin_lock(&rq->lock);
  2889. rq->clock_skip_update <<= 1; /* promote REQ to ACT */
  2890. switch_count = &prev->nivcsw;
  2891. if (!preempt && prev->state) {
  2892. if (unlikely(signal_pending_state(prev->state, prev))) {
  2893. prev->state = TASK_RUNNING;
  2894. } else {
  2895. deactivate_task(rq, prev, DEQUEUE_SLEEP);
  2896. prev->on_rq = 0;
  2897. /*
  2898. * If a worker went to sleep, notify and ask workqueue
  2899. * whether it wants to wake up a task to maintain
  2900. * concurrency.
  2901. */
  2902. if (prev->flags & PF_WQ_WORKER) {
  2903. struct task_struct *to_wakeup;
  2904. to_wakeup = wq_worker_sleeping(prev);
  2905. if (to_wakeup)
  2906. try_to_wake_up_local(to_wakeup, cookie);
  2907. }
  2908. }
  2909. switch_count = &prev->nvcsw;
  2910. }
  2911. if (task_on_rq_queued(prev))
  2912. update_rq_clock(rq);
  2913. next = pick_next_task(rq, prev, cookie);
  2914. clear_tsk_need_resched(prev);
  2915. clear_preempt_need_resched();
  2916. rq->clock_skip_update = 0;
  2917. if (likely(prev != next)) {
  2918. rq->nr_switches++;
  2919. rq->curr = next;
  2920. ++*switch_count;
  2921. trace_sched_switch(preempt, prev, next);
  2922. rq = context_switch(rq, prev, next, cookie); /* unlocks the rq */
  2923. } else {
  2924. lockdep_unpin_lock(&rq->lock, cookie);
  2925. raw_spin_unlock_irq(&rq->lock);
  2926. }
  2927. balance_callback(rq);
  2928. }
  2929. STACK_FRAME_NON_STANDARD(__schedule); /* switch_to() */
  2930. void __noreturn do_task_dead(void)
  2931. {
  2932. /*
  2933. * The setting of TASK_RUNNING by try_to_wake_up() may be delayed
  2934. * when the following two conditions become true.
  2935. * - There is race condition of mmap_sem (It is acquired by
  2936. * exit_mm()), and
  2937. * - SMI occurs before setting TASK_RUNINNG.
  2938. * (or hypervisor of virtual machine switches to other guest)
  2939. * As a result, we may become TASK_RUNNING after becoming TASK_DEAD
  2940. *
  2941. * To avoid it, we have to wait for releasing tsk->pi_lock which
  2942. * is held by try_to_wake_up()
  2943. */
  2944. smp_mb();
  2945. raw_spin_unlock_wait(&current->pi_lock);
  2946. /* causes final put_task_struct in finish_task_switch(). */
  2947. __set_current_state(TASK_DEAD);
  2948. current->flags |= PF_NOFREEZE; /* tell freezer to ignore us */
  2949. __schedule(false);
  2950. BUG();
  2951. /* Avoid "noreturn function does return". */
  2952. for (;;)
  2953. cpu_relax(); /* For when BUG is null */
  2954. }
  2955. static inline void sched_submit_work(struct task_struct *tsk)
  2956. {
  2957. if (!tsk->state || tsk_is_pi_blocked(tsk))
  2958. return;
  2959. /*
  2960. * If we are going to sleep and we have plugged IO queued,
  2961. * make sure to submit it to avoid deadlocks.
  2962. */
  2963. if (blk_needs_flush_plug(tsk))
  2964. blk_schedule_flush_plug(tsk);
  2965. }
  2966. asmlinkage __visible void __sched schedule(void)
  2967. {
  2968. struct task_struct *tsk = current;
  2969. sched_submit_work(tsk);
  2970. do {
  2971. preempt_disable();
  2972. __schedule(false);
  2973. sched_preempt_enable_no_resched();
  2974. } while (need_resched());
  2975. }
  2976. EXPORT_SYMBOL(schedule);
  2977. #ifdef CONFIG_CONTEXT_TRACKING
  2978. asmlinkage __visible void __sched schedule_user(void)
  2979. {
  2980. /*
  2981. * If we come here after a random call to set_need_resched(),
  2982. * or we have been woken up remotely but the IPI has not yet arrived,
  2983. * we haven't yet exited the RCU idle mode. Do it here manually until
  2984. * we find a better solution.
  2985. *
  2986. * NB: There are buggy callers of this function. Ideally we
  2987. * should warn if prev_state != CONTEXT_USER, but that will trigger
  2988. * too frequently to make sense yet.
  2989. */
  2990. enum ctx_state prev_state = exception_enter();
  2991. schedule();
  2992. exception_exit(prev_state);
  2993. }
  2994. #endif
  2995. /**
  2996. * schedule_preempt_disabled - called with preemption disabled
  2997. *
  2998. * Returns with preemption disabled. Note: preempt_count must be 1
  2999. */
  3000. void __sched schedule_preempt_disabled(void)
  3001. {
  3002. sched_preempt_enable_no_resched();
  3003. schedule();
  3004. preempt_disable();
  3005. }
  3006. static void __sched notrace preempt_schedule_common(void)
  3007. {
  3008. do {
  3009. /*
  3010. * Because the function tracer can trace preempt_count_sub()
  3011. * and it also uses preempt_enable/disable_notrace(), if
  3012. * NEED_RESCHED is set, the preempt_enable_notrace() called
  3013. * by the function tracer will call this function again and
  3014. * cause infinite recursion.
  3015. *
  3016. * Preemption must be disabled here before the function
  3017. * tracer can trace. Break up preempt_disable() into two
  3018. * calls. One to disable preemption without fear of being
  3019. * traced. The other to still record the preemption latency,
  3020. * which can also be traced by the function tracer.
  3021. */
  3022. preempt_disable_notrace();
  3023. preempt_latency_start(1);
  3024. __schedule(true);
  3025. preempt_latency_stop(1);
  3026. preempt_enable_no_resched_notrace();
  3027. /*
  3028. * Check again in case we missed a preemption opportunity
  3029. * between schedule and now.
  3030. */
  3031. } while (need_resched());
  3032. }
  3033. #ifdef CONFIG_PREEMPT
  3034. /*
  3035. * this is the entry point to schedule() from in-kernel preemption
  3036. * off of preempt_enable. Kernel preemptions off return from interrupt
  3037. * occur there and call schedule directly.
  3038. */
  3039. asmlinkage __visible void __sched notrace preempt_schedule(void)
  3040. {
  3041. /*
  3042. * If there is a non-zero preempt_count or interrupts are disabled,
  3043. * we do not want to preempt the current task. Just return..
  3044. */
  3045. if (likely(!preemptible()))
  3046. return;
  3047. preempt_schedule_common();
  3048. }
  3049. NOKPROBE_SYMBOL(preempt_schedule);
  3050. EXPORT_SYMBOL(preempt_schedule);
  3051. /**
  3052. * preempt_schedule_notrace - preempt_schedule called by tracing
  3053. *
  3054. * The tracing infrastructure uses preempt_enable_notrace to prevent
  3055. * recursion and tracing preempt enabling caused by the tracing
  3056. * infrastructure itself. But as tracing can happen in areas coming
  3057. * from userspace or just about to enter userspace, a preempt enable
  3058. * can occur before user_exit() is called. This will cause the scheduler
  3059. * to be called when the system is still in usermode.
  3060. *
  3061. * To prevent this, the preempt_enable_notrace will use this function
  3062. * instead of preempt_schedule() to exit user context if needed before
  3063. * calling the scheduler.
  3064. */
  3065. asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
  3066. {
  3067. enum ctx_state prev_ctx;
  3068. if (likely(!preemptible()))
  3069. return;
  3070. do {
  3071. /*
  3072. * Because the function tracer can trace preempt_count_sub()
  3073. * and it also uses preempt_enable/disable_notrace(), if
  3074. * NEED_RESCHED is set, the preempt_enable_notrace() called
  3075. * by the function tracer will call this function again and
  3076. * cause infinite recursion.
  3077. *
  3078. * Preemption must be disabled here before the function
  3079. * tracer can trace. Break up preempt_disable() into two
  3080. * calls. One to disable preemption without fear of being
  3081. * traced. The other to still record the preemption latency,
  3082. * which can also be traced by the function tracer.
  3083. */
  3084. preempt_disable_notrace();
  3085. preempt_latency_start(1);
  3086. /*
  3087. * Needs preempt disabled in case user_exit() is traced
  3088. * and the tracer calls preempt_enable_notrace() causing
  3089. * an infinite recursion.
  3090. */
  3091. prev_ctx = exception_enter();
  3092. __schedule(true);
  3093. exception_exit(prev_ctx);
  3094. preempt_latency_stop(1);
  3095. preempt_enable_no_resched_notrace();
  3096. } while (need_resched());
  3097. }
  3098. EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
  3099. #endif /* CONFIG_PREEMPT */
  3100. /*
  3101. * this is the entry point to schedule() from kernel preemption
  3102. * off of irq context.
  3103. * Note, that this is called and return with irqs disabled. This will
  3104. * protect us against recursive calling from irq.
  3105. */
  3106. asmlinkage __visible void __sched preempt_schedule_irq(void)
  3107. {
  3108. enum ctx_state prev_state;
  3109. /* Catch callers which need to be fixed */
  3110. BUG_ON(preempt_count() || !irqs_disabled());
  3111. prev_state = exception_enter();
  3112. do {
  3113. preempt_disable();
  3114. local_irq_enable();
  3115. __schedule(true);
  3116. local_irq_disable();
  3117. sched_preempt_enable_no_resched();
  3118. } while (need_resched());
  3119. exception_exit(prev_state);
  3120. }
  3121. int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
  3122. void *key)
  3123. {
  3124. return try_to_wake_up(curr->private, mode, wake_flags);
  3125. }
  3126. EXPORT_SYMBOL(default_wake_function);
  3127. #ifdef CONFIG_RT_MUTEXES
  3128. /*
  3129. * rt_mutex_setprio - set the current priority of a task
  3130. * @p: task
  3131. * @prio: prio value (kernel-internal form)
  3132. *
  3133. * This function changes the 'effective' priority of a task. It does
  3134. * not touch ->normal_prio like __setscheduler().
  3135. *
  3136. * Used by the rt_mutex code to implement priority inheritance
  3137. * logic. Call site only calls if the priority of the task changed.
  3138. */
  3139. void rt_mutex_setprio(struct task_struct *p, int prio)
  3140. {
  3141. int oldprio, queued, running, queue_flag = DEQUEUE_SAVE | DEQUEUE_MOVE;
  3142. const struct sched_class *prev_class;
  3143. struct rq_flags rf;
  3144. struct rq *rq;
  3145. BUG_ON(prio > MAX_PRIO);
  3146. rq = __task_rq_lock(p, &rf);
  3147. /*
  3148. * Idle task boosting is a nono in general. There is one
  3149. * exception, when PREEMPT_RT and NOHZ is active:
  3150. *
  3151. * The idle task calls get_next_timer_interrupt() and holds
  3152. * the timer wheel base->lock on the CPU and another CPU wants
  3153. * to access the timer (probably to cancel it). We can safely
  3154. * ignore the boosting request, as the idle CPU runs this code
  3155. * with interrupts disabled and will complete the lock
  3156. * protected section without being interrupted. So there is no
  3157. * real need to boost.
  3158. */
  3159. if (unlikely(p == rq->idle)) {
  3160. WARN_ON(p != rq->curr);
  3161. WARN_ON(p->pi_blocked_on);
  3162. goto out_unlock;
  3163. }
  3164. trace_sched_pi_setprio(p, prio);
  3165. oldprio = p->prio;
  3166. if (oldprio == prio)
  3167. queue_flag &= ~DEQUEUE_MOVE;
  3168. prev_class = p->sched_class;
  3169. queued = task_on_rq_queued(p);
  3170. running = task_current(rq, p);
  3171. if (queued)
  3172. dequeue_task(rq, p, queue_flag);
  3173. if (running)
  3174. put_prev_task(rq, p);
  3175. /*
  3176. * Boosting condition are:
  3177. * 1. -rt task is running and holds mutex A
  3178. * --> -dl task blocks on mutex A
  3179. *
  3180. * 2. -dl task is running and holds mutex A
  3181. * --> -dl task blocks on mutex A and could preempt the
  3182. * running task
  3183. */
  3184. if (dl_prio(prio)) {
  3185. struct task_struct *pi_task = rt_mutex_get_top_task(p);
  3186. if (!dl_prio(p->normal_prio) ||
  3187. (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
  3188. p->dl.dl_boosted = 1;
  3189. queue_flag |= ENQUEUE_REPLENISH;
  3190. } else
  3191. p->dl.dl_boosted = 0;
  3192. p->sched_class = &dl_sched_class;
  3193. } else if (rt_prio(prio)) {
  3194. if (dl_prio(oldprio))
  3195. p->dl.dl_boosted = 0;
  3196. if (oldprio < prio)
  3197. queue_flag |= ENQUEUE_HEAD;
  3198. p->sched_class = &rt_sched_class;
  3199. } else {
  3200. if (dl_prio(oldprio))
  3201. p->dl.dl_boosted = 0;
  3202. if (rt_prio(oldprio))
  3203. p->rt.timeout = 0;
  3204. p->sched_class = &fair_sched_class;
  3205. }
  3206. p->prio = prio;
  3207. if (running)
  3208. p->sched_class->set_curr_task(rq);
  3209. if (queued)
  3210. enqueue_task(rq, p, queue_flag);
  3211. check_class_changed(rq, p, prev_class, oldprio);
  3212. out_unlock:
  3213. preempt_disable(); /* avoid rq from going away on us */
  3214. __task_rq_unlock(rq, &rf);
  3215. balance_callback(rq);
  3216. preempt_enable();
  3217. }
  3218. #endif
  3219. void set_user_nice(struct task_struct *p, long nice)
  3220. {
  3221. int old_prio, delta, queued;
  3222. struct rq_flags rf;
  3223. struct rq *rq;
  3224. if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
  3225. return;
  3226. /*
  3227. * We have to be careful, if called from sys_setpriority(),
  3228. * the task might be in the middle of scheduling on another CPU.
  3229. */
  3230. rq = task_rq_lock(p, &rf);
  3231. /*
  3232. * The RT priorities are set via sched_setscheduler(), but we still
  3233. * allow the 'normal' nice value to be set - but as expected
  3234. * it wont have any effect on scheduling until the task is
  3235. * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
  3236. */
  3237. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  3238. p->static_prio = NICE_TO_PRIO(nice);
  3239. goto out_unlock;
  3240. }
  3241. queued = task_on_rq_queued(p);
  3242. if (queued)
  3243. dequeue_task(rq, p, DEQUEUE_SAVE);
  3244. p->static_prio = NICE_TO_PRIO(nice);
  3245. set_load_weight(p);
  3246. old_prio = p->prio;
  3247. p->prio = effective_prio(p);
  3248. delta = p->prio - old_prio;
  3249. if (queued) {
  3250. enqueue_task(rq, p, ENQUEUE_RESTORE);
  3251. /*
  3252. * If the task increased its priority or is running and
  3253. * lowered its priority, then reschedule its CPU:
  3254. */
  3255. if (delta < 0 || (delta > 0 && task_running(rq, p)))
  3256. resched_curr(rq);
  3257. }
  3258. out_unlock:
  3259. task_rq_unlock(rq, p, &rf);
  3260. }
  3261. EXPORT_SYMBOL(set_user_nice);
  3262. /*
  3263. * can_nice - check if a task can reduce its nice value
  3264. * @p: task
  3265. * @nice: nice value
  3266. */
  3267. int can_nice(const struct task_struct *p, const int nice)
  3268. {
  3269. /* convert nice value [19,-20] to rlimit style value [1,40] */
  3270. int nice_rlim = nice_to_rlimit(nice);
  3271. return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
  3272. capable(CAP_SYS_NICE));
  3273. }
  3274. #ifdef __ARCH_WANT_SYS_NICE
  3275. /*
  3276. * sys_nice - change the priority of the current process.
  3277. * @increment: priority increment
  3278. *
  3279. * sys_setpriority is a more generic, but much slower function that
  3280. * does similar things.
  3281. */
  3282. SYSCALL_DEFINE1(nice, int, increment)
  3283. {
  3284. long nice, retval;
  3285. /*
  3286. * Setpriority might change our priority at the same moment.
  3287. * We don't have to worry. Conceptually one call occurs first
  3288. * and we have a single winner.
  3289. */
  3290. increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
  3291. nice = task_nice(current) + increment;
  3292. nice = clamp_val(nice, MIN_NICE, MAX_NICE);
  3293. if (increment < 0 && !can_nice(current, nice))
  3294. return -EPERM;
  3295. retval = security_task_setnice(current, nice);
  3296. if (retval)
  3297. return retval;
  3298. set_user_nice(current, nice);
  3299. return 0;
  3300. }
  3301. #endif
  3302. /**
  3303. * task_prio - return the priority value of a given task.
  3304. * @p: the task in question.
  3305. *
  3306. * Return: The priority value as seen by users in /proc.
  3307. * RT tasks are offset by -200. Normal tasks are centered
  3308. * around 0, value goes from -16 to +15.
  3309. */
  3310. int task_prio(const struct task_struct *p)
  3311. {
  3312. return p->prio - MAX_RT_PRIO;
  3313. }
  3314. /**
  3315. * idle_cpu - is a given cpu idle currently?
  3316. * @cpu: the processor in question.
  3317. *
  3318. * Return: 1 if the CPU is currently idle. 0 otherwise.
  3319. */
  3320. int idle_cpu(int cpu)
  3321. {
  3322. struct rq *rq = cpu_rq(cpu);
  3323. if (rq->curr != rq->idle)
  3324. return 0;
  3325. if (rq->nr_running)
  3326. return 0;
  3327. #ifdef CONFIG_SMP
  3328. if (!llist_empty(&rq->wake_list))
  3329. return 0;
  3330. #endif
  3331. return 1;
  3332. }
  3333. /**
  3334. * idle_task - return the idle task for a given cpu.
  3335. * @cpu: the processor in question.
  3336. *
  3337. * Return: The idle task for the cpu @cpu.
  3338. */
  3339. struct task_struct *idle_task(int cpu)
  3340. {
  3341. return cpu_rq(cpu)->idle;
  3342. }
  3343. /**
  3344. * find_process_by_pid - find a process with a matching PID value.
  3345. * @pid: the pid in question.
  3346. *
  3347. * The task of @pid, if found. %NULL otherwise.
  3348. */
  3349. static struct task_struct *find_process_by_pid(pid_t pid)
  3350. {
  3351. return pid ? find_task_by_vpid(pid) : current;
  3352. }
  3353. /*
  3354. * This function initializes the sched_dl_entity of a newly becoming
  3355. * SCHED_DEADLINE task.
  3356. *
  3357. * Only the static values are considered here, the actual runtime and the
  3358. * absolute deadline will be properly calculated when the task is enqueued
  3359. * for the first time with its new policy.
  3360. */
  3361. static void
  3362. __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
  3363. {
  3364. struct sched_dl_entity *dl_se = &p->dl;
  3365. dl_se->dl_runtime = attr->sched_runtime;
  3366. dl_se->dl_deadline = attr->sched_deadline;
  3367. dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
  3368. dl_se->flags = attr->sched_flags;
  3369. dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
  3370. /*
  3371. * Changing the parameters of a task is 'tricky' and we're not doing
  3372. * the correct thing -- also see task_dead_dl() and switched_from_dl().
  3373. *
  3374. * What we SHOULD do is delay the bandwidth release until the 0-lag
  3375. * point. This would include retaining the task_struct until that time
  3376. * and change dl_overflow() to not immediately decrement the current
  3377. * amount.
  3378. *
  3379. * Instead we retain the current runtime/deadline and let the new
  3380. * parameters take effect after the current reservation period lapses.
  3381. * This is safe (albeit pessimistic) because the 0-lag point is always
  3382. * before the current scheduling deadline.
  3383. *
  3384. * We can still have temporary overloads because we do not delay the
  3385. * change in bandwidth until that time; so admission control is
  3386. * not on the safe side. It does however guarantee tasks will never
  3387. * consume more than promised.
  3388. */
  3389. }
  3390. /*
  3391. * sched_setparam() passes in -1 for its policy, to let the functions
  3392. * it calls know not to change it.
  3393. */
  3394. #define SETPARAM_POLICY -1
  3395. static void __setscheduler_params(struct task_struct *p,
  3396. const struct sched_attr *attr)
  3397. {
  3398. int policy = attr->sched_policy;
  3399. if (policy == SETPARAM_POLICY)
  3400. policy = p->policy;
  3401. p->policy = policy;
  3402. if (dl_policy(policy))
  3403. __setparam_dl(p, attr);
  3404. else if (fair_policy(policy))
  3405. p->static_prio = NICE_TO_PRIO(attr->sched_nice);
  3406. /*
  3407. * __sched_setscheduler() ensures attr->sched_priority == 0 when
  3408. * !rt_policy. Always setting this ensures that things like
  3409. * getparam()/getattr() don't report silly values for !rt tasks.
  3410. */
  3411. p->rt_priority = attr->sched_priority;
  3412. p->normal_prio = normal_prio(p);
  3413. set_load_weight(p);
  3414. }
  3415. /* Actually do priority change: must hold pi & rq lock. */
  3416. static void __setscheduler(struct rq *rq, struct task_struct *p,
  3417. const struct sched_attr *attr, bool keep_boost)
  3418. {
  3419. __setscheduler_params(p, attr);
  3420. /*
  3421. * Keep a potential priority boosting if called from
  3422. * sched_setscheduler().
  3423. */
  3424. if (keep_boost)
  3425. p->prio = rt_mutex_get_effective_prio(p, normal_prio(p));
  3426. else
  3427. p->prio = normal_prio(p);
  3428. if (dl_prio(p->prio))
  3429. p->sched_class = &dl_sched_class;
  3430. else if (rt_prio(p->prio))
  3431. p->sched_class = &rt_sched_class;
  3432. else
  3433. p->sched_class = &fair_sched_class;
  3434. }
  3435. static void
  3436. __getparam_dl(struct task_struct *p, struct sched_attr *attr)
  3437. {
  3438. struct sched_dl_entity *dl_se = &p->dl;
  3439. attr->sched_priority = p->rt_priority;
  3440. attr->sched_runtime = dl_se->dl_runtime;
  3441. attr->sched_deadline = dl_se->dl_deadline;
  3442. attr->sched_period = dl_se->dl_period;
  3443. attr->sched_flags = dl_se->flags;
  3444. }
  3445. /*
  3446. * This function validates the new parameters of a -deadline task.
  3447. * We ask for the deadline not being zero, and greater or equal
  3448. * than the runtime, as well as the period of being zero or
  3449. * greater than deadline. Furthermore, we have to be sure that
  3450. * user parameters are above the internal resolution of 1us (we
  3451. * check sched_runtime only since it is always the smaller one) and
  3452. * below 2^63 ns (we have to check both sched_deadline and
  3453. * sched_period, as the latter can be zero).
  3454. */
  3455. static bool
  3456. __checkparam_dl(const struct sched_attr *attr)
  3457. {
  3458. /* deadline != 0 */
  3459. if (attr->sched_deadline == 0)
  3460. return false;
  3461. /*
  3462. * Since we truncate DL_SCALE bits, make sure we're at least
  3463. * that big.
  3464. */
  3465. if (attr->sched_runtime < (1ULL << DL_SCALE))
  3466. return false;
  3467. /*
  3468. * Since we use the MSB for wrap-around and sign issues, make
  3469. * sure it's not set (mind that period can be equal to zero).
  3470. */
  3471. if (attr->sched_deadline & (1ULL << 63) ||
  3472. attr->sched_period & (1ULL << 63))
  3473. return false;
  3474. /* runtime <= deadline <= period (if period != 0) */
  3475. if ((attr->sched_period != 0 &&
  3476. attr->sched_period < attr->sched_deadline) ||
  3477. attr->sched_deadline < attr->sched_runtime)
  3478. return false;
  3479. return true;
  3480. }
  3481. /*
  3482. * check the target process has a UID that matches the current process's
  3483. */
  3484. static bool check_same_owner(struct task_struct *p)
  3485. {
  3486. const struct cred *cred = current_cred(), *pcred;
  3487. bool match;
  3488. rcu_read_lock();
  3489. pcred = __task_cred(p);
  3490. match = (uid_eq(cred->euid, pcred->euid) ||
  3491. uid_eq(cred->euid, pcred->uid));
  3492. rcu_read_unlock();
  3493. return match;
  3494. }
  3495. static bool dl_param_changed(struct task_struct *p,
  3496. const struct sched_attr *attr)
  3497. {
  3498. struct sched_dl_entity *dl_se = &p->dl;
  3499. if (dl_se->dl_runtime != attr->sched_runtime ||
  3500. dl_se->dl_deadline != attr->sched_deadline ||
  3501. dl_se->dl_period != attr->sched_period ||
  3502. dl_se->flags != attr->sched_flags)
  3503. return true;
  3504. return false;
  3505. }
  3506. static int __sched_setscheduler(struct task_struct *p,
  3507. const struct sched_attr *attr,
  3508. bool user, bool pi)
  3509. {
  3510. int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
  3511. MAX_RT_PRIO - 1 - attr->sched_priority;
  3512. int retval, oldprio, oldpolicy = -1, queued, running;
  3513. int new_effective_prio, policy = attr->sched_policy;
  3514. const struct sched_class *prev_class;
  3515. struct rq_flags rf;
  3516. int reset_on_fork;
  3517. int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
  3518. struct rq *rq;
  3519. /* may grab non-irq protected spin_locks */
  3520. BUG_ON(in_interrupt());
  3521. recheck:
  3522. /* double check policy once rq lock held */
  3523. if (policy < 0) {
  3524. reset_on_fork = p->sched_reset_on_fork;
  3525. policy = oldpolicy = p->policy;
  3526. } else {
  3527. reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
  3528. if (!valid_policy(policy))
  3529. return -EINVAL;
  3530. }
  3531. if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
  3532. return -EINVAL;
  3533. /*
  3534. * Valid priorities for SCHED_FIFO and SCHED_RR are
  3535. * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
  3536. * SCHED_BATCH and SCHED_IDLE is 0.
  3537. */
  3538. if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
  3539. (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
  3540. return -EINVAL;
  3541. if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
  3542. (rt_policy(policy) != (attr->sched_priority != 0)))
  3543. return -EINVAL;
  3544. /*
  3545. * Allow unprivileged RT tasks to decrease priority:
  3546. */
  3547. if (user && !capable(CAP_SYS_NICE)) {
  3548. if (fair_policy(policy)) {
  3549. if (attr->sched_nice < task_nice(p) &&
  3550. !can_nice(p, attr->sched_nice))
  3551. return -EPERM;
  3552. }
  3553. if (rt_policy(policy)) {
  3554. unsigned long rlim_rtprio =
  3555. task_rlimit(p, RLIMIT_RTPRIO);
  3556. /* can't set/change the rt policy */
  3557. if (policy != p->policy && !rlim_rtprio)
  3558. return -EPERM;
  3559. /* can't increase priority */
  3560. if (attr->sched_priority > p->rt_priority &&
  3561. attr->sched_priority > rlim_rtprio)
  3562. return -EPERM;
  3563. }
  3564. /*
  3565. * Can't set/change SCHED_DEADLINE policy at all for now
  3566. * (safest behavior); in the future we would like to allow
  3567. * unprivileged DL tasks to increase their relative deadline
  3568. * or reduce their runtime (both ways reducing utilization)
  3569. */
  3570. if (dl_policy(policy))
  3571. return -EPERM;
  3572. /*
  3573. * Treat SCHED_IDLE as nice 20. Only allow a switch to
  3574. * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
  3575. */
  3576. if (idle_policy(p->policy) && !idle_policy(policy)) {
  3577. if (!can_nice(p, task_nice(p)))
  3578. return -EPERM;
  3579. }
  3580. /* can't change other user's priorities */
  3581. if (!check_same_owner(p))
  3582. return -EPERM;
  3583. /* Normal users shall not reset the sched_reset_on_fork flag */
  3584. if (p->sched_reset_on_fork && !reset_on_fork)
  3585. return -EPERM;
  3586. }
  3587. if (user) {
  3588. retval = security_task_setscheduler(p);
  3589. if (retval)
  3590. return retval;
  3591. }
  3592. /*
  3593. * make sure no PI-waiters arrive (or leave) while we are
  3594. * changing the priority of the task:
  3595. *
  3596. * To be able to change p->policy safely, the appropriate
  3597. * runqueue lock must be held.
  3598. */
  3599. rq = task_rq_lock(p, &rf);
  3600. /*
  3601. * Changing the policy of the stop threads its a very bad idea
  3602. */
  3603. if (p == rq->stop) {
  3604. task_rq_unlock(rq, p, &rf);
  3605. return -EINVAL;
  3606. }
  3607. /*
  3608. * If not changing anything there's no need to proceed further,
  3609. * but store a possible modification of reset_on_fork.
  3610. */
  3611. if (unlikely(policy == p->policy)) {
  3612. if (fair_policy(policy) && attr->sched_nice != task_nice(p))
  3613. goto change;
  3614. if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
  3615. goto change;
  3616. if (dl_policy(policy) && dl_param_changed(p, attr))
  3617. goto change;
  3618. p->sched_reset_on_fork = reset_on_fork;
  3619. task_rq_unlock(rq, p, &rf);
  3620. return 0;
  3621. }
  3622. change:
  3623. if (user) {
  3624. #ifdef CONFIG_RT_GROUP_SCHED
  3625. /*
  3626. * Do not allow realtime tasks into groups that have no runtime
  3627. * assigned.
  3628. */
  3629. if (rt_bandwidth_enabled() && rt_policy(policy) &&
  3630. task_group(p)->rt_bandwidth.rt_runtime == 0 &&
  3631. !task_group_is_autogroup(task_group(p))) {
  3632. task_rq_unlock(rq, p, &rf);
  3633. return -EPERM;
  3634. }
  3635. #endif
  3636. #ifdef CONFIG_SMP
  3637. if (dl_bandwidth_enabled() && dl_policy(policy)) {
  3638. cpumask_t *span = rq->rd->span;
  3639. /*
  3640. * Don't allow tasks with an affinity mask smaller than
  3641. * the entire root_domain to become SCHED_DEADLINE. We
  3642. * will also fail if there's no bandwidth available.
  3643. */
  3644. if (!cpumask_subset(span, &p->cpus_allowed) ||
  3645. rq->rd->dl_bw.bw == 0) {
  3646. task_rq_unlock(rq, p, &rf);
  3647. return -EPERM;
  3648. }
  3649. }
  3650. #endif
  3651. }
  3652. /* recheck policy now with rq lock held */
  3653. if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
  3654. policy = oldpolicy = -1;
  3655. task_rq_unlock(rq, p, &rf);
  3656. goto recheck;
  3657. }
  3658. /*
  3659. * If setscheduling to SCHED_DEADLINE (or changing the parameters
  3660. * of a SCHED_DEADLINE task) we need to check if enough bandwidth
  3661. * is available.
  3662. */
  3663. if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
  3664. task_rq_unlock(rq, p, &rf);
  3665. return -EBUSY;
  3666. }
  3667. p->sched_reset_on_fork = reset_on_fork;
  3668. oldprio = p->prio;
  3669. if (pi) {
  3670. /*
  3671. * Take priority boosted tasks into account. If the new
  3672. * effective priority is unchanged, we just store the new
  3673. * normal parameters and do not touch the scheduler class and
  3674. * the runqueue. This will be done when the task deboost
  3675. * itself.
  3676. */
  3677. new_effective_prio = rt_mutex_get_effective_prio(p, newprio);
  3678. if (new_effective_prio == oldprio)
  3679. queue_flags &= ~DEQUEUE_MOVE;
  3680. }
  3681. queued = task_on_rq_queued(p);
  3682. running = task_current(rq, p);
  3683. if (queued)
  3684. dequeue_task(rq, p, queue_flags);
  3685. if (running)
  3686. put_prev_task(rq, p);
  3687. prev_class = p->sched_class;
  3688. __setscheduler(rq, p, attr, pi);
  3689. if (running)
  3690. p->sched_class->set_curr_task(rq);
  3691. if (queued) {
  3692. /*
  3693. * We enqueue to tail when the priority of a task is
  3694. * increased (user space view).
  3695. */
  3696. if (oldprio < p->prio)
  3697. queue_flags |= ENQUEUE_HEAD;
  3698. enqueue_task(rq, p, queue_flags);
  3699. }
  3700. check_class_changed(rq, p, prev_class, oldprio);
  3701. preempt_disable(); /* avoid rq from going away on us */
  3702. task_rq_unlock(rq, p, &rf);
  3703. if (pi)
  3704. rt_mutex_adjust_pi(p);
  3705. /*
  3706. * Run balance callbacks after we've adjusted the PI chain.
  3707. */
  3708. balance_callback(rq);
  3709. preempt_enable();
  3710. return 0;
  3711. }
  3712. static int _sched_setscheduler(struct task_struct *p, int policy,
  3713. const struct sched_param *param, bool check)
  3714. {
  3715. struct sched_attr attr = {
  3716. .sched_policy = policy,
  3717. .sched_priority = param->sched_priority,
  3718. .sched_nice = PRIO_TO_NICE(p->static_prio),
  3719. };
  3720. /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
  3721. if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
  3722. attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
  3723. policy &= ~SCHED_RESET_ON_FORK;
  3724. attr.sched_policy = policy;
  3725. }
  3726. return __sched_setscheduler(p, &attr, check, true);
  3727. }
  3728. /**
  3729. * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
  3730. * @p: the task in question.
  3731. * @policy: new policy.
  3732. * @param: structure containing the new RT priority.
  3733. *
  3734. * Return: 0 on success. An error code otherwise.
  3735. *
  3736. * NOTE that the task may be already dead.
  3737. */
  3738. int sched_setscheduler(struct task_struct *p, int policy,
  3739. const struct sched_param *param)
  3740. {
  3741. return _sched_setscheduler(p, policy, param, true);
  3742. }
  3743. EXPORT_SYMBOL_GPL(sched_setscheduler);
  3744. int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
  3745. {
  3746. return __sched_setscheduler(p, attr, true, true);
  3747. }
  3748. EXPORT_SYMBOL_GPL(sched_setattr);
  3749. /**
  3750. * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
  3751. * @p: the task in question.
  3752. * @policy: new policy.
  3753. * @param: structure containing the new RT priority.
  3754. *
  3755. * Just like sched_setscheduler, only don't bother checking if the
  3756. * current context has permission. For example, this is needed in
  3757. * stop_machine(): we create temporary high priority worker threads,
  3758. * but our caller might not have that capability.
  3759. *
  3760. * Return: 0 on success. An error code otherwise.
  3761. */
  3762. int sched_setscheduler_nocheck(struct task_struct *p, int policy,
  3763. const struct sched_param *param)
  3764. {
  3765. return _sched_setscheduler(p, policy, param, false);
  3766. }
  3767. EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
  3768. static int
  3769. do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
  3770. {
  3771. struct sched_param lparam;
  3772. struct task_struct *p;
  3773. int retval;
  3774. if (!param || pid < 0)
  3775. return -EINVAL;
  3776. if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
  3777. return -EFAULT;
  3778. rcu_read_lock();
  3779. retval = -ESRCH;
  3780. p = find_process_by_pid(pid);
  3781. if (p != NULL)
  3782. retval = sched_setscheduler(p, policy, &lparam);
  3783. rcu_read_unlock();
  3784. return retval;
  3785. }
  3786. /*
  3787. * Mimics kernel/events/core.c perf_copy_attr().
  3788. */
  3789. static int sched_copy_attr(struct sched_attr __user *uattr,
  3790. struct sched_attr *attr)
  3791. {
  3792. u32 size;
  3793. int ret;
  3794. if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
  3795. return -EFAULT;
  3796. /*
  3797. * zero the full structure, so that a short copy will be nice.
  3798. */
  3799. memset(attr, 0, sizeof(*attr));
  3800. ret = get_user(size, &uattr->size);
  3801. if (ret)
  3802. return ret;
  3803. if (size > PAGE_SIZE) /* silly large */
  3804. goto err_size;
  3805. if (!size) /* abi compat */
  3806. size = SCHED_ATTR_SIZE_VER0;
  3807. if (size < SCHED_ATTR_SIZE_VER0)
  3808. goto err_size;
  3809. /*
  3810. * If we're handed a bigger struct than we know of,
  3811. * ensure all the unknown bits are 0 - i.e. new
  3812. * user-space does not rely on any kernel feature
  3813. * extensions we dont know about yet.
  3814. */
  3815. if (size > sizeof(*attr)) {
  3816. unsigned char __user *addr;
  3817. unsigned char __user *end;
  3818. unsigned char val;
  3819. addr = (void __user *)uattr + sizeof(*attr);
  3820. end = (void __user *)uattr + size;
  3821. for (; addr < end; addr++) {
  3822. ret = get_user(val, addr);
  3823. if (ret)
  3824. return ret;
  3825. if (val)
  3826. goto err_size;
  3827. }
  3828. size = sizeof(*attr);
  3829. }
  3830. ret = copy_from_user(attr, uattr, size);
  3831. if (ret)
  3832. return -EFAULT;
  3833. /*
  3834. * XXX: do we want to be lenient like existing syscalls; or do we want
  3835. * to be strict and return an error on out-of-bounds values?
  3836. */
  3837. attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
  3838. return 0;
  3839. err_size:
  3840. put_user(sizeof(*attr), &uattr->size);
  3841. return -E2BIG;
  3842. }
  3843. /**
  3844. * sys_sched_setscheduler - set/change the scheduler policy and RT priority
  3845. * @pid: the pid in question.
  3846. * @policy: new policy.
  3847. * @param: structure containing the new RT priority.
  3848. *
  3849. * Return: 0 on success. An error code otherwise.
  3850. */
  3851. SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
  3852. struct sched_param __user *, param)
  3853. {
  3854. /* negative values for policy are not valid */
  3855. if (policy < 0)
  3856. return -EINVAL;
  3857. return do_sched_setscheduler(pid, policy, param);
  3858. }
  3859. /**
  3860. * sys_sched_setparam - set/change the RT priority of a thread
  3861. * @pid: the pid in question.
  3862. * @param: structure containing the new RT priority.
  3863. *
  3864. * Return: 0 on success. An error code otherwise.
  3865. */
  3866. SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
  3867. {
  3868. return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
  3869. }
  3870. /**
  3871. * sys_sched_setattr - same as above, but with extended sched_attr
  3872. * @pid: the pid in question.
  3873. * @uattr: structure containing the extended parameters.
  3874. * @flags: for future extension.
  3875. */
  3876. SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
  3877. unsigned int, flags)
  3878. {
  3879. struct sched_attr attr;
  3880. struct task_struct *p;
  3881. int retval;
  3882. if (!uattr || pid < 0 || flags)
  3883. return -EINVAL;
  3884. retval = sched_copy_attr(uattr, &attr);
  3885. if (retval)
  3886. return retval;
  3887. if ((int)attr.sched_policy < 0)
  3888. return -EINVAL;
  3889. rcu_read_lock();
  3890. retval = -ESRCH;
  3891. p = find_process_by_pid(pid);
  3892. if (p != NULL)
  3893. retval = sched_setattr(p, &attr);
  3894. rcu_read_unlock();
  3895. return retval;
  3896. }
  3897. /**
  3898. * sys_sched_getscheduler - get the policy (scheduling class) of a thread
  3899. * @pid: the pid in question.
  3900. *
  3901. * Return: On success, the policy of the thread. Otherwise, a negative error
  3902. * code.
  3903. */
  3904. SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
  3905. {
  3906. struct task_struct *p;
  3907. int retval;
  3908. if (pid < 0)
  3909. return -EINVAL;
  3910. retval = -ESRCH;
  3911. rcu_read_lock();
  3912. p = find_process_by_pid(pid);
  3913. if (p) {
  3914. retval = security_task_getscheduler(p);
  3915. if (!retval)
  3916. retval = p->policy
  3917. | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
  3918. }
  3919. rcu_read_unlock();
  3920. return retval;
  3921. }
  3922. /**
  3923. * sys_sched_getparam - get the RT priority of a thread
  3924. * @pid: the pid in question.
  3925. * @param: structure containing the RT priority.
  3926. *
  3927. * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
  3928. * code.
  3929. */
  3930. SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
  3931. {
  3932. struct sched_param lp = { .sched_priority = 0 };
  3933. struct task_struct *p;
  3934. int retval;
  3935. if (!param || pid < 0)
  3936. return -EINVAL;
  3937. rcu_read_lock();
  3938. p = find_process_by_pid(pid);
  3939. retval = -ESRCH;
  3940. if (!p)
  3941. goto out_unlock;
  3942. retval = security_task_getscheduler(p);
  3943. if (retval)
  3944. goto out_unlock;
  3945. if (task_has_rt_policy(p))
  3946. lp.sched_priority = p->rt_priority;
  3947. rcu_read_unlock();
  3948. /*
  3949. * This one might sleep, we cannot do it with a spinlock held ...
  3950. */
  3951. retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  3952. return retval;
  3953. out_unlock:
  3954. rcu_read_unlock();
  3955. return retval;
  3956. }
  3957. static int sched_read_attr(struct sched_attr __user *uattr,
  3958. struct sched_attr *attr,
  3959. unsigned int usize)
  3960. {
  3961. int ret;
  3962. if (!access_ok(VERIFY_WRITE, uattr, usize))
  3963. return -EFAULT;
  3964. /*
  3965. * If we're handed a smaller struct than we know of,
  3966. * ensure all the unknown bits are 0 - i.e. old
  3967. * user-space does not get uncomplete information.
  3968. */
  3969. if (usize < sizeof(*attr)) {
  3970. unsigned char *addr;
  3971. unsigned char *end;
  3972. addr = (void *)attr + usize;
  3973. end = (void *)attr + sizeof(*attr);
  3974. for (; addr < end; addr++) {
  3975. if (*addr)
  3976. return -EFBIG;
  3977. }
  3978. attr->size = usize;
  3979. }
  3980. ret = copy_to_user(uattr, attr, attr->size);
  3981. if (ret)
  3982. return -EFAULT;
  3983. return 0;
  3984. }
  3985. /**
  3986. * sys_sched_getattr - similar to sched_getparam, but with sched_attr
  3987. * @pid: the pid in question.
  3988. * @uattr: structure containing the extended parameters.
  3989. * @size: sizeof(attr) for fwd/bwd comp.
  3990. * @flags: for future extension.
  3991. */
  3992. SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
  3993. unsigned int, size, unsigned int, flags)
  3994. {
  3995. struct sched_attr attr = {
  3996. .size = sizeof(struct sched_attr),
  3997. };
  3998. struct task_struct *p;
  3999. int retval;
  4000. if (!uattr || pid < 0 || size > PAGE_SIZE ||
  4001. size < SCHED_ATTR_SIZE_VER0 || flags)
  4002. return -EINVAL;
  4003. rcu_read_lock();
  4004. p = find_process_by_pid(pid);
  4005. retval = -ESRCH;
  4006. if (!p)
  4007. goto out_unlock;
  4008. retval = security_task_getscheduler(p);
  4009. if (retval)
  4010. goto out_unlock;
  4011. attr.sched_policy = p->policy;
  4012. if (p->sched_reset_on_fork)
  4013. attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
  4014. if (task_has_dl_policy(p))
  4015. __getparam_dl(p, &attr);
  4016. else if (task_has_rt_policy(p))
  4017. attr.sched_priority = p->rt_priority;
  4018. else
  4019. attr.sched_nice = task_nice(p);
  4020. rcu_read_unlock();
  4021. retval = sched_read_attr(uattr, &attr, size);
  4022. return retval;
  4023. out_unlock:
  4024. rcu_read_unlock();
  4025. return retval;
  4026. }
  4027. long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
  4028. {
  4029. cpumask_var_t cpus_allowed, new_mask;
  4030. struct task_struct *p;
  4031. int retval;
  4032. rcu_read_lock();
  4033. p = find_process_by_pid(pid);
  4034. if (!p) {
  4035. rcu_read_unlock();
  4036. return -ESRCH;
  4037. }
  4038. /* Prevent p going away */
  4039. get_task_struct(p);
  4040. rcu_read_unlock();
  4041. if (p->flags & PF_NO_SETAFFINITY) {
  4042. retval = -EINVAL;
  4043. goto out_put_task;
  4044. }
  4045. if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
  4046. retval = -ENOMEM;
  4047. goto out_put_task;
  4048. }
  4049. if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
  4050. retval = -ENOMEM;
  4051. goto out_free_cpus_allowed;
  4052. }
  4053. retval = -EPERM;
  4054. if (!check_same_owner(p)) {
  4055. rcu_read_lock();
  4056. if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
  4057. rcu_read_unlock();
  4058. goto out_free_new_mask;
  4059. }
  4060. rcu_read_unlock();
  4061. }
  4062. retval = security_task_setscheduler(p);
  4063. if (retval)
  4064. goto out_free_new_mask;
  4065. cpuset_cpus_allowed(p, cpus_allowed);
  4066. cpumask_and(new_mask, in_mask, cpus_allowed);
  4067. /*
  4068. * Since bandwidth control happens on root_domain basis,
  4069. * if admission test is enabled, we only admit -deadline
  4070. * tasks allowed to run on all the CPUs in the task's
  4071. * root_domain.
  4072. */
  4073. #ifdef CONFIG_SMP
  4074. if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
  4075. rcu_read_lock();
  4076. if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
  4077. retval = -EBUSY;
  4078. rcu_read_unlock();
  4079. goto out_free_new_mask;
  4080. }
  4081. rcu_read_unlock();
  4082. }
  4083. #endif
  4084. again:
  4085. retval = __set_cpus_allowed_ptr(p, new_mask, true);
  4086. if (!retval) {
  4087. cpuset_cpus_allowed(p, cpus_allowed);
  4088. if (!cpumask_subset(new_mask, cpus_allowed)) {
  4089. /*
  4090. * We must have raced with a concurrent cpuset
  4091. * update. Just reset the cpus_allowed to the
  4092. * cpuset's cpus_allowed
  4093. */
  4094. cpumask_copy(new_mask, cpus_allowed);
  4095. goto again;
  4096. }
  4097. }
  4098. out_free_new_mask:
  4099. free_cpumask_var(new_mask);
  4100. out_free_cpus_allowed:
  4101. free_cpumask_var(cpus_allowed);
  4102. out_put_task:
  4103. put_task_struct(p);
  4104. return retval;
  4105. }
  4106. static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
  4107. struct cpumask *new_mask)
  4108. {
  4109. if (len < cpumask_size())
  4110. cpumask_clear(new_mask);
  4111. else if (len > cpumask_size())
  4112. len = cpumask_size();
  4113. return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
  4114. }
  4115. /**
  4116. * sys_sched_setaffinity - set the cpu affinity of a process
  4117. * @pid: pid of the process
  4118. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  4119. * @user_mask_ptr: user-space pointer to the new cpu mask
  4120. *
  4121. * Return: 0 on success. An error code otherwise.
  4122. */
  4123. SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
  4124. unsigned long __user *, user_mask_ptr)
  4125. {
  4126. cpumask_var_t new_mask;
  4127. int retval;
  4128. if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
  4129. return -ENOMEM;
  4130. retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
  4131. if (retval == 0)
  4132. retval = sched_setaffinity(pid, new_mask);
  4133. free_cpumask_var(new_mask);
  4134. return retval;
  4135. }
  4136. long sched_getaffinity(pid_t pid, struct cpumask *mask)
  4137. {
  4138. struct task_struct *p;
  4139. unsigned long flags;
  4140. int retval;
  4141. rcu_read_lock();
  4142. retval = -ESRCH;
  4143. p = find_process_by_pid(pid);
  4144. if (!p)
  4145. goto out_unlock;
  4146. retval = security_task_getscheduler(p);
  4147. if (retval)
  4148. goto out_unlock;
  4149. raw_spin_lock_irqsave(&p->pi_lock, flags);
  4150. cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
  4151. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  4152. out_unlock:
  4153. rcu_read_unlock();
  4154. return retval;
  4155. }
  4156. /**
  4157. * sys_sched_getaffinity - get the cpu affinity of a process
  4158. * @pid: pid of the process
  4159. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  4160. * @user_mask_ptr: user-space pointer to hold the current cpu mask
  4161. *
  4162. * Return: size of CPU mask copied to user_mask_ptr on success. An
  4163. * error code otherwise.
  4164. */
  4165. SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
  4166. unsigned long __user *, user_mask_ptr)
  4167. {
  4168. int ret;
  4169. cpumask_var_t mask;
  4170. if ((len * BITS_PER_BYTE) < nr_cpu_ids)
  4171. return -EINVAL;
  4172. if (len & (sizeof(unsigned long)-1))
  4173. return -EINVAL;
  4174. if (!alloc_cpumask_var(&mask, GFP_KERNEL))
  4175. return -ENOMEM;
  4176. ret = sched_getaffinity(pid, mask);
  4177. if (ret == 0) {
  4178. size_t retlen = min_t(size_t, len, cpumask_size());
  4179. if (copy_to_user(user_mask_ptr, mask, retlen))
  4180. ret = -EFAULT;
  4181. else
  4182. ret = retlen;
  4183. }
  4184. free_cpumask_var(mask);
  4185. return ret;
  4186. }
  4187. /**
  4188. * sys_sched_yield - yield the current processor to other threads.
  4189. *
  4190. * This function yields the current CPU to other tasks. If there are no
  4191. * other threads running on this CPU then this function will return.
  4192. *
  4193. * Return: 0.
  4194. */
  4195. SYSCALL_DEFINE0(sched_yield)
  4196. {
  4197. struct rq *rq = this_rq_lock();
  4198. schedstat_inc(rq->yld_count);
  4199. current->sched_class->yield_task(rq);
  4200. /*
  4201. * Since we are going to call schedule() anyway, there's
  4202. * no need to preempt or enable interrupts:
  4203. */
  4204. __release(rq->lock);
  4205. spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
  4206. do_raw_spin_unlock(&rq->lock);
  4207. sched_preempt_enable_no_resched();
  4208. schedule();
  4209. return 0;
  4210. }
  4211. #ifndef CONFIG_PREEMPT
  4212. int __sched _cond_resched(void)
  4213. {
  4214. if (should_resched(0)) {
  4215. preempt_schedule_common();
  4216. return 1;
  4217. }
  4218. return 0;
  4219. }
  4220. EXPORT_SYMBOL(_cond_resched);
  4221. #endif
  4222. /*
  4223. * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
  4224. * call schedule, and on return reacquire the lock.
  4225. *
  4226. * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
  4227. * operations here to prevent schedule() from being called twice (once via
  4228. * spin_unlock(), once by hand).
  4229. */
  4230. int __cond_resched_lock(spinlock_t *lock)
  4231. {
  4232. int resched = should_resched(PREEMPT_LOCK_OFFSET);
  4233. int ret = 0;
  4234. lockdep_assert_held(lock);
  4235. if (spin_needbreak(lock) || resched) {
  4236. spin_unlock(lock);
  4237. if (resched)
  4238. preempt_schedule_common();
  4239. else
  4240. cpu_relax();
  4241. ret = 1;
  4242. spin_lock(lock);
  4243. }
  4244. return ret;
  4245. }
  4246. EXPORT_SYMBOL(__cond_resched_lock);
  4247. int __sched __cond_resched_softirq(void)
  4248. {
  4249. BUG_ON(!in_softirq());
  4250. if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
  4251. local_bh_enable();
  4252. preempt_schedule_common();
  4253. local_bh_disable();
  4254. return 1;
  4255. }
  4256. return 0;
  4257. }
  4258. EXPORT_SYMBOL(__cond_resched_softirq);
  4259. /**
  4260. * yield - yield the current processor to other threads.
  4261. *
  4262. * Do not ever use this function, there's a 99% chance you're doing it wrong.
  4263. *
  4264. * The scheduler is at all times free to pick the calling task as the most
  4265. * eligible task to run, if removing the yield() call from your code breaks
  4266. * it, its already broken.
  4267. *
  4268. * Typical broken usage is:
  4269. *
  4270. * while (!event)
  4271. * yield();
  4272. *
  4273. * where one assumes that yield() will let 'the other' process run that will
  4274. * make event true. If the current task is a SCHED_FIFO task that will never
  4275. * happen. Never use yield() as a progress guarantee!!
  4276. *
  4277. * If you want to use yield() to wait for something, use wait_event().
  4278. * If you want to use yield() to be 'nice' for others, use cond_resched().
  4279. * If you still want to use yield(), do not!
  4280. */
  4281. void __sched yield(void)
  4282. {
  4283. set_current_state(TASK_RUNNING);
  4284. sys_sched_yield();
  4285. }
  4286. EXPORT_SYMBOL(yield);
  4287. /**
  4288. * yield_to - yield the current processor to another thread in
  4289. * your thread group, or accelerate that thread toward the
  4290. * processor it's on.
  4291. * @p: target task
  4292. * @preempt: whether task preemption is allowed or not
  4293. *
  4294. * It's the caller's job to ensure that the target task struct
  4295. * can't go away on us before we can do any checks.
  4296. *
  4297. * Return:
  4298. * true (>0) if we indeed boosted the target task.
  4299. * false (0) if we failed to boost the target.
  4300. * -ESRCH if there's no task to yield to.
  4301. */
  4302. int __sched yield_to(struct task_struct *p, bool preempt)
  4303. {
  4304. struct task_struct *curr = current;
  4305. struct rq *rq, *p_rq;
  4306. unsigned long flags;
  4307. int yielded = 0;
  4308. local_irq_save(flags);
  4309. rq = this_rq();
  4310. again:
  4311. p_rq = task_rq(p);
  4312. /*
  4313. * If we're the only runnable task on the rq and target rq also
  4314. * has only one task, there's absolutely no point in yielding.
  4315. */
  4316. if (rq->nr_running == 1 && p_rq->nr_running == 1) {
  4317. yielded = -ESRCH;
  4318. goto out_irq;
  4319. }
  4320. double_rq_lock(rq, p_rq);
  4321. if (task_rq(p) != p_rq) {
  4322. double_rq_unlock(rq, p_rq);
  4323. goto again;
  4324. }
  4325. if (!curr->sched_class->yield_to_task)
  4326. goto out_unlock;
  4327. if (curr->sched_class != p->sched_class)
  4328. goto out_unlock;
  4329. if (task_running(p_rq, p) || p->state)
  4330. goto out_unlock;
  4331. yielded = curr->sched_class->yield_to_task(rq, p, preempt);
  4332. if (yielded) {
  4333. schedstat_inc(rq->yld_count);
  4334. /*
  4335. * Make p's CPU reschedule; pick_next_entity takes care of
  4336. * fairness.
  4337. */
  4338. if (preempt && rq != p_rq)
  4339. resched_curr(p_rq);
  4340. }
  4341. out_unlock:
  4342. double_rq_unlock(rq, p_rq);
  4343. out_irq:
  4344. local_irq_restore(flags);
  4345. if (yielded > 0)
  4346. schedule();
  4347. return yielded;
  4348. }
  4349. EXPORT_SYMBOL_GPL(yield_to);
  4350. /*
  4351. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  4352. * that process accounting knows that this is a task in IO wait state.
  4353. */
  4354. long __sched io_schedule_timeout(long timeout)
  4355. {
  4356. int old_iowait = current->in_iowait;
  4357. struct rq *rq;
  4358. long ret;
  4359. current->in_iowait = 1;
  4360. blk_schedule_flush_plug(current);
  4361. delayacct_blkio_start();
  4362. rq = raw_rq();
  4363. atomic_inc(&rq->nr_iowait);
  4364. ret = schedule_timeout(timeout);
  4365. current->in_iowait = old_iowait;
  4366. atomic_dec(&rq->nr_iowait);
  4367. delayacct_blkio_end();
  4368. return ret;
  4369. }
  4370. EXPORT_SYMBOL(io_schedule_timeout);
  4371. /**
  4372. * sys_sched_get_priority_max - return maximum RT priority.
  4373. * @policy: scheduling class.
  4374. *
  4375. * Return: On success, this syscall returns the maximum
  4376. * rt_priority that can be used by a given scheduling class.
  4377. * On failure, a negative error code is returned.
  4378. */
  4379. SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
  4380. {
  4381. int ret = -EINVAL;
  4382. switch (policy) {
  4383. case SCHED_FIFO:
  4384. case SCHED_RR:
  4385. ret = MAX_USER_RT_PRIO-1;
  4386. break;
  4387. case SCHED_DEADLINE:
  4388. case SCHED_NORMAL:
  4389. case SCHED_BATCH:
  4390. case SCHED_IDLE:
  4391. ret = 0;
  4392. break;
  4393. }
  4394. return ret;
  4395. }
  4396. /**
  4397. * sys_sched_get_priority_min - return minimum RT priority.
  4398. * @policy: scheduling class.
  4399. *
  4400. * Return: On success, this syscall returns the minimum
  4401. * rt_priority that can be used by a given scheduling class.
  4402. * On failure, a negative error code is returned.
  4403. */
  4404. SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
  4405. {
  4406. int ret = -EINVAL;
  4407. switch (policy) {
  4408. case SCHED_FIFO:
  4409. case SCHED_RR:
  4410. ret = 1;
  4411. break;
  4412. case SCHED_DEADLINE:
  4413. case SCHED_NORMAL:
  4414. case SCHED_BATCH:
  4415. case SCHED_IDLE:
  4416. ret = 0;
  4417. }
  4418. return ret;
  4419. }
  4420. /**
  4421. * sys_sched_rr_get_interval - return the default timeslice of a process.
  4422. * @pid: pid of the process.
  4423. * @interval: userspace pointer to the timeslice value.
  4424. *
  4425. * this syscall writes the default timeslice value of a given process
  4426. * into the user-space timespec buffer. A value of '0' means infinity.
  4427. *
  4428. * Return: On success, 0 and the timeslice is in @interval. Otherwise,
  4429. * an error code.
  4430. */
  4431. SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
  4432. struct timespec __user *, interval)
  4433. {
  4434. struct task_struct *p;
  4435. unsigned int time_slice;
  4436. struct rq_flags rf;
  4437. struct timespec t;
  4438. struct rq *rq;
  4439. int retval;
  4440. if (pid < 0)
  4441. return -EINVAL;
  4442. retval = -ESRCH;
  4443. rcu_read_lock();
  4444. p = find_process_by_pid(pid);
  4445. if (!p)
  4446. goto out_unlock;
  4447. retval = security_task_getscheduler(p);
  4448. if (retval)
  4449. goto out_unlock;
  4450. rq = task_rq_lock(p, &rf);
  4451. time_slice = 0;
  4452. if (p->sched_class->get_rr_interval)
  4453. time_slice = p->sched_class->get_rr_interval(rq, p);
  4454. task_rq_unlock(rq, p, &rf);
  4455. rcu_read_unlock();
  4456. jiffies_to_timespec(time_slice, &t);
  4457. retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
  4458. return retval;
  4459. out_unlock:
  4460. rcu_read_unlock();
  4461. return retval;
  4462. }
  4463. static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
  4464. void sched_show_task(struct task_struct *p)
  4465. {
  4466. unsigned long free = 0;
  4467. int ppid;
  4468. unsigned long state = p->state;
  4469. if (state)
  4470. state = __ffs(state) + 1;
  4471. printk(KERN_INFO "%-15.15s %c", p->comm,
  4472. state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
  4473. #if BITS_PER_LONG == 32
  4474. if (state == TASK_RUNNING)
  4475. printk(KERN_CONT " running ");
  4476. else
  4477. printk(KERN_CONT " %08lx ", thread_saved_pc(p));
  4478. #else
  4479. if (state == TASK_RUNNING)
  4480. printk(KERN_CONT " running task ");
  4481. else
  4482. printk(KERN_CONT " %016lx ", thread_saved_pc(p));
  4483. #endif
  4484. #ifdef CONFIG_DEBUG_STACK_USAGE
  4485. free = stack_not_used(p);
  4486. #endif
  4487. ppid = 0;
  4488. rcu_read_lock();
  4489. if (pid_alive(p))
  4490. ppid = task_pid_nr(rcu_dereference(p->real_parent));
  4491. rcu_read_unlock();
  4492. printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
  4493. task_pid_nr(p), ppid,
  4494. (unsigned long)task_thread_info(p)->flags);
  4495. print_worker_info(KERN_INFO, p);
  4496. show_stack(p, NULL);
  4497. }
  4498. void show_state_filter(unsigned long state_filter)
  4499. {
  4500. struct task_struct *g, *p;
  4501. #if BITS_PER_LONG == 32
  4502. printk(KERN_INFO
  4503. " task PC stack pid father\n");
  4504. #else
  4505. printk(KERN_INFO
  4506. " task PC stack pid father\n");
  4507. #endif
  4508. rcu_read_lock();
  4509. for_each_process_thread(g, p) {
  4510. /*
  4511. * reset the NMI-timeout, listing all files on a slow
  4512. * console might take a lot of time:
  4513. * Also, reset softlockup watchdogs on all CPUs, because
  4514. * another CPU might be blocked waiting for us to process
  4515. * an IPI.
  4516. */
  4517. touch_nmi_watchdog();
  4518. touch_all_softlockup_watchdogs();
  4519. if (!state_filter || (p->state & state_filter))
  4520. sched_show_task(p);
  4521. }
  4522. #ifdef CONFIG_SCHED_DEBUG
  4523. if (!state_filter)
  4524. sysrq_sched_debug_show();
  4525. #endif
  4526. rcu_read_unlock();
  4527. /*
  4528. * Only show locks if all tasks are dumped:
  4529. */
  4530. if (!state_filter)
  4531. debug_show_all_locks();
  4532. }
  4533. void init_idle_bootup_task(struct task_struct *idle)
  4534. {
  4535. idle->sched_class = &idle_sched_class;
  4536. }
  4537. /**
  4538. * init_idle - set up an idle thread for a given CPU
  4539. * @idle: task in question
  4540. * @cpu: cpu the idle task belongs to
  4541. *
  4542. * NOTE: this function does not set the idle thread's NEED_RESCHED
  4543. * flag, to make booting more robust.
  4544. */
  4545. void init_idle(struct task_struct *idle, int cpu)
  4546. {
  4547. struct rq *rq = cpu_rq(cpu);
  4548. unsigned long flags;
  4549. raw_spin_lock_irqsave(&idle->pi_lock, flags);
  4550. raw_spin_lock(&rq->lock);
  4551. __sched_fork(0, idle);
  4552. idle->state = TASK_RUNNING;
  4553. idle->se.exec_start = sched_clock();
  4554. kasan_unpoison_task_stack(idle);
  4555. #ifdef CONFIG_SMP
  4556. /*
  4557. * Its possible that init_idle() gets called multiple times on a task,
  4558. * in that case do_set_cpus_allowed() will not do the right thing.
  4559. *
  4560. * And since this is boot we can forgo the serialization.
  4561. */
  4562. set_cpus_allowed_common(idle, cpumask_of(cpu));
  4563. #endif
  4564. /*
  4565. * We're having a chicken and egg problem, even though we are
  4566. * holding rq->lock, the cpu isn't yet set to this cpu so the
  4567. * lockdep check in task_group() will fail.
  4568. *
  4569. * Similar case to sched_fork(). / Alternatively we could
  4570. * use task_rq_lock() here and obtain the other rq->lock.
  4571. *
  4572. * Silence PROVE_RCU
  4573. */
  4574. rcu_read_lock();
  4575. __set_task_cpu(idle, cpu);
  4576. rcu_read_unlock();
  4577. rq->curr = rq->idle = idle;
  4578. idle->on_rq = TASK_ON_RQ_QUEUED;
  4579. #ifdef CONFIG_SMP
  4580. idle->on_cpu = 1;
  4581. #endif
  4582. raw_spin_unlock(&rq->lock);
  4583. raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
  4584. /* Set the preempt count _outside_ the spinlocks! */
  4585. init_idle_preempt_count(idle, cpu);
  4586. /*
  4587. * The idle tasks have their own, simple scheduling class:
  4588. */
  4589. idle->sched_class = &idle_sched_class;
  4590. ftrace_graph_init_idle_task(idle, cpu);
  4591. vtime_init_idle(idle, cpu);
  4592. #ifdef CONFIG_SMP
  4593. sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
  4594. #endif
  4595. }
  4596. int cpuset_cpumask_can_shrink(const struct cpumask *cur,
  4597. const struct cpumask *trial)
  4598. {
  4599. int ret = 1, trial_cpus;
  4600. struct dl_bw *cur_dl_b;
  4601. unsigned long flags;
  4602. if (!cpumask_weight(cur))
  4603. return ret;
  4604. rcu_read_lock_sched();
  4605. cur_dl_b = dl_bw_of(cpumask_any(cur));
  4606. trial_cpus = cpumask_weight(trial);
  4607. raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
  4608. if (cur_dl_b->bw != -1 &&
  4609. cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
  4610. ret = 0;
  4611. raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
  4612. rcu_read_unlock_sched();
  4613. return ret;
  4614. }
  4615. int task_can_attach(struct task_struct *p,
  4616. const struct cpumask *cs_cpus_allowed)
  4617. {
  4618. int ret = 0;
  4619. /*
  4620. * Kthreads which disallow setaffinity shouldn't be moved
  4621. * to a new cpuset; we don't want to change their cpu
  4622. * affinity and isolating such threads by their set of
  4623. * allowed nodes is unnecessary. Thus, cpusets are not
  4624. * applicable for such threads. This prevents checking for
  4625. * success of set_cpus_allowed_ptr() on all attached tasks
  4626. * before cpus_allowed may be changed.
  4627. */
  4628. if (p->flags & PF_NO_SETAFFINITY) {
  4629. ret = -EINVAL;
  4630. goto out;
  4631. }
  4632. #ifdef CONFIG_SMP
  4633. if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
  4634. cs_cpus_allowed)) {
  4635. unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
  4636. cs_cpus_allowed);
  4637. struct dl_bw *dl_b;
  4638. bool overflow;
  4639. int cpus;
  4640. unsigned long flags;
  4641. rcu_read_lock_sched();
  4642. dl_b = dl_bw_of(dest_cpu);
  4643. raw_spin_lock_irqsave(&dl_b->lock, flags);
  4644. cpus = dl_bw_cpus(dest_cpu);
  4645. overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
  4646. if (overflow)
  4647. ret = -EBUSY;
  4648. else {
  4649. /*
  4650. * We reserve space for this task in the destination
  4651. * root_domain, as we can't fail after this point.
  4652. * We will free resources in the source root_domain
  4653. * later on (see set_cpus_allowed_dl()).
  4654. */
  4655. __dl_add(dl_b, p->dl.dl_bw);
  4656. }
  4657. raw_spin_unlock_irqrestore(&dl_b->lock, flags);
  4658. rcu_read_unlock_sched();
  4659. }
  4660. #endif
  4661. out:
  4662. return ret;
  4663. }
  4664. #ifdef CONFIG_SMP
  4665. static bool sched_smp_initialized __read_mostly;
  4666. #ifdef CONFIG_NUMA_BALANCING
  4667. /* Migrate current task p to target_cpu */
  4668. int migrate_task_to(struct task_struct *p, int target_cpu)
  4669. {
  4670. struct migration_arg arg = { p, target_cpu };
  4671. int curr_cpu = task_cpu(p);
  4672. if (curr_cpu == target_cpu)
  4673. return 0;
  4674. if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
  4675. return -EINVAL;
  4676. /* TODO: This is not properly updating schedstats */
  4677. trace_sched_move_numa(p, curr_cpu, target_cpu);
  4678. return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
  4679. }
  4680. /*
  4681. * Requeue a task on a given node and accurately track the number of NUMA
  4682. * tasks on the runqueues
  4683. */
  4684. void sched_setnuma(struct task_struct *p, int nid)
  4685. {
  4686. bool queued, running;
  4687. struct rq_flags rf;
  4688. struct rq *rq;
  4689. rq = task_rq_lock(p, &rf);
  4690. queued = task_on_rq_queued(p);
  4691. running = task_current(rq, p);
  4692. if (queued)
  4693. dequeue_task(rq, p, DEQUEUE_SAVE);
  4694. if (running)
  4695. put_prev_task(rq, p);
  4696. p->numa_preferred_nid = nid;
  4697. if (running)
  4698. p->sched_class->set_curr_task(rq);
  4699. if (queued)
  4700. enqueue_task(rq, p, ENQUEUE_RESTORE);
  4701. task_rq_unlock(rq, p, &rf);
  4702. }
  4703. #endif /* CONFIG_NUMA_BALANCING */
  4704. #ifdef CONFIG_HOTPLUG_CPU
  4705. /*
  4706. * Ensures that the idle task is using init_mm right before its cpu goes
  4707. * offline.
  4708. */
  4709. void idle_task_exit(void)
  4710. {
  4711. struct mm_struct *mm = current->active_mm;
  4712. BUG_ON(cpu_online(smp_processor_id()));
  4713. if (mm != &init_mm) {
  4714. switch_mm_irqs_off(mm, &init_mm, current);
  4715. finish_arch_post_lock_switch();
  4716. }
  4717. mmdrop(mm);
  4718. }
  4719. /*
  4720. * Since this CPU is going 'away' for a while, fold any nr_active delta
  4721. * we might have. Assumes we're called after migrate_tasks() so that the
  4722. * nr_active count is stable. We need to take the teardown thread which
  4723. * is calling this into account, so we hand in adjust = 1 to the load
  4724. * calculation.
  4725. *
  4726. * Also see the comment "Global load-average calculations".
  4727. */
  4728. static void calc_load_migrate(struct rq *rq)
  4729. {
  4730. long delta = calc_load_fold_active(rq, 1);
  4731. if (delta)
  4732. atomic_long_add(delta, &calc_load_tasks);
  4733. }
  4734. static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
  4735. {
  4736. }
  4737. static const struct sched_class fake_sched_class = {
  4738. .put_prev_task = put_prev_task_fake,
  4739. };
  4740. static struct task_struct fake_task = {
  4741. /*
  4742. * Avoid pull_{rt,dl}_task()
  4743. */
  4744. .prio = MAX_PRIO + 1,
  4745. .sched_class = &fake_sched_class,
  4746. };
  4747. /*
  4748. * Migrate all tasks from the rq, sleeping tasks will be migrated by
  4749. * try_to_wake_up()->select_task_rq().
  4750. *
  4751. * Called with rq->lock held even though we'er in stop_machine() and
  4752. * there's no concurrency possible, we hold the required locks anyway
  4753. * because of lock validation efforts.
  4754. */
  4755. static void migrate_tasks(struct rq *dead_rq)
  4756. {
  4757. struct rq *rq = dead_rq;
  4758. struct task_struct *next, *stop = rq->stop;
  4759. struct pin_cookie cookie;
  4760. int dest_cpu;
  4761. /*
  4762. * Fudge the rq selection such that the below task selection loop
  4763. * doesn't get stuck on the currently eligible stop task.
  4764. *
  4765. * We're currently inside stop_machine() and the rq is either stuck
  4766. * in the stop_machine_cpu_stop() loop, or we're executing this code,
  4767. * either way we should never end up calling schedule() until we're
  4768. * done here.
  4769. */
  4770. rq->stop = NULL;
  4771. /*
  4772. * put_prev_task() and pick_next_task() sched
  4773. * class method both need to have an up-to-date
  4774. * value of rq->clock[_task]
  4775. */
  4776. update_rq_clock(rq);
  4777. for (;;) {
  4778. /*
  4779. * There's this thread running, bail when that's the only
  4780. * remaining thread.
  4781. */
  4782. if (rq->nr_running == 1)
  4783. break;
  4784. /*
  4785. * pick_next_task assumes pinned rq->lock.
  4786. */
  4787. cookie = lockdep_pin_lock(&rq->lock);
  4788. next = pick_next_task(rq, &fake_task, cookie);
  4789. BUG_ON(!next);
  4790. next->sched_class->put_prev_task(rq, next);
  4791. /*
  4792. * Rules for changing task_struct::cpus_allowed are holding
  4793. * both pi_lock and rq->lock, such that holding either
  4794. * stabilizes the mask.
  4795. *
  4796. * Drop rq->lock is not quite as disastrous as it usually is
  4797. * because !cpu_active at this point, which means load-balance
  4798. * will not interfere. Also, stop-machine.
  4799. */
  4800. lockdep_unpin_lock(&rq->lock, cookie);
  4801. raw_spin_unlock(&rq->lock);
  4802. raw_spin_lock(&next->pi_lock);
  4803. raw_spin_lock(&rq->lock);
  4804. /*
  4805. * Since we're inside stop-machine, _nothing_ should have
  4806. * changed the task, WARN if weird stuff happened, because in
  4807. * that case the above rq->lock drop is a fail too.
  4808. */
  4809. if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
  4810. raw_spin_unlock(&next->pi_lock);
  4811. continue;
  4812. }
  4813. /* Find suitable destination for @next, with force if needed. */
  4814. dest_cpu = select_fallback_rq(dead_rq->cpu, next);
  4815. rq = __migrate_task(rq, next, dest_cpu);
  4816. if (rq != dead_rq) {
  4817. raw_spin_unlock(&rq->lock);
  4818. rq = dead_rq;
  4819. raw_spin_lock(&rq->lock);
  4820. }
  4821. raw_spin_unlock(&next->pi_lock);
  4822. }
  4823. rq->stop = stop;
  4824. }
  4825. #endif /* CONFIG_HOTPLUG_CPU */
  4826. static void set_rq_online(struct rq *rq)
  4827. {
  4828. if (!rq->online) {
  4829. const struct sched_class *class;
  4830. cpumask_set_cpu(rq->cpu, rq->rd->online);
  4831. rq->online = 1;
  4832. for_each_class(class) {
  4833. if (class->rq_online)
  4834. class->rq_online(rq);
  4835. }
  4836. }
  4837. }
  4838. static void set_rq_offline(struct rq *rq)
  4839. {
  4840. if (rq->online) {
  4841. const struct sched_class *class;
  4842. for_each_class(class) {
  4843. if (class->rq_offline)
  4844. class->rq_offline(rq);
  4845. }
  4846. cpumask_clear_cpu(rq->cpu, rq->rd->online);
  4847. rq->online = 0;
  4848. }
  4849. }
  4850. static void set_cpu_rq_start_time(unsigned int cpu)
  4851. {
  4852. struct rq *rq = cpu_rq(cpu);
  4853. rq->age_stamp = sched_clock_cpu(cpu);
  4854. }
  4855. static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
  4856. #ifdef CONFIG_SCHED_DEBUG
  4857. static __read_mostly int sched_debug_enabled;
  4858. static int __init sched_debug_setup(char *str)
  4859. {
  4860. sched_debug_enabled = 1;
  4861. return 0;
  4862. }
  4863. early_param("sched_debug", sched_debug_setup);
  4864. static inline bool sched_debug(void)
  4865. {
  4866. return sched_debug_enabled;
  4867. }
  4868. static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
  4869. struct cpumask *groupmask)
  4870. {
  4871. struct sched_group *group = sd->groups;
  4872. cpumask_clear(groupmask);
  4873. printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
  4874. if (!(sd->flags & SD_LOAD_BALANCE)) {
  4875. printk("does not load-balance\n");
  4876. if (sd->parent)
  4877. printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
  4878. " has parent");
  4879. return -1;
  4880. }
  4881. printk(KERN_CONT "span %*pbl level %s\n",
  4882. cpumask_pr_args(sched_domain_span(sd)), sd->name);
  4883. if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
  4884. printk(KERN_ERR "ERROR: domain->span does not contain "
  4885. "CPU%d\n", cpu);
  4886. }
  4887. if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
  4888. printk(KERN_ERR "ERROR: domain->groups does not contain"
  4889. " CPU%d\n", cpu);
  4890. }
  4891. printk(KERN_DEBUG "%*s groups:", level + 1, "");
  4892. do {
  4893. if (!group) {
  4894. printk("\n");
  4895. printk(KERN_ERR "ERROR: group is NULL\n");
  4896. break;
  4897. }
  4898. if (!cpumask_weight(sched_group_cpus(group))) {
  4899. printk(KERN_CONT "\n");
  4900. printk(KERN_ERR "ERROR: empty group\n");
  4901. break;
  4902. }
  4903. if (!(sd->flags & SD_OVERLAP) &&
  4904. cpumask_intersects(groupmask, sched_group_cpus(group))) {
  4905. printk(KERN_CONT "\n");
  4906. printk(KERN_ERR "ERROR: repeated CPUs\n");
  4907. break;
  4908. }
  4909. cpumask_or(groupmask, groupmask, sched_group_cpus(group));
  4910. printk(KERN_CONT " %*pbl",
  4911. cpumask_pr_args(sched_group_cpus(group)));
  4912. if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
  4913. printk(KERN_CONT " (cpu_capacity = %d)",
  4914. group->sgc->capacity);
  4915. }
  4916. group = group->next;
  4917. } while (group != sd->groups);
  4918. printk(KERN_CONT "\n");
  4919. if (!cpumask_equal(sched_domain_span(sd), groupmask))
  4920. printk(KERN_ERR "ERROR: groups don't span domain->span\n");
  4921. if (sd->parent &&
  4922. !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
  4923. printk(KERN_ERR "ERROR: parent span is not a superset "
  4924. "of domain->span\n");
  4925. return 0;
  4926. }
  4927. static void sched_domain_debug(struct sched_domain *sd, int cpu)
  4928. {
  4929. int level = 0;
  4930. if (!sched_debug_enabled)
  4931. return;
  4932. if (!sd) {
  4933. printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
  4934. return;
  4935. }
  4936. printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
  4937. for (;;) {
  4938. if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
  4939. break;
  4940. level++;
  4941. sd = sd->parent;
  4942. if (!sd)
  4943. break;
  4944. }
  4945. }
  4946. #else /* !CONFIG_SCHED_DEBUG */
  4947. # define sched_debug_enabled 0
  4948. # define sched_domain_debug(sd, cpu) do { } while (0)
  4949. static inline bool sched_debug(void)
  4950. {
  4951. return false;
  4952. }
  4953. #endif /* CONFIG_SCHED_DEBUG */
  4954. static int sd_degenerate(struct sched_domain *sd)
  4955. {
  4956. if (cpumask_weight(sched_domain_span(sd)) == 1)
  4957. return 1;
  4958. /* Following flags need at least 2 groups */
  4959. if (sd->flags & (SD_LOAD_BALANCE |
  4960. SD_BALANCE_NEWIDLE |
  4961. SD_BALANCE_FORK |
  4962. SD_BALANCE_EXEC |
  4963. SD_SHARE_CPUCAPACITY |
  4964. SD_ASYM_CPUCAPACITY |
  4965. SD_SHARE_PKG_RESOURCES |
  4966. SD_SHARE_POWERDOMAIN)) {
  4967. if (sd->groups != sd->groups->next)
  4968. return 0;
  4969. }
  4970. /* Following flags don't use groups */
  4971. if (sd->flags & (SD_WAKE_AFFINE))
  4972. return 0;
  4973. return 1;
  4974. }
  4975. static int
  4976. sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
  4977. {
  4978. unsigned long cflags = sd->flags, pflags = parent->flags;
  4979. if (sd_degenerate(parent))
  4980. return 1;
  4981. if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
  4982. return 0;
  4983. /* Flags needing groups don't count if only 1 group in parent */
  4984. if (parent->groups == parent->groups->next) {
  4985. pflags &= ~(SD_LOAD_BALANCE |
  4986. SD_BALANCE_NEWIDLE |
  4987. SD_BALANCE_FORK |
  4988. SD_BALANCE_EXEC |
  4989. SD_ASYM_CPUCAPACITY |
  4990. SD_SHARE_CPUCAPACITY |
  4991. SD_SHARE_PKG_RESOURCES |
  4992. SD_PREFER_SIBLING |
  4993. SD_SHARE_POWERDOMAIN);
  4994. if (nr_node_ids == 1)
  4995. pflags &= ~SD_SERIALIZE;
  4996. }
  4997. if (~cflags & pflags)
  4998. return 0;
  4999. return 1;
  5000. }
  5001. static void free_rootdomain(struct rcu_head *rcu)
  5002. {
  5003. struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
  5004. cpupri_cleanup(&rd->cpupri);
  5005. cpudl_cleanup(&rd->cpudl);
  5006. free_cpumask_var(rd->dlo_mask);
  5007. free_cpumask_var(rd->rto_mask);
  5008. free_cpumask_var(rd->online);
  5009. free_cpumask_var(rd->span);
  5010. kfree(rd);
  5011. }
  5012. static void rq_attach_root(struct rq *rq, struct root_domain *rd)
  5013. {
  5014. struct root_domain *old_rd = NULL;
  5015. unsigned long flags;
  5016. raw_spin_lock_irqsave(&rq->lock, flags);
  5017. if (rq->rd) {
  5018. old_rd = rq->rd;
  5019. if (cpumask_test_cpu(rq->cpu, old_rd->online))
  5020. set_rq_offline(rq);
  5021. cpumask_clear_cpu(rq->cpu, old_rd->span);
  5022. /*
  5023. * If we dont want to free the old_rd yet then
  5024. * set old_rd to NULL to skip the freeing later
  5025. * in this function:
  5026. */
  5027. if (!atomic_dec_and_test(&old_rd->refcount))
  5028. old_rd = NULL;
  5029. }
  5030. atomic_inc(&rd->refcount);
  5031. rq->rd = rd;
  5032. cpumask_set_cpu(rq->cpu, rd->span);
  5033. if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
  5034. set_rq_online(rq);
  5035. raw_spin_unlock_irqrestore(&rq->lock, flags);
  5036. if (old_rd)
  5037. call_rcu_sched(&old_rd->rcu, free_rootdomain);
  5038. }
  5039. static int init_rootdomain(struct root_domain *rd)
  5040. {
  5041. memset(rd, 0, sizeof(*rd));
  5042. if (!zalloc_cpumask_var(&rd->span, GFP_KERNEL))
  5043. goto out;
  5044. if (!zalloc_cpumask_var(&rd->online, GFP_KERNEL))
  5045. goto free_span;
  5046. if (!zalloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
  5047. goto free_online;
  5048. if (!zalloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
  5049. goto free_dlo_mask;
  5050. init_dl_bw(&rd->dl_bw);
  5051. if (cpudl_init(&rd->cpudl) != 0)
  5052. goto free_dlo_mask;
  5053. if (cpupri_init(&rd->cpupri) != 0)
  5054. goto free_rto_mask;
  5055. return 0;
  5056. free_rto_mask:
  5057. free_cpumask_var(rd->rto_mask);
  5058. free_dlo_mask:
  5059. free_cpumask_var(rd->dlo_mask);
  5060. free_online:
  5061. free_cpumask_var(rd->online);
  5062. free_span:
  5063. free_cpumask_var(rd->span);
  5064. out:
  5065. return -ENOMEM;
  5066. }
  5067. /*
  5068. * By default the system creates a single root-domain with all cpus as
  5069. * members (mimicking the global state we have today).
  5070. */
  5071. struct root_domain def_root_domain;
  5072. static void init_defrootdomain(void)
  5073. {
  5074. init_rootdomain(&def_root_domain);
  5075. atomic_set(&def_root_domain.refcount, 1);
  5076. }
  5077. static struct root_domain *alloc_rootdomain(void)
  5078. {
  5079. struct root_domain *rd;
  5080. rd = kmalloc(sizeof(*rd), GFP_KERNEL);
  5081. if (!rd)
  5082. return NULL;
  5083. if (init_rootdomain(rd) != 0) {
  5084. kfree(rd);
  5085. return NULL;
  5086. }
  5087. return rd;
  5088. }
  5089. static void free_sched_groups(struct sched_group *sg, int free_sgc)
  5090. {
  5091. struct sched_group *tmp, *first;
  5092. if (!sg)
  5093. return;
  5094. first = sg;
  5095. do {
  5096. tmp = sg->next;
  5097. if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
  5098. kfree(sg->sgc);
  5099. kfree(sg);
  5100. sg = tmp;
  5101. } while (sg != first);
  5102. }
  5103. static void free_sched_domain(struct rcu_head *rcu)
  5104. {
  5105. struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
  5106. /*
  5107. * If its an overlapping domain it has private groups, iterate and
  5108. * nuke them all.
  5109. */
  5110. if (sd->flags & SD_OVERLAP) {
  5111. free_sched_groups(sd->groups, 1);
  5112. } else if (atomic_dec_and_test(&sd->groups->ref)) {
  5113. kfree(sd->groups->sgc);
  5114. kfree(sd->groups);
  5115. }
  5116. kfree(sd);
  5117. }
  5118. static void destroy_sched_domain(struct sched_domain *sd)
  5119. {
  5120. call_rcu(&sd->rcu, free_sched_domain);
  5121. }
  5122. static void destroy_sched_domains(struct sched_domain *sd)
  5123. {
  5124. for (; sd; sd = sd->parent)
  5125. destroy_sched_domain(sd);
  5126. }
  5127. /*
  5128. * Keep a special pointer to the highest sched_domain that has
  5129. * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
  5130. * allows us to avoid some pointer chasing select_idle_sibling().
  5131. *
  5132. * Also keep a unique ID per domain (we use the first cpu number in
  5133. * the cpumask of the domain), this allows us to quickly tell if
  5134. * two cpus are in the same cache domain, see cpus_share_cache().
  5135. */
  5136. DEFINE_PER_CPU(struct sched_domain *, sd_llc);
  5137. DEFINE_PER_CPU(int, sd_llc_size);
  5138. DEFINE_PER_CPU(int, sd_llc_id);
  5139. DEFINE_PER_CPU(struct sched_domain *, sd_numa);
  5140. DEFINE_PER_CPU(struct sched_domain *, sd_busy);
  5141. DEFINE_PER_CPU(struct sched_domain *, sd_asym);
  5142. static void update_top_cache_domain(int cpu)
  5143. {
  5144. struct sched_domain *sd;
  5145. struct sched_domain *busy_sd = NULL;
  5146. int id = cpu;
  5147. int size = 1;
  5148. sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
  5149. if (sd) {
  5150. id = cpumask_first(sched_domain_span(sd));
  5151. size = cpumask_weight(sched_domain_span(sd));
  5152. busy_sd = sd->parent; /* sd_busy */
  5153. }
  5154. rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd);
  5155. rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
  5156. per_cpu(sd_llc_size, cpu) = size;
  5157. per_cpu(sd_llc_id, cpu) = id;
  5158. sd = lowest_flag_domain(cpu, SD_NUMA);
  5159. rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
  5160. sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
  5161. rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
  5162. }
  5163. /*
  5164. * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
  5165. * hold the hotplug lock.
  5166. */
  5167. static void
  5168. cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
  5169. {
  5170. struct rq *rq = cpu_rq(cpu);
  5171. struct sched_domain *tmp;
  5172. /* Remove the sched domains which do not contribute to scheduling. */
  5173. for (tmp = sd; tmp; ) {
  5174. struct sched_domain *parent = tmp->parent;
  5175. if (!parent)
  5176. break;
  5177. if (sd_parent_degenerate(tmp, parent)) {
  5178. tmp->parent = parent->parent;
  5179. if (parent->parent)
  5180. parent->parent->child = tmp;
  5181. /*
  5182. * Transfer SD_PREFER_SIBLING down in case of a
  5183. * degenerate parent; the spans match for this
  5184. * so the property transfers.
  5185. */
  5186. if (parent->flags & SD_PREFER_SIBLING)
  5187. tmp->flags |= SD_PREFER_SIBLING;
  5188. destroy_sched_domain(parent);
  5189. } else
  5190. tmp = tmp->parent;
  5191. }
  5192. if (sd && sd_degenerate(sd)) {
  5193. tmp = sd;
  5194. sd = sd->parent;
  5195. destroy_sched_domain(tmp);
  5196. if (sd)
  5197. sd->child = NULL;
  5198. }
  5199. sched_domain_debug(sd, cpu);
  5200. rq_attach_root(rq, rd);
  5201. tmp = rq->sd;
  5202. rcu_assign_pointer(rq->sd, sd);
  5203. destroy_sched_domains(tmp);
  5204. update_top_cache_domain(cpu);
  5205. }
  5206. /* Setup the mask of cpus configured for isolated domains */
  5207. static int __init isolated_cpu_setup(char *str)
  5208. {
  5209. int ret;
  5210. alloc_bootmem_cpumask_var(&cpu_isolated_map);
  5211. ret = cpulist_parse(str, cpu_isolated_map);
  5212. if (ret) {
  5213. pr_err("sched: Error, all isolcpus= values must be between 0 and %d\n", nr_cpu_ids);
  5214. return 0;
  5215. }
  5216. return 1;
  5217. }
  5218. __setup("isolcpus=", isolated_cpu_setup);
  5219. struct s_data {
  5220. struct sched_domain ** __percpu sd;
  5221. struct root_domain *rd;
  5222. };
  5223. enum s_alloc {
  5224. sa_rootdomain,
  5225. sa_sd,
  5226. sa_sd_storage,
  5227. sa_none,
  5228. };
  5229. /*
  5230. * Build an iteration mask that can exclude certain CPUs from the upwards
  5231. * domain traversal.
  5232. *
  5233. * Asymmetric node setups can result in situations where the domain tree is of
  5234. * unequal depth, make sure to skip domains that already cover the entire
  5235. * range.
  5236. *
  5237. * In that case build_sched_domains() will have terminated the iteration early
  5238. * and our sibling sd spans will be empty. Domains should always include the
  5239. * cpu they're built on, so check that.
  5240. *
  5241. */
  5242. static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
  5243. {
  5244. const struct cpumask *span = sched_domain_span(sd);
  5245. struct sd_data *sdd = sd->private;
  5246. struct sched_domain *sibling;
  5247. int i;
  5248. for_each_cpu(i, span) {
  5249. sibling = *per_cpu_ptr(sdd->sd, i);
  5250. if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
  5251. continue;
  5252. cpumask_set_cpu(i, sched_group_mask(sg));
  5253. }
  5254. }
  5255. /*
  5256. * Return the canonical balance cpu for this group, this is the first cpu
  5257. * of this group that's also in the iteration mask.
  5258. */
  5259. int group_balance_cpu(struct sched_group *sg)
  5260. {
  5261. return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
  5262. }
  5263. static int
  5264. build_overlap_sched_groups(struct sched_domain *sd, int cpu)
  5265. {
  5266. struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
  5267. const struct cpumask *span = sched_domain_span(sd);
  5268. struct cpumask *covered = sched_domains_tmpmask;
  5269. struct sd_data *sdd = sd->private;
  5270. struct sched_domain *sibling;
  5271. int i;
  5272. cpumask_clear(covered);
  5273. for_each_cpu(i, span) {
  5274. struct cpumask *sg_span;
  5275. if (cpumask_test_cpu(i, covered))
  5276. continue;
  5277. sibling = *per_cpu_ptr(sdd->sd, i);
  5278. /* See the comment near build_group_mask(). */
  5279. if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
  5280. continue;
  5281. sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
  5282. GFP_KERNEL, cpu_to_node(cpu));
  5283. if (!sg)
  5284. goto fail;
  5285. sg_span = sched_group_cpus(sg);
  5286. if (sibling->child)
  5287. cpumask_copy(sg_span, sched_domain_span(sibling->child));
  5288. else
  5289. cpumask_set_cpu(i, sg_span);
  5290. cpumask_or(covered, covered, sg_span);
  5291. sg->sgc = *per_cpu_ptr(sdd->sgc, i);
  5292. if (atomic_inc_return(&sg->sgc->ref) == 1)
  5293. build_group_mask(sd, sg);
  5294. /*
  5295. * Initialize sgc->capacity such that even if we mess up the
  5296. * domains and no possible iteration will get us here, we won't
  5297. * die on a /0 trap.
  5298. */
  5299. sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
  5300. /*
  5301. * Make sure the first group of this domain contains the
  5302. * canonical balance cpu. Otherwise the sched_domain iteration
  5303. * breaks. See update_sg_lb_stats().
  5304. */
  5305. if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
  5306. group_balance_cpu(sg) == cpu)
  5307. groups = sg;
  5308. if (!first)
  5309. first = sg;
  5310. if (last)
  5311. last->next = sg;
  5312. last = sg;
  5313. last->next = first;
  5314. }
  5315. sd->groups = groups;
  5316. return 0;
  5317. fail:
  5318. free_sched_groups(first, 0);
  5319. return -ENOMEM;
  5320. }
  5321. static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
  5322. {
  5323. struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
  5324. struct sched_domain *child = sd->child;
  5325. if (child)
  5326. cpu = cpumask_first(sched_domain_span(child));
  5327. if (sg) {
  5328. *sg = *per_cpu_ptr(sdd->sg, cpu);
  5329. (*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
  5330. atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
  5331. }
  5332. return cpu;
  5333. }
  5334. /*
  5335. * build_sched_groups will build a circular linked list of the groups
  5336. * covered by the given span, and will set each group's ->cpumask correctly,
  5337. * and ->cpu_capacity to 0.
  5338. *
  5339. * Assumes the sched_domain tree is fully constructed
  5340. */
  5341. static int
  5342. build_sched_groups(struct sched_domain *sd, int cpu)
  5343. {
  5344. struct sched_group *first = NULL, *last = NULL;
  5345. struct sd_data *sdd = sd->private;
  5346. const struct cpumask *span = sched_domain_span(sd);
  5347. struct cpumask *covered;
  5348. int i;
  5349. get_group(cpu, sdd, &sd->groups);
  5350. atomic_inc(&sd->groups->ref);
  5351. if (cpu != cpumask_first(span))
  5352. return 0;
  5353. lockdep_assert_held(&sched_domains_mutex);
  5354. covered = sched_domains_tmpmask;
  5355. cpumask_clear(covered);
  5356. for_each_cpu(i, span) {
  5357. struct sched_group *sg;
  5358. int group, j;
  5359. if (cpumask_test_cpu(i, covered))
  5360. continue;
  5361. group = get_group(i, sdd, &sg);
  5362. cpumask_setall(sched_group_mask(sg));
  5363. for_each_cpu(j, span) {
  5364. if (get_group(j, sdd, NULL) != group)
  5365. continue;
  5366. cpumask_set_cpu(j, covered);
  5367. cpumask_set_cpu(j, sched_group_cpus(sg));
  5368. }
  5369. if (!first)
  5370. first = sg;
  5371. if (last)
  5372. last->next = sg;
  5373. last = sg;
  5374. }
  5375. last->next = first;
  5376. return 0;
  5377. }
  5378. /*
  5379. * Initialize sched groups cpu_capacity.
  5380. *
  5381. * cpu_capacity indicates the capacity of sched group, which is used while
  5382. * distributing the load between different sched groups in a sched domain.
  5383. * Typically cpu_capacity for all the groups in a sched domain will be same
  5384. * unless there are asymmetries in the topology. If there are asymmetries,
  5385. * group having more cpu_capacity will pickup more load compared to the
  5386. * group having less cpu_capacity.
  5387. */
  5388. static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
  5389. {
  5390. struct sched_group *sg = sd->groups;
  5391. WARN_ON(!sg);
  5392. do {
  5393. sg->group_weight = cpumask_weight(sched_group_cpus(sg));
  5394. sg = sg->next;
  5395. } while (sg != sd->groups);
  5396. if (cpu != group_balance_cpu(sg))
  5397. return;
  5398. update_group_capacity(sd, cpu);
  5399. atomic_set(&sg->sgc->nr_busy_cpus, sg->group_weight);
  5400. }
  5401. /*
  5402. * Initializers for schedule domains
  5403. * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
  5404. */
  5405. static int default_relax_domain_level = -1;
  5406. int sched_domain_level_max;
  5407. static int __init setup_relax_domain_level(char *str)
  5408. {
  5409. if (kstrtoint(str, 0, &default_relax_domain_level))
  5410. pr_warn("Unable to set relax_domain_level\n");
  5411. return 1;
  5412. }
  5413. __setup("relax_domain_level=", setup_relax_domain_level);
  5414. static void set_domain_attribute(struct sched_domain *sd,
  5415. struct sched_domain_attr *attr)
  5416. {
  5417. int request;
  5418. if (!attr || attr->relax_domain_level < 0) {
  5419. if (default_relax_domain_level < 0)
  5420. return;
  5421. else
  5422. request = default_relax_domain_level;
  5423. } else
  5424. request = attr->relax_domain_level;
  5425. if (request < sd->level) {
  5426. /* turn off idle balance on this domain */
  5427. sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
  5428. } else {
  5429. /* turn on idle balance on this domain */
  5430. sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
  5431. }
  5432. }
  5433. static void __sdt_free(const struct cpumask *cpu_map);
  5434. static int __sdt_alloc(const struct cpumask *cpu_map);
  5435. static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
  5436. const struct cpumask *cpu_map)
  5437. {
  5438. switch (what) {
  5439. case sa_rootdomain:
  5440. if (!atomic_read(&d->rd->refcount))
  5441. free_rootdomain(&d->rd->rcu); /* fall through */
  5442. case sa_sd:
  5443. free_percpu(d->sd); /* fall through */
  5444. case sa_sd_storage:
  5445. __sdt_free(cpu_map); /* fall through */
  5446. case sa_none:
  5447. break;
  5448. }
  5449. }
  5450. static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
  5451. const struct cpumask *cpu_map)
  5452. {
  5453. memset(d, 0, sizeof(*d));
  5454. if (__sdt_alloc(cpu_map))
  5455. return sa_sd_storage;
  5456. d->sd = alloc_percpu(struct sched_domain *);
  5457. if (!d->sd)
  5458. return sa_sd_storage;
  5459. d->rd = alloc_rootdomain();
  5460. if (!d->rd)
  5461. return sa_sd;
  5462. return sa_rootdomain;
  5463. }
  5464. /*
  5465. * NULL the sd_data elements we've used to build the sched_domain and
  5466. * sched_group structure so that the subsequent __free_domain_allocs()
  5467. * will not free the data we're using.
  5468. */
  5469. static void claim_allocations(int cpu, struct sched_domain *sd)
  5470. {
  5471. struct sd_data *sdd = sd->private;
  5472. WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
  5473. *per_cpu_ptr(sdd->sd, cpu) = NULL;
  5474. if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
  5475. *per_cpu_ptr(sdd->sg, cpu) = NULL;
  5476. if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
  5477. *per_cpu_ptr(sdd->sgc, cpu) = NULL;
  5478. }
  5479. #ifdef CONFIG_NUMA
  5480. static int sched_domains_numa_levels;
  5481. enum numa_topology_type sched_numa_topology_type;
  5482. static int *sched_domains_numa_distance;
  5483. int sched_max_numa_distance;
  5484. static struct cpumask ***sched_domains_numa_masks;
  5485. static int sched_domains_curr_level;
  5486. #endif
  5487. /*
  5488. * SD_flags allowed in topology descriptions.
  5489. *
  5490. * These flags are purely descriptive of the topology and do not prescribe
  5491. * behaviour. Behaviour is artificial and mapped in the below sd_init()
  5492. * function:
  5493. *
  5494. * SD_SHARE_CPUCAPACITY - describes SMT topologies
  5495. * SD_SHARE_PKG_RESOURCES - describes shared caches
  5496. * SD_NUMA - describes NUMA topologies
  5497. * SD_SHARE_POWERDOMAIN - describes shared power domain
  5498. * SD_ASYM_CPUCAPACITY - describes mixed capacity topologies
  5499. *
  5500. * Odd one out, which beside describing the topology has a quirk also
  5501. * prescribes the desired behaviour that goes along with it:
  5502. *
  5503. * SD_ASYM_PACKING - describes SMT quirks
  5504. */
  5505. #define TOPOLOGY_SD_FLAGS \
  5506. (SD_SHARE_CPUCAPACITY | \
  5507. SD_SHARE_PKG_RESOURCES | \
  5508. SD_NUMA | \
  5509. SD_ASYM_PACKING | \
  5510. SD_ASYM_CPUCAPACITY | \
  5511. SD_SHARE_POWERDOMAIN)
  5512. static struct sched_domain *
  5513. sd_init(struct sched_domain_topology_level *tl,
  5514. struct sched_domain *child, int cpu)
  5515. {
  5516. struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
  5517. int sd_weight, sd_flags = 0;
  5518. #ifdef CONFIG_NUMA
  5519. /*
  5520. * Ugly hack to pass state to sd_numa_mask()...
  5521. */
  5522. sched_domains_curr_level = tl->numa_level;
  5523. #endif
  5524. sd_weight = cpumask_weight(tl->mask(cpu));
  5525. if (tl->sd_flags)
  5526. sd_flags = (*tl->sd_flags)();
  5527. if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
  5528. "wrong sd_flags in topology description\n"))
  5529. sd_flags &= ~TOPOLOGY_SD_FLAGS;
  5530. *sd = (struct sched_domain){
  5531. .min_interval = sd_weight,
  5532. .max_interval = 2*sd_weight,
  5533. .busy_factor = 32,
  5534. .imbalance_pct = 125,
  5535. .cache_nice_tries = 0,
  5536. .busy_idx = 0,
  5537. .idle_idx = 0,
  5538. .newidle_idx = 0,
  5539. .wake_idx = 0,
  5540. .forkexec_idx = 0,
  5541. .flags = 1*SD_LOAD_BALANCE
  5542. | 1*SD_BALANCE_NEWIDLE
  5543. | 1*SD_BALANCE_EXEC
  5544. | 1*SD_BALANCE_FORK
  5545. | 0*SD_BALANCE_WAKE
  5546. | 1*SD_WAKE_AFFINE
  5547. | 0*SD_SHARE_CPUCAPACITY
  5548. | 0*SD_SHARE_PKG_RESOURCES
  5549. | 0*SD_SERIALIZE
  5550. | 0*SD_PREFER_SIBLING
  5551. | 0*SD_NUMA
  5552. | sd_flags
  5553. ,
  5554. .last_balance = jiffies,
  5555. .balance_interval = sd_weight,
  5556. .smt_gain = 0,
  5557. .max_newidle_lb_cost = 0,
  5558. .next_decay_max_lb_cost = jiffies,
  5559. .child = child,
  5560. #ifdef CONFIG_SCHED_DEBUG
  5561. .name = tl->name,
  5562. #endif
  5563. };
  5564. /*
  5565. * Convert topological properties into behaviour.
  5566. */
  5567. if (sd->flags & SD_ASYM_CPUCAPACITY) {
  5568. struct sched_domain *t = sd;
  5569. for_each_lower_domain(t)
  5570. t->flags |= SD_BALANCE_WAKE;
  5571. }
  5572. if (sd->flags & SD_SHARE_CPUCAPACITY) {
  5573. sd->flags |= SD_PREFER_SIBLING;
  5574. sd->imbalance_pct = 110;
  5575. sd->smt_gain = 1178; /* ~15% */
  5576. } else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
  5577. sd->imbalance_pct = 117;
  5578. sd->cache_nice_tries = 1;
  5579. sd->busy_idx = 2;
  5580. #ifdef CONFIG_NUMA
  5581. } else if (sd->flags & SD_NUMA) {
  5582. sd->cache_nice_tries = 2;
  5583. sd->busy_idx = 3;
  5584. sd->idle_idx = 2;
  5585. sd->flags |= SD_SERIALIZE;
  5586. if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
  5587. sd->flags &= ~(SD_BALANCE_EXEC |
  5588. SD_BALANCE_FORK |
  5589. SD_WAKE_AFFINE);
  5590. }
  5591. #endif
  5592. } else {
  5593. sd->flags |= SD_PREFER_SIBLING;
  5594. sd->cache_nice_tries = 1;
  5595. sd->busy_idx = 2;
  5596. sd->idle_idx = 1;
  5597. }
  5598. sd->private = &tl->data;
  5599. return sd;
  5600. }
  5601. /*
  5602. * Topology list, bottom-up.
  5603. */
  5604. static struct sched_domain_topology_level default_topology[] = {
  5605. #ifdef CONFIG_SCHED_SMT
  5606. { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
  5607. #endif
  5608. #ifdef CONFIG_SCHED_MC
  5609. { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
  5610. #endif
  5611. { cpu_cpu_mask, SD_INIT_NAME(DIE) },
  5612. { NULL, },
  5613. };
  5614. static struct sched_domain_topology_level *sched_domain_topology =
  5615. default_topology;
  5616. #define for_each_sd_topology(tl) \
  5617. for (tl = sched_domain_topology; tl->mask; tl++)
  5618. void set_sched_topology(struct sched_domain_topology_level *tl)
  5619. {
  5620. if (WARN_ON_ONCE(sched_smp_initialized))
  5621. return;
  5622. sched_domain_topology = tl;
  5623. }
  5624. #ifdef CONFIG_NUMA
  5625. static const struct cpumask *sd_numa_mask(int cpu)
  5626. {
  5627. return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
  5628. }
  5629. static void sched_numa_warn(const char *str)
  5630. {
  5631. static int done = false;
  5632. int i,j;
  5633. if (done)
  5634. return;
  5635. done = true;
  5636. printk(KERN_WARNING "ERROR: %s\n\n", str);
  5637. for (i = 0; i < nr_node_ids; i++) {
  5638. printk(KERN_WARNING " ");
  5639. for (j = 0; j < nr_node_ids; j++)
  5640. printk(KERN_CONT "%02d ", node_distance(i,j));
  5641. printk(KERN_CONT "\n");
  5642. }
  5643. printk(KERN_WARNING "\n");
  5644. }
  5645. bool find_numa_distance(int distance)
  5646. {
  5647. int i;
  5648. if (distance == node_distance(0, 0))
  5649. return true;
  5650. for (i = 0; i < sched_domains_numa_levels; i++) {
  5651. if (sched_domains_numa_distance[i] == distance)
  5652. return true;
  5653. }
  5654. return false;
  5655. }
  5656. /*
  5657. * A system can have three types of NUMA topology:
  5658. * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
  5659. * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
  5660. * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
  5661. *
  5662. * The difference between a glueless mesh topology and a backplane
  5663. * topology lies in whether communication between not directly
  5664. * connected nodes goes through intermediary nodes (where programs
  5665. * could run), or through backplane controllers. This affects
  5666. * placement of programs.
  5667. *
  5668. * The type of topology can be discerned with the following tests:
  5669. * - If the maximum distance between any nodes is 1 hop, the system
  5670. * is directly connected.
  5671. * - If for two nodes A and B, located N > 1 hops away from each other,
  5672. * there is an intermediary node C, which is < N hops away from both
  5673. * nodes A and B, the system is a glueless mesh.
  5674. */
  5675. static void init_numa_topology_type(void)
  5676. {
  5677. int a, b, c, n;
  5678. n = sched_max_numa_distance;
  5679. if (sched_domains_numa_levels <= 1) {
  5680. sched_numa_topology_type = NUMA_DIRECT;
  5681. return;
  5682. }
  5683. for_each_online_node(a) {
  5684. for_each_online_node(b) {
  5685. /* Find two nodes furthest removed from each other. */
  5686. if (node_distance(a, b) < n)
  5687. continue;
  5688. /* Is there an intermediary node between a and b? */
  5689. for_each_online_node(c) {
  5690. if (node_distance(a, c) < n &&
  5691. node_distance(b, c) < n) {
  5692. sched_numa_topology_type =
  5693. NUMA_GLUELESS_MESH;
  5694. return;
  5695. }
  5696. }
  5697. sched_numa_topology_type = NUMA_BACKPLANE;
  5698. return;
  5699. }
  5700. }
  5701. }
  5702. static void sched_init_numa(void)
  5703. {
  5704. int next_distance, curr_distance = node_distance(0, 0);
  5705. struct sched_domain_topology_level *tl;
  5706. int level = 0;
  5707. int i, j, k;
  5708. sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
  5709. if (!sched_domains_numa_distance)
  5710. return;
  5711. /*
  5712. * O(nr_nodes^2) deduplicating selection sort -- in order to find the
  5713. * unique distances in the node_distance() table.
  5714. *
  5715. * Assumes node_distance(0,j) includes all distances in
  5716. * node_distance(i,j) in order to avoid cubic time.
  5717. */
  5718. next_distance = curr_distance;
  5719. for (i = 0; i < nr_node_ids; i++) {
  5720. for (j = 0; j < nr_node_ids; j++) {
  5721. for (k = 0; k < nr_node_ids; k++) {
  5722. int distance = node_distance(i, k);
  5723. if (distance > curr_distance &&
  5724. (distance < next_distance ||
  5725. next_distance == curr_distance))
  5726. next_distance = distance;
  5727. /*
  5728. * While not a strong assumption it would be nice to know
  5729. * about cases where if node A is connected to B, B is not
  5730. * equally connected to A.
  5731. */
  5732. if (sched_debug() && node_distance(k, i) != distance)
  5733. sched_numa_warn("Node-distance not symmetric");
  5734. if (sched_debug() && i && !find_numa_distance(distance))
  5735. sched_numa_warn("Node-0 not representative");
  5736. }
  5737. if (next_distance != curr_distance) {
  5738. sched_domains_numa_distance[level++] = next_distance;
  5739. sched_domains_numa_levels = level;
  5740. curr_distance = next_distance;
  5741. } else break;
  5742. }
  5743. /*
  5744. * In case of sched_debug() we verify the above assumption.
  5745. */
  5746. if (!sched_debug())
  5747. break;
  5748. }
  5749. if (!level)
  5750. return;
  5751. /*
  5752. * 'level' contains the number of unique distances, excluding the
  5753. * identity distance node_distance(i,i).
  5754. *
  5755. * The sched_domains_numa_distance[] array includes the actual distance
  5756. * numbers.
  5757. */
  5758. /*
  5759. * Here, we should temporarily reset sched_domains_numa_levels to 0.
  5760. * If it fails to allocate memory for array sched_domains_numa_masks[][],
  5761. * the array will contain less then 'level' members. This could be
  5762. * dangerous when we use it to iterate array sched_domains_numa_masks[][]
  5763. * in other functions.
  5764. *
  5765. * We reset it to 'level' at the end of this function.
  5766. */
  5767. sched_domains_numa_levels = 0;
  5768. sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
  5769. if (!sched_domains_numa_masks)
  5770. return;
  5771. /*
  5772. * Now for each level, construct a mask per node which contains all
  5773. * cpus of nodes that are that many hops away from us.
  5774. */
  5775. for (i = 0; i < level; i++) {
  5776. sched_domains_numa_masks[i] =
  5777. kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
  5778. if (!sched_domains_numa_masks[i])
  5779. return;
  5780. for (j = 0; j < nr_node_ids; j++) {
  5781. struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
  5782. if (!mask)
  5783. return;
  5784. sched_domains_numa_masks[i][j] = mask;
  5785. for_each_node(k) {
  5786. if (node_distance(j, k) > sched_domains_numa_distance[i])
  5787. continue;
  5788. cpumask_or(mask, mask, cpumask_of_node(k));
  5789. }
  5790. }
  5791. }
  5792. /* Compute default topology size */
  5793. for (i = 0; sched_domain_topology[i].mask; i++);
  5794. tl = kzalloc((i + level + 1) *
  5795. sizeof(struct sched_domain_topology_level), GFP_KERNEL);
  5796. if (!tl)
  5797. return;
  5798. /*
  5799. * Copy the default topology bits..
  5800. */
  5801. for (i = 0; sched_domain_topology[i].mask; i++)
  5802. tl[i] = sched_domain_topology[i];
  5803. /*
  5804. * .. and append 'j' levels of NUMA goodness.
  5805. */
  5806. for (j = 0; j < level; i++, j++) {
  5807. tl[i] = (struct sched_domain_topology_level){
  5808. .mask = sd_numa_mask,
  5809. .sd_flags = cpu_numa_flags,
  5810. .flags = SDTL_OVERLAP,
  5811. .numa_level = j,
  5812. SD_INIT_NAME(NUMA)
  5813. };
  5814. }
  5815. sched_domain_topology = tl;
  5816. sched_domains_numa_levels = level;
  5817. sched_max_numa_distance = sched_domains_numa_distance[level - 1];
  5818. init_numa_topology_type();
  5819. }
  5820. static void sched_domains_numa_masks_set(unsigned int cpu)
  5821. {
  5822. int node = cpu_to_node(cpu);
  5823. int i, j;
  5824. for (i = 0; i < sched_domains_numa_levels; i++) {
  5825. for (j = 0; j < nr_node_ids; j++) {
  5826. if (node_distance(j, node) <= sched_domains_numa_distance[i])
  5827. cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
  5828. }
  5829. }
  5830. }
  5831. static void sched_domains_numa_masks_clear(unsigned int cpu)
  5832. {
  5833. int i, j;
  5834. for (i = 0; i < sched_domains_numa_levels; i++) {
  5835. for (j = 0; j < nr_node_ids; j++)
  5836. cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
  5837. }
  5838. }
  5839. #else
  5840. static inline void sched_init_numa(void) { }
  5841. static void sched_domains_numa_masks_set(unsigned int cpu) { }
  5842. static void sched_domains_numa_masks_clear(unsigned int cpu) { }
  5843. #endif /* CONFIG_NUMA */
  5844. static int __sdt_alloc(const struct cpumask *cpu_map)
  5845. {
  5846. struct sched_domain_topology_level *tl;
  5847. int j;
  5848. for_each_sd_topology(tl) {
  5849. struct sd_data *sdd = &tl->data;
  5850. sdd->sd = alloc_percpu(struct sched_domain *);
  5851. if (!sdd->sd)
  5852. return -ENOMEM;
  5853. sdd->sg = alloc_percpu(struct sched_group *);
  5854. if (!sdd->sg)
  5855. return -ENOMEM;
  5856. sdd->sgc = alloc_percpu(struct sched_group_capacity *);
  5857. if (!sdd->sgc)
  5858. return -ENOMEM;
  5859. for_each_cpu(j, cpu_map) {
  5860. struct sched_domain *sd;
  5861. struct sched_group *sg;
  5862. struct sched_group_capacity *sgc;
  5863. sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
  5864. GFP_KERNEL, cpu_to_node(j));
  5865. if (!sd)
  5866. return -ENOMEM;
  5867. *per_cpu_ptr(sdd->sd, j) = sd;
  5868. sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
  5869. GFP_KERNEL, cpu_to_node(j));
  5870. if (!sg)
  5871. return -ENOMEM;
  5872. sg->next = sg;
  5873. *per_cpu_ptr(sdd->sg, j) = sg;
  5874. sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
  5875. GFP_KERNEL, cpu_to_node(j));
  5876. if (!sgc)
  5877. return -ENOMEM;
  5878. *per_cpu_ptr(sdd->sgc, j) = sgc;
  5879. }
  5880. }
  5881. return 0;
  5882. }
  5883. static void __sdt_free(const struct cpumask *cpu_map)
  5884. {
  5885. struct sched_domain_topology_level *tl;
  5886. int j;
  5887. for_each_sd_topology(tl) {
  5888. struct sd_data *sdd = &tl->data;
  5889. for_each_cpu(j, cpu_map) {
  5890. struct sched_domain *sd;
  5891. if (sdd->sd) {
  5892. sd = *per_cpu_ptr(sdd->sd, j);
  5893. if (sd && (sd->flags & SD_OVERLAP))
  5894. free_sched_groups(sd->groups, 0);
  5895. kfree(*per_cpu_ptr(sdd->sd, j));
  5896. }
  5897. if (sdd->sg)
  5898. kfree(*per_cpu_ptr(sdd->sg, j));
  5899. if (sdd->sgc)
  5900. kfree(*per_cpu_ptr(sdd->sgc, j));
  5901. }
  5902. free_percpu(sdd->sd);
  5903. sdd->sd = NULL;
  5904. free_percpu(sdd->sg);
  5905. sdd->sg = NULL;
  5906. free_percpu(sdd->sgc);
  5907. sdd->sgc = NULL;
  5908. }
  5909. }
  5910. struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
  5911. const struct cpumask *cpu_map, struct sched_domain_attr *attr,
  5912. struct sched_domain *child, int cpu)
  5913. {
  5914. struct sched_domain *sd = sd_init(tl, child, cpu);
  5915. cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
  5916. if (child) {
  5917. sd->level = child->level + 1;
  5918. sched_domain_level_max = max(sched_domain_level_max, sd->level);
  5919. child->parent = sd;
  5920. if (!cpumask_subset(sched_domain_span(child),
  5921. sched_domain_span(sd))) {
  5922. pr_err("BUG: arch topology borken\n");
  5923. #ifdef CONFIG_SCHED_DEBUG
  5924. pr_err(" the %s domain not a subset of the %s domain\n",
  5925. child->name, sd->name);
  5926. #endif
  5927. /* Fixup, ensure @sd has at least @child cpus. */
  5928. cpumask_or(sched_domain_span(sd),
  5929. sched_domain_span(sd),
  5930. sched_domain_span(child));
  5931. }
  5932. }
  5933. set_domain_attribute(sd, attr);
  5934. return sd;
  5935. }
  5936. /*
  5937. * Build sched domains for a given set of cpus and attach the sched domains
  5938. * to the individual cpus
  5939. */
  5940. static int build_sched_domains(const struct cpumask *cpu_map,
  5941. struct sched_domain_attr *attr)
  5942. {
  5943. enum s_alloc alloc_state;
  5944. struct sched_domain *sd;
  5945. struct s_data d;
  5946. struct rq *rq = NULL;
  5947. int i, ret = -ENOMEM;
  5948. alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
  5949. if (alloc_state != sa_rootdomain)
  5950. goto error;
  5951. /* Set up domains for cpus specified by the cpu_map. */
  5952. for_each_cpu(i, cpu_map) {
  5953. struct sched_domain_topology_level *tl;
  5954. sd = NULL;
  5955. for_each_sd_topology(tl) {
  5956. sd = build_sched_domain(tl, cpu_map, attr, sd, i);
  5957. if (tl == sched_domain_topology)
  5958. *per_cpu_ptr(d.sd, i) = sd;
  5959. if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
  5960. sd->flags |= SD_OVERLAP;
  5961. if (cpumask_equal(cpu_map, sched_domain_span(sd)))
  5962. break;
  5963. }
  5964. }
  5965. /* Build the groups for the domains */
  5966. for_each_cpu(i, cpu_map) {
  5967. for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
  5968. sd->span_weight = cpumask_weight(sched_domain_span(sd));
  5969. if (sd->flags & SD_OVERLAP) {
  5970. if (build_overlap_sched_groups(sd, i))
  5971. goto error;
  5972. } else {
  5973. if (build_sched_groups(sd, i))
  5974. goto error;
  5975. }
  5976. }
  5977. }
  5978. /* Calculate CPU capacity for physical packages and nodes */
  5979. for (i = nr_cpumask_bits-1; i >= 0; i--) {
  5980. if (!cpumask_test_cpu(i, cpu_map))
  5981. continue;
  5982. for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
  5983. claim_allocations(i, sd);
  5984. init_sched_groups_capacity(i, sd);
  5985. }
  5986. }
  5987. /* Attach the domains */
  5988. rcu_read_lock();
  5989. for_each_cpu(i, cpu_map) {
  5990. rq = cpu_rq(i);
  5991. sd = *per_cpu_ptr(d.sd, i);
  5992. /* Use READ_ONCE()/WRITE_ONCE() to avoid load/store tearing: */
  5993. if (rq->cpu_capacity_orig > READ_ONCE(d.rd->max_cpu_capacity))
  5994. WRITE_ONCE(d.rd->max_cpu_capacity, rq->cpu_capacity_orig);
  5995. cpu_attach_domain(sd, d.rd, i);
  5996. }
  5997. rcu_read_unlock();
  5998. if (rq && sched_debug_enabled) {
  5999. pr_info("span: %*pbl (max cpu_capacity = %lu)\n",
  6000. cpumask_pr_args(cpu_map), rq->rd->max_cpu_capacity);
  6001. }
  6002. ret = 0;
  6003. error:
  6004. __free_domain_allocs(&d, alloc_state, cpu_map);
  6005. return ret;
  6006. }
  6007. static cpumask_var_t *doms_cur; /* current sched domains */
  6008. static int ndoms_cur; /* number of sched domains in 'doms_cur' */
  6009. static struct sched_domain_attr *dattr_cur;
  6010. /* attribues of custom domains in 'doms_cur' */
  6011. /*
  6012. * Special case: If a kmalloc of a doms_cur partition (array of
  6013. * cpumask) fails, then fallback to a single sched domain,
  6014. * as determined by the single cpumask fallback_doms.
  6015. */
  6016. static cpumask_var_t fallback_doms;
  6017. /*
  6018. * arch_update_cpu_topology lets virtualized architectures update the
  6019. * cpu core maps. It is supposed to return 1 if the topology changed
  6020. * or 0 if it stayed the same.
  6021. */
  6022. int __weak arch_update_cpu_topology(void)
  6023. {
  6024. return 0;
  6025. }
  6026. cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
  6027. {
  6028. int i;
  6029. cpumask_var_t *doms;
  6030. doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
  6031. if (!doms)
  6032. return NULL;
  6033. for (i = 0; i < ndoms; i++) {
  6034. if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
  6035. free_sched_domains(doms, i);
  6036. return NULL;
  6037. }
  6038. }
  6039. return doms;
  6040. }
  6041. void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
  6042. {
  6043. unsigned int i;
  6044. for (i = 0; i < ndoms; i++)
  6045. free_cpumask_var(doms[i]);
  6046. kfree(doms);
  6047. }
  6048. /*
  6049. * Set up scheduler domains and groups. Callers must hold the hotplug lock.
  6050. * For now this just excludes isolated cpus, but could be used to
  6051. * exclude other special cases in the future.
  6052. */
  6053. static int init_sched_domains(const struct cpumask *cpu_map)
  6054. {
  6055. int err;
  6056. arch_update_cpu_topology();
  6057. ndoms_cur = 1;
  6058. doms_cur = alloc_sched_domains(ndoms_cur);
  6059. if (!doms_cur)
  6060. doms_cur = &fallback_doms;
  6061. cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
  6062. err = build_sched_domains(doms_cur[0], NULL);
  6063. register_sched_domain_sysctl();
  6064. return err;
  6065. }
  6066. /*
  6067. * Detach sched domains from a group of cpus specified in cpu_map
  6068. * These cpus will now be attached to the NULL domain
  6069. */
  6070. static void detach_destroy_domains(const struct cpumask *cpu_map)
  6071. {
  6072. int i;
  6073. rcu_read_lock();
  6074. for_each_cpu(i, cpu_map)
  6075. cpu_attach_domain(NULL, &def_root_domain, i);
  6076. rcu_read_unlock();
  6077. }
  6078. /* handle null as "default" */
  6079. static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
  6080. struct sched_domain_attr *new, int idx_new)
  6081. {
  6082. struct sched_domain_attr tmp;
  6083. /* fast path */
  6084. if (!new && !cur)
  6085. return 1;
  6086. tmp = SD_ATTR_INIT;
  6087. return !memcmp(cur ? (cur + idx_cur) : &tmp,
  6088. new ? (new + idx_new) : &tmp,
  6089. sizeof(struct sched_domain_attr));
  6090. }
  6091. /*
  6092. * Partition sched domains as specified by the 'ndoms_new'
  6093. * cpumasks in the array doms_new[] of cpumasks. This compares
  6094. * doms_new[] to the current sched domain partitioning, doms_cur[].
  6095. * It destroys each deleted domain and builds each new domain.
  6096. *
  6097. * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
  6098. * The masks don't intersect (don't overlap.) We should setup one
  6099. * sched domain for each mask. CPUs not in any of the cpumasks will
  6100. * not be load balanced. If the same cpumask appears both in the
  6101. * current 'doms_cur' domains and in the new 'doms_new', we can leave
  6102. * it as it is.
  6103. *
  6104. * The passed in 'doms_new' should be allocated using
  6105. * alloc_sched_domains. This routine takes ownership of it and will
  6106. * free_sched_domains it when done with it. If the caller failed the
  6107. * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
  6108. * and partition_sched_domains() will fallback to the single partition
  6109. * 'fallback_doms', it also forces the domains to be rebuilt.
  6110. *
  6111. * If doms_new == NULL it will be replaced with cpu_online_mask.
  6112. * ndoms_new == 0 is a special case for destroying existing domains,
  6113. * and it will not create the default domain.
  6114. *
  6115. * Call with hotplug lock held
  6116. */
  6117. void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
  6118. struct sched_domain_attr *dattr_new)
  6119. {
  6120. int i, j, n;
  6121. int new_topology;
  6122. mutex_lock(&sched_domains_mutex);
  6123. /* always unregister in case we don't destroy any domains */
  6124. unregister_sched_domain_sysctl();
  6125. /* Let architecture update cpu core mappings. */
  6126. new_topology = arch_update_cpu_topology();
  6127. n = doms_new ? ndoms_new : 0;
  6128. /* Destroy deleted domains */
  6129. for (i = 0; i < ndoms_cur; i++) {
  6130. for (j = 0; j < n && !new_topology; j++) {
  6131. if (cpumask_equal(doms_cur[i], doms_new[j])
  6132. && dattrs_equal(dattr_cur, i, dattr_new, j))
  6133. goto match1;
  6134. }
  6135. /* no match - a current sched domain not in new doms_new[] */
  6136. detach_destroy_domains(doms_cur[i]);
  6137. match1:
  6138. ;
  6139. }
  6140. n = ndoms_cur;
  6141. if (doms_new == NULL) {
  6142. n = 0;
  6143. doms_new = &fallback_doms;
  6144. cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
  6145. WARN_ON_ONCE(dattr_new);
  6146. }
  6147. /* Build new domains */
  6148. for (i = 0; i < ndoms_new; i++) {
  6149. for (j = 0; j < n && !new_topology; j++) {
  6150. if (cpumask_equal(doms_new[i], doms_cur[j])
  6151. && dattrs_equal(dattr_new, i, dattr_cur, j))
  6152. goto match2;
  6153. }
  6154. /* no match - add a new doms_new */
  6155. build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
  6156. match2:
  6157. ;
  6158. }
  6159. /* Remember the new sched domains */
  6160. if (doms_cur != &fallback_doms)
  6161. free_sched_domains(doms_cur, ndoms_cur);
  6162. kfree(dattr_cur); /* kfree(NULL) is safe */
  6163. doms_cur = doms_new;
  6164. dattr_cur = dattr_new;
  6165. ndoms_cur = ndoms_new;
  6166. register_sched_domain_sysctl();
  6167. mutex_unlock(&sched_domains_mutex);
  6168. }
  6169. static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
  6170. /*
  6171. * Update cpusets according to cpu_active mask. If cpusets are
  6172. * disabled, cpuset_update_active_cpus() becomes a simple wrapper
  6173. * around partition_sched_domains().
  6174. *
  6175. * If we come here as part of a suspend/resume, don't touch cpusets because we
  6176. * want to restore it back to its original state upon resume anyway.
  6177. */
  6178. static void cpuset_cpu_active(void)
  6179. {
  6180. if (cpuhp_tasks_frozen) {
  6181. /*
  6182. * num_cpus_frozen tracks how many CPUs are involved in suspend
  6183. * resume sequence. As long as this is not the last online
  6184. * operation in the resume sequence, just build a single sched
  6185. * domain, ignoring cpusets.
  6186. */
  6187. num_cpus_frozen--;
  6188. if (likely(num_cpus_frozen)) {
  6189. partition_sched_domains(1, NULL, NULL);
  6190. return;
  6191. }
  6192. /*
  6193. * This is the last CPU online operation. So fall through and
  6194. * restore the original sched domains by considering the
  6195. * cpuset configurations.
  6196. */
  6197. }
  6198. cpuset_update_active_cpus(true);
  6199. }
  6200. static int cpuset_cpu_inactive(unsigned int cpu)
  6201. {
  6202. unsigned long flags;
  6203. struct dl_bw *dl_b;
  6204. bool overflow;
  6205. int cpus;
  6206. if (!cpuhp_tasks_frozen) {
  6207. rcu_read_lock_sched();
  6208. dl_b = dl_bw_of(cpu);
  6209. raw_spin_lock_irqsave(&dl_b->lock, flags);
  6210. cpus = dl_bw_cpus(cpu);
  6211. overflow = __dl_overflow(dl_b, cpus, 0, 0);
  6212. raw_spin_unlock_irqrestore(&dl_b->lock, flags);
  6213. rcu_read_unlock_sched();
  6214. if (overflow)
  6215. return -EBUSY;
  6216. cpuset_update_active_cpus(false);
  6217. } else {
  6218. num_cpus_frozen++;
  6219. partition_sched_domains(1, NULL, NULL);
  6220. }
  6221. return 0;
  6222. }
  6223. int sched_cpu_activate(unsigned int cpu)
  6224. {
  6225. struct rq *rq = cpu_rq(cpu);
  6226. unsigned long flags;
  6227. set_cpu_active(cpu, true);
  6228. if (sched_smp_initialized) {
  6229. sched_domains_numa_masks_set(cpu);
  6230. cpuset_cpu_active();
  6231. }
  6232. /*
  6233. * Put the rq online, if not already. This happens:
  6234. *
  6235. * 1) In the early boot process, because we build the real domains
  6236. * after all cpus have been brought up.
  6237. *
  6238. * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
  6239. * domains.
  6240. */
  6241. raw_spin_lock_irqsave(&rq->lock, flags);
  6242. if (rq->rd) {
  6243. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  6244. set_rq_online(rq);
  6245. }
  6246. raw_spin_unlock_irqrestore(&rq->lock, flags);
  6247. update_max_interval();
  6248. return 0;
  6249. }
  6250. int sched_cpu_deactivate(unsigned int cpu)
  6251. {
  6252. int ret;
  6253. set_cpu_active(cpu, false);
  6254. /*
  6255. * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
  6256. * users of this state to go away such that all new such users will
  6257. * observe it.
  6258. *
  6259. * For CONFIG_PREEMPT we have preemptible RCU and its sync_rcu() might
  6260. * not imply sync_sched(), so wait for both.
  6261. *
  6262. * Do sync before park smpboot threads to take care the rcu boost case.
  6263. */
  6264. if (IS_ENABLED(CONFIG_PREEMPT))
  6265. synchronize_rcu_mult(call_rcu, call_rcu_sched);
  6266. else
  6267. synchronize_rcu();
  6268. if (!sched_smp_initialized)
  6269. return 0;
  6270. ret = cpuset_cpu_inactive(cpu);
  6271. if (ret) {
  6272. set_cpu_active(cpu, true);
  6273. return ret;
  6274. }
  6275. sched_domains_numa_masks_clear(cpu);
  6276. return 0;
  6277. }
  6278. static void sched_rq_cpu_starting(unsigned int cpu)
  6279. {
  6280. struct rq *rq = cpu_rq(cpu);
  6281. rq->calc_load_update = calc_load_update;
  6282. update_max_interval();
  6283. }
  6284. int sched_cpu_starting(unsigned int cpu)
  6285. {
  6286. set_cpu_rq_start_time(cpu);
  6287. sched_rq_cpu_starting(cpu);
  6288. return 0;
  6289. }
  6290. #ifdef CONFIG_HOTPLUG_CPU
  6291. int sched_cpu_dying(unsigned int cpu)
  6292. {
  6293. struct rq *rq = cpu_rq(cpu);
  6294. unsigned long flags;
  6295. /* Handle pending wakeups and then migrate everything off */
  6296. sched_ttwu_pending();
  6297. raw_spin_lock_irqsave(&rq->lock, flags);
  6298. if (rq->rd) {
  6299. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  6300. set_rq_offline(rq);
  6301. }
  6302. migrate_tasks(rq);
  6303. BUG_ON(rq->nr_running != 1);
  6304. raw_spin_unlock_irqrestore(&rq->lock, flags);
  6305. calc_load_migrate(rq);
  6306. update_max_interval();
  6307. nohz_balance_exit_idle(cpu);
  6308. hrtick_clear(rq);
  6309. return 0;
  6310. }
  6311. #endif
  6312. void __init sched_init_smp(void)
  6313. {
  6314. cpumask_var_t non_isolated_cpus;
  6315. alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
  6316. alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
  6317. sched_init_numa();
  6318. /*
  6319. * There's no userspace yet to cause hotplug operations; hence all the
  6320. * cpu masks are stable and all blatant races in the below code cannot
  6321. * happen.
  6322. */
  6323. mutex_lock(&sched_domains_mutex);
  6324. init_sched_domains(cpu_active_mask);
  6325. cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
  6326. if (cpumask_empty(non_isolated_cpus))
  6327. cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
  6328. mutex_unlock(&sched_domains_mutex);
  6329. /* Move init over to a non-isolated CPU */
  6330. if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
  6331. BUG();
  6332. sched_init_granularity();
  6333. free_cpumask_var(non_isolated_cpus);
  6334. init_sched_rt_class();
  6335. init_sched_dl_class();
  6336. sched_smp_initialized = true;
  6337. }
  6338. static int __init migration_init(void)
  6339. {
  6340. sched_rq_cpu_starting(smp_processor_id());
  6341. return 0;
  6342. }
  6343. early_initcall(migration_init);
  6344. #else
  6345. void __init sched_init_smp(void)
  6346. {
  6347. sched_init_granularity();
  6348. }
  6349. #endif /* CONFIG_SMP */
  6350. int in_sched_functions(unsigned long addr)
  6351. {
  6352. return in_lock_functions(addr) ||
  6353. (addr >= (unsigned long)__sched_text_start
  6354. && addr < (unsigned long)__sched_text_end);
  6355. }
  6356. #ifdef CONFIG_CGROUP_SCHED
  6357. /*
  6358. * Default task group.
  6359. * Every task in system belongs to this group at bootup.
  6360. */
  6361. struct task_group root_task_group;
  6362. LIST_HEAD(task_groups);
  6363. /* Cacheline aligned slab cache for task_group */
  6364. static struct kmem_cache *task_group_cache __read_mostly;
  6365. #endif
  6366. DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
  6367. void __init sched_init(void)
  6368. {
  6369. int i, j;
  6370. unsigned long alloc_size = 0, ptr;
  6371. #ifdef CONFIG_FAIR_GROUP_SCHED
  6372. alloc_size += 2 * nr_cpu_ids * sizeof(void **);
  6373. #endif
  6374. #ifdef CONFIG_RT_GROUP_SCHED
  6375. alloc_size += 2 * nr_cpu_ids * sizeof(void **);
  6376. #endif
  6377. if (alloc_size) {
  6378. ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
  6379. #ifdef CONFIG_FAIR_GROUP_SCHED
  6380. root_task_group.se = (struct sched_entity **)ptr;
  6381. ptr += nr_cpu_ids * sizeof(void **);
  6382. root_task_group.cfs_rq = (struct cfs_rq **)ptr;
  6383. ptr += nr_cpu_ids * sizeof(void **);
  6384. #endif /* CONFIG_FAIR_GROUP_SCHED */
  6385. #ifdef CONFIG_RT_GROUP_SCHED
  6386. root_task_group.rt_se = (struct sched_rt_entity **)ptr;
  6387. ptr += nr_cpu_ids * sizeof(void **);
  6388. root_task_group.rt_rq = (struct rt_rq **)ptr;
  6389. ptr += nr_cpu_ids * sizeof(void **);
  6390. #endif /* CONFIG_RT_GROUP_SCHED */
  6391. }
  6392. #ifdef CONFIG_CPUMASK_OFFSTACK
  6393. for_each_possible_cpu(i) {
  6394. per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
  6395. cpumask_size(), GFP_KERNEL, cpu_to_node(i));
  6396. }
  6397. #endif /* CONFIG_CPUMASK_OFFSTACK */
  6398. init_rt_bandwidth(&def_rt_bandwidth,
  6399. global_rt_period(), global_rt_runtime());
  6400. init_dl_bandwidth(&def_dl_bandwidth,
  6401. global_rt_period(), global_rt_runtime());
  6402. #ifdef CONFIG_SMP
  6403. init_defrootdomain();
  6404. #endif
  6405. #ifdef CONFIG_RT_GROUP_SCHED
  6406. init_rt_bandwidth(&root_task_group.rt_bandwidth,
  6407. global_rt_period(), global_rt_runtime());
  6408. #endif /* CONFIG_RT_GROUP_SCHED */
  6409. #ifdef CONFIG_CGROUP_SCHED
  6410. task_group_cache = KMEM_CACHE(task_group, 0);
  6411. list_add(&root_task_group.list, &task_groups);
  6412. INIT_LIST_HEAD(&root_task_group.children);
  6413. INIT_LIST_HEAD(&root_task_group.siblings);
  6414. autogroup_init(&init_task);
  6415. #endif /* CONFIG_CGROUP_SCHED */
  6416. for_each_possible_cpu(i) {
  6417. struct rq *rq;
  6418. rq = cpu_rq(i);
  6419. raw_spin_lock_init(&rq->lock);
  6420. rq->nr_running = 0;
  6421. rq->calc_load_active = 0;
  6422. rq->calc_load_update = jiffies + LOAD_FREQ;
  6423. init_cfs_rq(&rq->cfs);
  6424. init_rt_rq(&rq->rt);
  6425. init_dl_rq(&rq->dl);
  6426. #ifdef CONFIG_FAIR_GROUP_SCHED
  6427. root_task_group.shares = ROOT_TASK_GROUP_LOAD;
  6428. INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
  6429. /*
  6430. * How much cpu bandwidth does root_task_group get?
  6431. *
  6432. * In case of task-groups formed thr' the cgroup filesystem, it
  6433. * gets 100% of the cpu resources in the system. This overall
  6434. * system cpu resource is divided among the tasks of
  6435. * root_task_group and its child task-groups in a fair manner,
  6436. * based on each entity's (task or task-group's) weight
  6437. * (se->load.weight).
  6438. *
  6439. * In other words, if root_task_group has 10 tasks of weight
  6440. * 1024) and two child groups A0 and A1 (of weight 1024 each),
  6441. * then A0's share of the cpu resource is:
  6442. *
  6443. * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
  6444. *
  6445. * We achieve this by letting root_task_group's tasks sit
  6446. * directly in rq->cfs (i.e root_task_group->se[] = NULL).
  6447. */
  6448. init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
  6449. init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
  6450. #endif /* CONFIG_FAIR_GROUP_SCHED */
  6451. rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
  6452. #ifdef CONFIG_RT_GROUP_SCHED
  6453. init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
  6454. #endif
  6455. for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
  6456. rq->cpu_load[j] = 0;
  6457. #ifdef CONFIG_SMP
  6458. rq->sd = NULL;
  6459. rq->rd = NULL;
  6460. rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
  6461. rq->balance_callback = NULL;
  6462. rq->active_balance = 0;
  6463. rq->next_balance = jiffies;
  6464. rq->push_cpu = 0;
  6465. rq->cpu = i;
  6466. rq->online = 0;
  6467. rq->idle_stamp = 0;
  6468. rq->avg_idle = 2*sysctl_sched_migration_cost;
  6469. rq->max_idle_balance_cost = sysctl_sched_migration_cost;
  6470. INIT_LIST_HEAD(&rq->cfs_tasks);
  6471. rq_attach_root(rq, &def_root_domain);
  6472. #ifdef CONFIG_NO_HZ_COMMON
  6473. rq->last_load_update_tick = jiffies;
  6474. rq->nohz_flags = 0;
  6475. #endif
  6476. #ifdef CONFIG_NO_HZ_FULL
  6477. rq->last_sched_tick = 0;
  6478. #endif
  6479. #endif /* CONFIG_SMP */
  6480. init_rq_hrtick(rq);
  6481. atomic_set(&rq->nr_iowait, 0);
  6482. }
  6483. set_load_weight(&init_task);
  6484. /*
  6485. * The boot idle thread does lazy MMU switching as well:
  6486. */
  6487. atomic_inc(&init_mm.mm_count);
  6488. enter_lazy_tlb(&init_mm, current);
  6489. /*
  6490. * Make us the idle thread. Technically, schedule() should not be
  6491. * called from this thread, however somewhere below it might be,
  6492. * but because we are the idle thread, we just pick up running again
  6493. * when this runqueue becomes "idle".
  6494. */
  6495. init_idle(current, smp_processor_id());
  6496. calc_load_update = jiffies + LOAD_FREQ;
  6497. #ifdef CONFIG_SMP
  6498. zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
  6499. /* May be allocated at isolcpus cmdline parse time */
  6500. if (cpu_isolated_map == NULL)
  6501. zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
  6502. idle_thread_set_boot_cpu();
  6503. set_cpu_rq_start_time(smp_processor_id());
  6504. #endif
  6505. init_sched_fair_class();
  6506. init_schedstats();
  6507. scheduler_running = 1;
  6508. }
  6509. #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
  6510. static inline int preempt_count_equals(int preempt_offset)
  6511. {
  6512. int nested = preempt_count() + rcu_preempt_depth();
  6513. return (nested == preempt_offset);
  6514. }
  6515. void __might_sleep(const char *file, int line, int preempt_offset)
  6516. {
  6517. /*
  6518. * Blocking primitives will set (and therefore destroy) current->state,
  6519. * since we will exit with TASK_RUNNING make sure we enter with it,
  6520. * otherwise we will destroy state.
  6521. */
  6522. WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
  6523. "do not call blocking ops when !TASK_RUNNING; "
  6524. "state=%lx set at [<%p>] %pS\n",
  6525. current->state,
  6526. (void *)current->task_state_change,
  6527. (void *)current->task_state_change);
  6528. ___might_sleep(file, line, preempt_offset);
  6529. }
  6530. EXPORT_SYMBOL(__might_sleep);
  6531. void ___might_sleep(const char *file, int line, int preempt_offset)
  6532. {
  6533. static unsigned long prev_jiffy; /* ratelimiting */
  6534. unsigned long preempt_disable_ip;
  6535. rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
  6536. if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
  6537. !is_idle_task(current)) ||
  6538. system_state != SYSTEM_RUNNING || oops_in_progress)
  6539. return;
  6540. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  6541. return;
  6542. prev_jiffy = jiffies;
  6543. /* Save this before calling printk(), since that will clobber it */
  6544. preempt_disable_ip = get_preempt_disable_ip(current);
  6545. printk(KERN_ERR
  6546. "BUG: sleeping function called from invalid context at %s:%d\n",
  6547. file, line);
  6548. printk(KERN_ERR
  6549. "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
  6550. in_atomic(), irqs_disabled(),
  6551. current->pid, current->comm);
  6552. if (task_stack_end_corrupted(current))
  6553. printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
  6554. debug_show_held_locks(current);
  6555. if (irqs_disabled())
  6556. print_irqtrace_events(current);
  6557. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
  6558. && !preempt_count_equals(preempt_offset)) {
  6559. pr_err("Preemption disabled at:");
  6560. print_ip_sym(preempt_disable_ip);
  6561. pr_cont("\n");
  6562. }
  6563. dump_stack();
  6564. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  6565. }
  6566. EXPORT_SYMBOL(___might_sleep);
  6567. #endif
  6568. #ifdef CONFIG_MAGIC_SYSRQ
  6569. void normalize_rt_tasks(void)
  6570. {
  6571. struct task_struct *g, *p;
  6572. struct sched_attr attr = {
  6573. .sched_policy = SCHED_NORMAL,
  6574. };
  6575. read_lock(&tasklist_lock);
  6576. for_each_process_thread(g, p) {
  6577. /*
  6578. * Only normalize user tasks:
  6579. */
  6580. if (p->flags & PF_KTHREAD)
  6581. continue;
  6582. p->se.exec_start = 0;
  6583. schedstat_set(p->se.statistics.wait_start, 0);
  6584. schedstat_set(p->se.statistics.sleep_start, 0);
  6585. schedstat_set(p->se.statistics.block_start, 0);
  6586. if (!dl_task(p) && !rt_task(p)) {
  6587. /*
  6588. * Renice negative nice level userspace
  6589. * tasks back to 0:
  6590. */
  6591. if (task_nice(p) < 0)
  6592. set_user_nice(p, 0);
  6593. continue;
  6594. }
  6595. __sched_setscheduler(p, &attr, false, false);
  6596. }
  6597. read_unlock(&tasklist_lock);
  6598. }
  6599. #endif /* CONFIG_MAGIC_SYSRQ */
  6600. #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
  6601. /*
  6602. * These functions are only useful for the IA64 MCA handling, or kdb.
  6603. *
  6604. * They can only be called when the whole system has been
  6605. * stopped - every CPU needs to be quiescent, and no scheduling
  6606. * activity can take place. Using them for anything else would
  6607. * be a serious bug, and as a result, they aren't even visible
  6608. * under any other configuration.
  6609. */
  6610. /**
  6611. * curr_task - return the current task for a given cpu.
  6612. * @cpu: the processor in question.
  6613. *
  6614. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  6615. *
  6616. * Return: The current task for @cpu.
  6617. */
  6618. struct task_struct *curr_task(int cpu)
  6619. {
  6620. return cpu_curr(cpu);
  6621. }
  6622. #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
  6623. #ifdef CONFIG_IA64
  6624. /**
  6625. * set_curr_task - set the current task for a given cpu.
  6626. * @cpu: the processor in question.
  6627. * @p: the task pointer to set.
  6628. *
  6629. * Description: This function must only be used when non-maskable interrupts
  6630. * are serviced on a separate stack. It allows the architecture to switch the
  6631. * notion of the current task on a cpu in a non-blocking manner. This function
  6632. * must be called with all CPU's synchronized, and interrupts disabled, the
  6633. * and caller must save the original value of the current task (see
  6634. * curr_task() above) and restore that value before reenabling interrupts and
  6635. * re-starting the system.
  6636. *
  6637. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  6638. */
  6639. void set_curr_task(int cpu, struct task_struct *p)
  6640. {
  6641. cpu_curr(cpu) = p;
  6642. }
  6643. #endif
  6644. #ifdef CONFIG_CGROUP_SCHED
  6645. /* task_group_lock serializes the addition/removal of task groups */
  6646. static DEFINE_SPINLOCK(task_group_lock);
  6647. static void sched_free_group(struct task_group *tg)
  6648. {
  6649. free_fair_sched_group(tg);
  6650. free_rt_sched_group(tg);
  6651. autogroup_free(tg);
  6652. kmem_cache_free(task_group_cache, tg);
  6653. }
  6654. /* allocate runqueue etc for a new task group */
  6655. struct task_group *sched_create_group(struct task_group *parent)
  6656. {
  6657. struct task_group *tg;
  6658. tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
  6659. if (!tg)
  6660. return ERR_PTR(-ENOMEM);
  6661. if (!alloc_fair_sched_group(tg, parent))
  6662. goto err;
  6663. if (!alloc_rt_sched_group(tg, parent))
  6664. goto err;
  6665. return tg;
  6666. err:
  6667. sched_free_group(tg);
  6668. return ERR_PTR(-ENOMEM);
  6669. }
  6670. void sched_online_group(struct task_group *tg, struct task_group *parent)
  6671. {
  6672. unsigned long flags;
  6673. spin_lock_irqsave(&task_group_lock, flags);
  6674. list_add_rcu(&tg->list, &task_groups);
  6675. WARN_ON(!parent); /* root should already exist */
  6676. tg->parent = parent;
  6677. INIT_LIST_HEAD(&tg->children);
  6678. list_add_rcu(&tg->siblings, &parent->children);
  6679. spin_unlock_irqrestore(&task_group_lock, flags);
  6680. online_fair_sched_group(tg);
  6681. }
  6682. /* rcu callback to free various structures associated with a task group */
  6683. static void sched_free_group_rcu(struct rcu_head *rhp)
  6684. {
  6685. /* now it should be safe to free those cfs_rqs */
  6686. sched_free_group(container_of(rhp, struct task_group, rcu));
  6687. }
  6688. void sched_destroy_group(struct task_group *tg)
  6689. {
  6690. /* wait for possible concurrent references to cfs_rqs complete */
  6691. call_rcu(&tg->rcu, sched_free_group_rcu);
  6692. }
  6693. void sched_offline_group(struct task_group *tg)
  6694. {
  6695. unsigned long flags;
  6696. /* end participation in shares distribution */
  6697. unregister_fair_sched_group(tg);
  6698. spin_lock_irqsave(&task_group_lock, flags);
  6699. list_del_rcu(&tg->list);
  6700. list_del_rcu(&tg->siblings);
  6701. spin_unlock_irqrestore(&task_group_lock, flags);
  6702. }
  6703. static void sched_change_group(struct task_struct *tsk, int type)
  6704. {
  6705. struct task_group *tg;
  6706. /*
  6707. * All callers are synchronized by task_rq_lock(); we do not use RCU
  6708. * which is pointless here. Thus, we pass "true" to task_css_check()
  6709. * to prevent lockdep warnings.
  6710. */
  6711. tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
  6712. struct task_group, css);
  6713. tg = autogroup_task_group(tsk, tg);
  6714. tsk->sched_task_group = tg;
  6715. #ifdef CONFIG_FAIR_GROUP_SCHED
  6716. if (tsk->sched_class->task_change_group)
  6717. tsk->sched_class->task_change_group(tsk, type);
  6718. else
  6719. #endif
  6720. set_task_rq(tsk, task_cpu(tsk));
  6721. }
  6722. /*
  6723. * Change task's runqueue when it moves between groups.
  6724. *
  6725. * The caller of this function should have put the task in its new group by
  6726. * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
  6727. * its new group.
  6728. */
  6729. void sched_move_task(struct task_struct *tsk)
  6730. {
  6731. int queued, running;
  6732. struct rq_flags rf;
  6733. struct rq *rq;
  6734. rq = task_rq_lock(tsk, &rf);
  6735. running = task_current(rq, tsk);
  6736. queued = task_on_rq_queued(tsk);
  6737. if (queued)
  6738. dequeue_task(rq, tsk, DEQUEUE_SAVE | DEQUEUE_MOVE);
  6739. if (unlikely(running))
  6740. put_prev_task(rq, tsk);
  6741. sched_change_group(tsk, TASK_MOVE_GROUP);
  6742. if (unlikely(running))
  6743. tsk->sched_class->set_curr_task(rq);
  6744. if (queued)
  6745. enqueue_task(rq, tsk, ENQUEUE_RESTORE | ENQUEUE_MOVE);
  6746. task_rq_unlock(rq, tsk, &rf);
  6747. }
  6748. #endif /* CONFIG_CGROUP_SCHED */
  6749. #ifdef CONFIG_RT_GROUP_SCHED
  6750. /*
  6751. * Ensure that the real time constraints are schedulable.
  6752. */
  6753. static DEFINE_MUTEX(rt_constraints_mutex);
  6754. /* Must be called with tasklist_lock held */
  6755. static inline int tg_has_rt_tasks(struct task_group *tg)
  6756. {
  6757. struct task_struct *g, *p;
  6758. /*
  6759. * Autogroups do not have RT tasks; see autogroup_create().
  6760. */
  6761. if (task_group_is_autogroup(tg))
  6762. return 0;
  6763. for_each_process_thread(g, p) {
  6764. if (rt_task(p) && task_group(p) == tg)
  6765. return 1;
  6766. }
  6767. return 0;
  6768. }
  6769. struct rt_schedulable_data {
  6770. struct task_group *tg;
  6771. u64 rt_period;
  6772. u64 rt_runtime;
  6773. };
  6774. static int tg_rt_schedulable(struct task_group *tg, void *data)
  6775. {
  6776. struct rt_schedulable_data *d = data;
  6777. struct task_group *child;
  6778. unsigned long total, sum = 0;
  6779. u64 period, runtime;
  6780. period = ktime_to_ns(tg->rt_bandwidth.rt_period);
  6781. runtime = tg->rt_bandwidth.rt_runtime;
  6782. if (tg == d->tg) {
  6783. period = d->rt_period;
  6784. runtime = d->rt_runtime;
  6785. }
  6786. /*
  6787. * Cannot have more runtime than the period.
  6788. */
  6789. if (runtime > period && runtime != RUNTIME_INF)
  6790. return -EINVAL;
  6791. /*
  6792. * Ensure we don't starve existing RT tasks.
  6793. */
  6794. if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
  6795. return -EBUSY;
  6796. total = to_ratio(period, runtime);
  6797. /*
  6798. * Nobody can have more than the global setting allows.
  6799. */
  6800. if (total > to_ratio(global_rt_period(), global_rt_runtime()))
  6801. return -EINVAL;
  6802. /*
  6803. * The sum of our children's runtime should not exceed our own.
  6804. */
  6805. list_for_each_entry_rcu(child, &tg->children, siblings) {
  6806. period = ktime_to_ns(child->rt_bandwidth.rt_period);
  6807. runtime = child->rt_bandwidth.rt_runtime;
  6808. if (child == d->tg) {
  6809. period = d->rt_period;
  6810. runtime = d->rt_runtime;
  6811. }
  6812. sum += to_ratio(period, runtime);
  6813. }
  6814. if (sum > total)
  6815. return -EINVAL;
  6816. return 0;
  6817. }
  6818. static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
  6819. {
  6820. int ret;
  6821. struct rt_schedulable_data data = {
  6822. .tg = tg,
  6823. .rt_period = period,
  6824. .rt_runtime = runtime,
  6825. };
  6826. rcu_read_lock();
  6827. ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
  6828. rcu_read_unlock();
  6829. return ret;
  6830. }
  6831. static int tg_set_rt_bandwidth(struct task_group *tg,
  6832. u64 rt_period, u64 rt_runtime)
  6833. {
  6834. int i, err = 0;
  6835. /*
  6836. * Disallowing the root group RT runtime is BAD, it would disallow the
  6837. * kernel creating (and or operating) RT threads.
  6838. */
  6839. if (tg == &root_task_group && rt_runtime == 0)
  6840. return -EINVAL;
  6841. /* No period doesn't make any sense. */
  6842. if (rt_period == 0)
  6843. return -EINVAL;
  6844. mutex_lock(&rt_constraints_mutex);
  6845. read_lock(&tasklist_lock);
  6846. err = __rt_schedulable(tg, rt_period, rt_runtime);
  6847. if (err)
  6848. goto unlock;
  6849. raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
  6850. tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
  6851. tg->rt_bandwidth.rt_runtime = rt_runtime;
  6852. for_each_possible_cpu(i) {
  6853. struct rt_rq *rt_rq = tg->rt_rq[i];
  6854. raw_spin_lock(&rt_rq->rt_runtime_lock);
  6855. rt_rq->rt_runtime = rt_runtime;
  6856. raw_spin_unlock(&rt_rq->rt_runtime_lock);
  6857. }
  6858. raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
  6859. unlock:
  6860. read_unlock(&tasklist_lock);
  6861. mutex_unlock(&rt_constraints_mutex);
  6862. return err;
  6863. }
  6864. static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
  6865. {
  6866. u64 rt_runtime, rt_period;
  6867. rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
  6868. rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
  6869. if (rt_runtime_us < 0)
  6870. rt_runtime = RUNTIME_INF;
  6871. return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
  6872. }
  6873. static long sched_group_rt_runtime(struct task_group *tg)
  6874. {
  6875. u64 rt_runtime_us;
  6876. if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
  6877. return -1;
  6878. rt_runtime_us = tg->rt_bandwidth.rt_runtime;
  6879. do_div(rt_runtime_us, NSEC_PER_USEC);
  6880. return rt_runtime_us;
  6881. }
  6882. static int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
  6883. {
  6884. u64 rt_runtime, rt_period;
  6885. rt_period = rt_period_us * NSEC_PER_USEC;
  6886. rt_runtime = tg->rt_bandwidth.rt_runtime;
  6887. return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
  6888. }
  6889. static long sched_group_rt_period(struct task_group *tg)
  6890. {
  6891. u64 rt_period_us;
  6892. rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
  6893. do_div(rt_period_us, NSEC_PER_USEC);
  6894. return rt_period_us;
  6895. }
  6896. #endif /* CONFIG_RT_GROUP_SCHED */
  6897. #ifdef CONFIG_RT_GROUP_SCHED
  6898. static int sched_rt_global_constraints(void)
  6899. {
  6900. int ret = 0;
  6901. mutex_lock(&rt_constraints_mutex);
  6902. read_lock(&tasklist_lock);
  6903. ret = __rt_schedulable(NULL, 0, 0);
  6904. read_unlock(&tasklist_lock);
  6905. mutex_unlock(&rt_constraints_mutex);
  6906. return ret;
  6907. }
  6908. static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
  6909. {
  6910. /* Don't accept realtime tasks when there is no way for them to run */
  6911. if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
  6912. return 0;
  6913. return 1;
  6914. }
  6915. #else /* !CONFIG_RT_GROUP_SCHED */
  6916. static int sched_rt_global_constraints(void)
  6917. {
  6918. unsigned long flags;
  6919. int i;
  6920. raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
  6921. for_each_possible_cpu(i) {
  6922. struct rt_rq *rt_rq = &cpu_rq(i)->rt;
  6923. raw_spin_lock(&rt_rq->rt_runtime_lock);
  6924. rt_rq->rt_runtime = global_rt_runtime();
  6925. raw_spin_unlock(&rt_rq->rt_runtime_lock);
  6926. }
  6927. raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
  6928. return 0;
  6929. }
  6930. #endif /* CONFIG_RT_GROUP_SCHED */
  6931. static int sched_dl_global_validate(void)
  6932. {
  6933. u64 runtime = global_rt_runtime();
  6934. u64 period = global_rt_period();
  6935. u64 new_bw = to_ratio(period, runtime);
  6936. struct dl_bw *dl_b;
  6937. int cpu, ret = 0;
  6938. unsigned long flags;
  6939. /*
  6940. * Here we want to check the bandwidth not being set to some
  6941. * value smaller than the currently allocated bandwidth in
  6942. * any of the root_domains.
  6943. *
  6944. * FIXME: Cycling on all the CPUs is overdoing, but simpler than
  6945. * cycling on root_domains... Discussion on different/better
  6946. * solutions is welcome!
  6947. */
  6948. for_each_possible_cpu(cpu) {
  6949. rcu_read_lock_sched();
  6950. dl_b = dl_bw_of(cpu);
  6951. raw_spin_lock_irqsave(&dl_b->lock, flags);
  6952. if (new_bw < dl_b->total_bw)
  6953. ret = -EBUSY;
  6954. raw_spin_unlock_irqrestore(&dl_b->lock, flags);
  6955. rcu_read_unlock_sched();
  6956. if (ret)
  6957. break;
  6958. }
  6959. return ret;
  6960. }
  6961. static void sched_dl_do_global(void)
  6962. {
  6963. u64 new_bw = -1;
  6964. struct dl_bw *dl_b;
  6965. int cpu;
  6966. unsigned long flags;
  6967. def_dl_bandwidth.dl_period = global_rt_period();
  6968. def_dl_bandwidth.dl_runtime = global_rt_runtime();
  6969. if (global_rt_runtime() != RUNTIME_INF)
  6970. new_bw = to_ratio(global_rt_period(), global_rt_runtime());
  6971. /*
  6972. * FIXME: As above...
  6973. */
  6974. for_each_possible_cpu(cpu) {
  6975. rcu_read_lock_sched();
  6976. dl_b = dl_bw_of(cpu);
  6977. raw_spin_lock_irqsave(&dl_b->lock, flags);
  6978. dl_b->bw = new_bw;
  6979. raw_spin_unlock_irqrestore(&dl_b->lock, flags);
  6980. rcu_read_unlock_sched();
  6981. }
  6982. }
  6983. static int sched_rt_global_validate(void)
  6984. {
  6985. if (sysctl_sched_rt_period <= 0)
  6986. return -EINVAL;
  6987. if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
  6988. (sysctl_sched_rt_runtime > sysctl_sched_rt_period))
  6989. return -EINVAL;
  6990. return 0;
  6991. }
  6992. static void sched_rt_do_global(void)
  6993. {
  6994. def_rt_bandwidth.rt_runtime = global_rt_runtime();
  6995. def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
  6996. }
  6997. int sched_rt_handler(struct ctl_table *table, int write,
  6998. void __user *buffer, size_t *lenp,
  6999. loff_t *ppos)
  7000. {
  7001. int old_period, old_runtime;
  7002. static DEFINE_MUTEX(mutex);
  7003. int ret;
  7004. mutex_lock(&mutex);
  7005. old_period = sysctl_sched_rt_period;
  7006. old_runtime = sysctl_sched_rt_runtime;
  7007. ret = proc_dointvec(table, write, buffer, lenp, ppos);
  7008. if (!ret && write) {
  7009. ret = sched_rt_global_validate();
  7010. if (ret)
  7011. goto undo;
  7012. ret = sched_dl_global_validate();
  7013. if (ret)
  7014. goto undo;
  7015. ret = sched_rt_global_constraints();
  7016. if (ret)
  7017. goto undo;
  7018. sched_rt_do_global();
  7019. sched_dl_do_global();
  7020. }
  7021. if (0) {
  7022. undo:
  7023. sysctl_sched_rt_period = old_period;
  7024. sysctl_sched_rt_runtime = old_runtime;
  7025. }
  7026. mutex_unlock(&mutex);
  7027. return ret;
  7028. }
  7029. int sched_rr_handler(struct ctl_table *table, int write,
  7030. void __user *buffer, size_t *lenp,
  7031. loff_t *ppos)
  7032. {
  7033. int ret;
  7034. static DEFINE_MUTEX(mutex);
  7035. mutex_lock(&mutex);
  7036. ret = proc_dointvec(table, write, buffer, lenp, ppos);
  7037. /* make sure that internally we keep jiffies */
  7038. /* also, writing zero resets timeslice to default */
  7039. if (!ret && write) {
  7040. sched_rr_timeslice = sched_rr_timeslice <= 0 ?
  7041. RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
  7042. }
  7043. mutex_unlock(&mutex);
  7044. return ret;
  7045. }
  7046. #ifdef CONFIG_CGROUP_SCHED
  7047. static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
  7048. {
  7049. return css ? container_of(css, struct task_group, css) : NULL;
  7050. }
  7051. static struct cgroup_subsys_state *
  7052. cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  7053. {
  7054. struct task_group *parent = css_tg(parent_css);
  7055. struct task_group *tg;
  7056. if (!parent) {
  7057. /* This is early initialization for the top cgroup */
  7058. return &root_task_group.css;
  7059. }
  7060. tg = sched_create_group(parent);
  7061. if (IS_ERR(tg))
  7062. return ERR_PTR(-ENOMEM);
  7063. sched_online_group(tg, parent);
  7064. return &tg->css;
  7065. }
  7066. static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
  7067. {
  7068. struct task_group *tg = css_tg(css);
  7069. sched_offline_group(tg);
  7070. }
  7071. static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
  7072. {
  7073. struct task_group *tg = css_tg(css);
  7074. /*
  7075. * Relies on the RCU grace period between css_released() and this.
  7076. */
  7077. sched_free_group(tg);
  7078. }
  7079. /*
  7080. * This is called before wake_up_new_task(), therefore we really only
  7081. * have to set its group bits, all the other stuff does not apply.
  7082. */
  7083. static void cpu_cgroup_fork(struct task_struct *task)
  7084. {
  7085. struct rq_flags rf;
  7086. struct rq *rq;
  7087. rq = task_rq_lock(task, &rf);
  7088. sched_change_group(task, TASK_SET_GROUP);
  7089. task_rq_unlock(rq, task, &rf);
  7090. }
  7091. static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
  7092. {
  7093. struct task_struct *task;
  7094. struct cgroup_subsys_state *css;
  7095. int ret = 0;
  7096. cgroup_taskset_for_each(task, css, tset) {
  7097. #ifdef CONFIG_RT_GROUP_SCHED
  7098. if (!sched_rt_can_attach(css_tg(css), task))
  7099. return -EINVAL;
  7100. #else
  7101. /* We don't support RT-tasks being in separate groups */
  7102. if (task->sched_class != &fair_sched_class)
  7103. return -EINVAL;
  7104. #endif
  7105. /*
  7106. * Serialize against wake_up_new_task() such that if its
  7107. * running, we're sure to observe its full state.
  7108. */
  7109. raw_spin_lock_irq(&task->pi_lock);
  7110. /*
  7111. * Avoid calling sched_move_task() before wake_up_new_task()
  7112. * has happened. This would lead to problems with PELT, due to
  7113. * move wanting to detach+attach while we're not attached yet.
  7114. */
  7115. if (task->state == TASK_NEW)
  7116. ret = -EINVAL;
  7117. raw_spin_unlock_irq(&task->pi_lock);
  7118. if (ret)
  7119. break;
  7120. }
  7121. return ret;
  7122. }
  7123. static void cpu_cgroup_attach(struct cgroup_taskset *tset)
  7124. {
  7125. struct task_struct *task;
  7126. struct cgroup_subsys_state *css;
  7127. cgroup_taskset_for_each(task, css, tset)
  7128. sched_move_task(task);
  7129. }
  7130. #ifdef CONFIG_FAIR_GROUP_SCHED
  7131. static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
  7132. struct cftype *cftype, u64 shareval)
  7133. {
  7134. return sched_group_set_shares(css_tg(css), scale_load(shareval));
  7135. }
  7136. static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
  7137. struct cftype *cft)
  7138. {
  7139. struct task_group *tg = css_tg(css);
  7140. return (u64) scale_load_down(tg->shares);
  7141. }
  7142. #ifdef CONFIG_CFS_BANDWIDTH
  7143. static DEFINE_MUTEX(cfs_constraints_mutex);
  7144. const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
  7145. const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
  7146. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
  7147. static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
  7148. {
  7149. int i, ret = 0, runtime_enabled, runtime_was_enabled;
  7150. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  7151. if (tg == &root_task_group)
  7152. return -EINVAL;
  7153. /*
  7154. * Ensure we have at some amount of bandwidth every period. This is
  7155. * to prevent reaching a state of large arrears when throttled via
  7156. * entity_tick() resulting in prolonged exit starvation.
  7157. */
  7158. if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
  7159. return -EINVAL;
  7160. /*
  7161. * Likewise, bound things on the otherside by preventing insane quota
  7162. * periods. This also allows us to normalize in computing quota
  7163. * feasibility.
  7164. */
  7165. if (period > max_cfs_quota_period)
  7166. return -EINVAL;
  7167. /*
  7168. * Prevent race between setting of cfs_rq->runtime_enabled and
  7169. * unthrottle_offline_cfs_rqs().
  7170. */
  7171. get_online_cpus();
  7172. mutex_lock(&cfs_constraints_mutex);
  7173. ret = __cfs_schedulable(tg, period, quota);
  7174. if (ret)
  7175. goto out_unlock;
  7176. runtime_enabled = quota != RUNTIME_INF;
  7177. runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
  7178. /*
  7179. * If we need to toggle cfs_bandwidth_used, off->on must occur
  7180. * before making related changes, and on->off must occur afterwards
  7181. */
  7182. if (runtime_enabled && !runtime_was_enabled)
  7183. cfs_bandwidth_usage_inc();
  7184. raw_spin_lock_irq(&cfs_b->lock);
  7185. cfs_b->period = ns_to_ktime(period);
  7186. cfs_b->quota = quota;
  7187. __refill_cfs_bandwidth_runtime(cfs_b);
  7188. /* restart the period timer (if active) to handle new period expiry */
  7189. if (runtime_enabled)
  7190. start_cfs_bandwidth(cfs_b);
  7191. raw_spin_unlock_irq(&cfs_b->lock);
  7192. for_each_online_cpu(i) {
  7193. struct cfs_rq *cfs_rq = tg->cfs_rq[i];
  7194. struct rq *rq = cfs_rq->rq;
  7195. raw_spin_lock_irq(&rq->lock);
  7196. cfs_rq->runtime_enabled = runtime_enabled;
  7197. cfs_rq->runtime_remaining = 0;
  7198. if (cfs_rq->throttled)
  7199. unthrottle_cfs_rq(cfs_rq);
  7200. raw_spin_unlock_irq(&rq->lock);
  7201. }
  7202. if (runtime_was_enabled && !runtime_enabled)
  7203. cfs_bandwidth_usage_dec();
  7204. out_unlock:
  7205. mutex_unlock(&cfs_constraints_mutex);
  7206. put_online_cpus();
  7207. return ret;
  7208. }
  7209. int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
  7210. {
  7211. u64 quota, period;
  7212. period = ktime_to_ns(tg->cfs_bandwidth.period);
  7213. if (cfs_quota_us < 0)
  7214. quota = RUNTIME_INF;
  7215. else
  7216. quota = (u64)cfs_quota_us * NSEC_PER_USEC;
  7217. return tg_set_cfs_bandwidth(tg, period, quota);
  7218. }
  7219. long tg_get_cfs_quota(struct task_group *tg)
  7220. {
  7221. u64 quota_us;
  7222. if (tg->cfs_bandwidth.quota == RUNTIME_INF)
  7223. return -1;
  7224. quota_us = tg->cfs_bandwidth.quota;
  7225. do_div(quota_us, NSEC_PER_USEC);
  7226. return quota_us;
  7227. }
  7228. int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
  7229. {
  7230. u64 quota, period;
  7231. period = (u64)cfs_period_us * NSEC_PER_USEC;
  7232. quota = tg->cfs_bandwidth.quota;
  7233. return tg_set_cfs_bandwidth(tg, period, quota);
  7234. }
  7235. long tg_get_cfs_period(struct task_group *tg)
  7236. {
  7237. u64 cfs_period_us;
  7238. cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
  7239. do_div(cfs_period_us, NSEC_PER_USEC);
  7240. return cfs_period_us;
  7241. }
  7242. static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
  7243. struct cftype *cft)
  7244. {
  7245. return tg_get_cfs_quota(css_tg(css));
  7246. }
  7247. static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
  7248. struct cftype *cftype, s64 cfs_quota_us)
  7249. {
  7250. return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
  7251. }
  7252. static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
  7253. struct cftype *cft)
  7254. {
  7255. return tg_get_cfs_period(css_tg(css));
  7256. }
  7257. static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
  7258. struct cftype *cftype, u64 cfs_period_us)
  7259. {
  7260. return tg_set_cfs_period(css_tg(css), cfs_period_us);
  7261. }
  7262. struct cfs_schedulable_data {
  7263. struct task_group *tg;
  7264. u64 period, quota;
  7265. };
  7266. /*
  7267. * normalize group quota/period to be quota/max_period
  7268. * note: units are usecs
  7269. */
  7270. static u64 normalize_cfs_quota(struct task_group *tg,
  7271. struct cfs_schedulable_data *d)
  7272. {
  7273. u64 quota, period;
  7274. if (tg == d->tg) {
  7275. period = d->period;
  7276. quota = d->quota;
  7277. } else {
  7278. period = tg_get_cfs_period(tg);
  7279. quota = tg_get_cfs_quota(tg);
  7280. }
  7281. /* note: these should typically be equivalent */
  7282. if (quota == RUNTIME_INF || quota == -1)
  7283. return RUNTIME_INF;
  7284. return to_ratio(period, quota);
  7285. }
  7286. static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
  7287. {
  7288. struct cfs_schedulable_data *d = data;
  7289. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  7290. s64 quota = 0, parent_quota = -1;
  7291. if (!tg->parent) {
  7292. quota = RUNTIME_INF;
  7293. } else {
  7294. struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
  7295. quota = normalize_cfs_quota(tg, d);
  7296. parent_quota = parent_b->hierarchical_quota;
  7297. /*
  7298. * ensure max(child_quota) <= parent_quota, inherit when no
  7299. * limit is set
  7300. */
  7301. if (quota == RUNTIME_INF)
  7302. quota = parent_quota;
  7303. else if (parent_quota != RUNTIME_INF && quota > parent_quota)
  7304. return -EINVAL;
  7305. }
  7306. cfs_b->hierarchical_quota = quota;
  7307. return 0;
  7308. }
  7309. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
  7310. {
  7311. int ret;
  7312. struct cfs_schedulable_data data = {
  7313. .tg = tg,
  7314. .period = period,
  7315. .quota = quota,
  7316. };
  7317. if (quota != RUNTIME_INF) {
  7318. do_div(data.period, NSEC_PER_USEC);
  7319. do_div(data.quota, NSEC_PER_USEC);
  7320. }
  7321. rcu_read_lock();
  7322. ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
  7323. rcu_read_unlock();
  7324. return ret;
  7325. }
  7326. static int cpu_stats_show(struct seq_file *sf, void *v)
  7327. {
  7328. struct task_group *tg = css_tg(seq_css(sf));
  7329. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  7330. seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
  7331. seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
  7332. seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
  7333. return 0;
  7334. }
  7335. #endif /* CONFIG_CFS_BANDWIDTH */
  7336. #endif /* CONFIG_FAIR_GROUP_SCHED */
  7337. #ifdef CONFIG_RT_GROUP_SCHED
  7338. static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
  7339. struct cftype *cft, s64 val)
  7340. {
  7341. return sched_group_set_rt_runtime(css_tg(css), val);
  7342. }
  7343. static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
  7344. struct cftype *cft)
  7345. {
  7346. return sched_group_rt_runtime(css_tg(css));
  7347. }
  7348. static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
  7349. struct cftype *cftype, u64 rt_period_us)
  7350. {
  7351. return sched_group_set_rt_period(css_tg(css), rt_period_us);
  7352. }
  7353. static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
  7354. struct cftype *cft)
  7355. {
  7356. return sched_group_rt_period(css_tg(css));
  7357. }
  7358. #endif /* CONFIG_RT_GROUP_SCHED */
  7359. static struct cftype cpu_files[] = {
  7360. #ifdef CONFIG_FAIR_GROUP_SCHED
  7361. {
  7362. .name = "shares",
  7363. .read_u64 = cpu_shares_read_u64,
  7364. .write_u64 = cpu_shares_write_u64,
  7365. },
  7366. #endif
  7367. #ifdef CONFIG_CFS_BANDWIDTH
  7368. {
  7369. .name = "cfs_quota_us",
  7370. .read_s64 = cpu_cfs_quota_read_s64,
  7371. .write_s64 = cpu_cfs_quota_write_s64,
  7372. },
  7373. {
  7374. .name = "cfs_period_us",
  7375. .read_u64 = cpu_cfs_period_read_u64,
  7376. .write_u64 = cpu_cfs_period_write_u64,
  7377. },
  7378. {
  7379. .name = "stat",
  7380. .seq_show = cpu_stats_show,
  7381. },
  7382. #endif
  7383. #ifdef CONFIG_RT_GROUP_SCHED
  7384. {
  7385. .name = "rt_runtime_us",
  7386. .read_s64 = cpu_rt_runtime_read,
  7387. .write_s64 = cpu_rt_runtime_write,
  7388. },
  7389. {
  7390. .name = "rt_period_us",
  7391. .read_u64 = cpu_rt_period_read_uint,
  7392. .write_u64 = cpu_rt_period_write_uint,
  7393. },
  7394. #endif
  7395. { } /* terminate */
  7396. };
  7397. struct cgroup_subsys cpu_cgrp_subsys = {
  7398. .css_alloc = cpu_cgroup_css_alloc,
  7399. .css_released = cpu_cgroup_css_released,
  7400. .css_free = cpu_cgroup_css_free,
  7401. .fork = cpu_cgroup_fork,
  7402. .can_attach = cpu_cgroup_can_attach,
  7403. .attach = cpu_cgroup_attach,
  7404. .legacy_cftypes = cpu_files,
  7405. .early_init = true,
  7406. };
  7407. #endif /* CONFIG_CGROUP_SCHED */
  7408. void dump_cpu_task(int cpu)
  7409. {
  7410. pr_info("Task dump for CPU %d:\n", cpu);
  7411. sched_show_task(cpu_curr(cpu));
  7412. }
  7413. /*
  7414. * Nice levels are multiplicative, with a gentle 10% change for every
  7415. * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
  7416. * nice 1, it will get ~10% less CPU time than another CPU-bound task
  7417. * that remained on nice 0.
  7418. *
  7419. * The "10% effect" is relative and cumulative: from _any_ nice level,
  7420. * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
  7421. * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
  7422. * If a task goes up by ~10% and another task goes down by ~10% then
  7423. * the relative distance between them is ~25%.)
  7424. */
  7425. const int sched_prio_to_weight[40] = {
  7426. /* -20 */ 88761, 71755, 56483, 46273, 36291,
  7427. /* -15 */ 29154, 23254, 18705, 14949, 11916,
  7428. /* -10 */ 9548, 7620, 6100, 4904, 3906,
  7429. /* -5 */ 3121, 2501, 1991, 1586, 1277,
  7430. /* 0 */ 1024, 820, 655, 526, 423,
  7431. /* 5 */ 335, 272, 215, 172, 137,
  7432. /* 10 */ 110, 87, 70, 56, 45,
  7433. /* 15 */ 36, 29, 23, 18, 15,
  7434. };
  7435. /*
  7436. * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
  7437. *
  7438. * In cases where the weight does not change often, we can use the
  7439. * precalculated inverse to speed up arithmetics by turning divisions
  7440. * into multiplications:
  7441. */
  7442. const u32 sched_prio_to_wmult[40] = {
  7443. /* -20 */ 48388, 59856, 76040, 92818, 118348,
  7444. /* -15 */ 147320, 184698, 229616, 287308, 360437,
  7445. /* -10 */ 449829, 563644, 704093, 875809, 1099582,
  7446. /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
  7447. /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
  7448. /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
  7449. /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
  7450. /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
  7451. };