core.c 214 KB

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