core.c 217 KB

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