core.c 204 KB

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