sched.c 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839
  1. /*
  2. * kernel/sched.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. */
  20. #include <linux/mm.h>
  21. #include <linux/module.h>
  22. #include <linux/nmi.h>
  23. #include <linux/init.h>
  24. #include <asm/uaccess.h>
  25. #include <linux/highmem.h>
  26. #include <linux/smp_lock.h>
  27. #include <asm/mmu_context.h>
  28. #include <linux/interrupt.h>
  29. #include <linux/capability.h>
  30. #include <linux/completion.h>
  31. #include <linux/kernel_stat.h>
  32. #include <linux/debug_locks.h>
  33. #include <linux/security.h>
  34. #include <linux/notifier.h>
  35. #include <linux/profile.h>
  36. #include <linux/suspend.h>
  37. #include <linux/vmalloc.h>
  38. #include <linux/blkdev.h>
  39. #include <linux/delay.h>
  40. #include <linux/smp.h>
  41. #include <linux/threads.h>
  42. #include <linux/timer.h>
  43. #include <linux/rcupdate.h>
  44. #include <linux/cpu.h>
  45. #include <linux/cpuset.h>
  46. #include <linux/percpu.h>
  47. #include <linux/kthread.h>
  48. #include <linux/seq_file.h>
  49. #include <linux/syscalls.h>
  50. #include <linux/times.h>
  51. #include <linux/acct.h>
  52. #include <linux/kprobes.h>
  53. #include <asm/tlb.h>
  54. #include <asm/unistd.h>
  55. /*
  56. * Convert user-nice values [ -20 ... 0 ... 19 ]
  57. * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
  58. * and back.
  59. */
  60. #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
  61. #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
  62. #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
  63. /*
  64. * 'User priority' is the nice value converted to something we
  65. * can work with better when scaling various scheduler parameters,
  66. * it's a [ 0 ... 39 ] range.
  67. */
  68. #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
  69. #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
  70. #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
  71. /*
  72. * Some helpers for converting nanosecond timing to jiffy resolution
  73. */
  74. #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
  75. #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
  76. /*
  77. * These are the 'tuning knobs' of the scheduler:
  78. *
  79. * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
  80. * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
  81. * Timeslices get refilled after they expire.
  82. */
  83. #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
  84. #define DEF_TIMESLICE (100 * HZ / 1000)
  85. #define ON_RUNQUEUE_WEIGHT 30
  86. #define CHILD_PENALTY 95
  87. #define PARENT_PENALTY 100
  88. #define EXIT_WEIGHT 3
  89. #define PRIO_BONUS_RATIO 25
  90. #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
  91. #define INTERACTIVE_DELTA 2
  92. #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
  93. #define STARVATION_LIMIT (MAX_SLEEP_AVG)
  94. #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
  95. /*
  96. * If a task is 'interactive' then we reinsert it in the active
  97. * array after it has expired its current timeslice. (it will not
  98. * continue to run immediately, it will still roundrobin with
  99. * other interactive tasks.)
  100. *
  101. * This part scales the interactivity limit depending on niceness.
  102. *
  103. * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
  104. * Here are a few examples of different nice levels:
  105. *
  106. * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
  107. * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
  108. * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
  109. * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
  110. * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
  111. *
  112. * (the X axis represents the possible -5 ... 0 ... +5 dynamic
  113. * priority range a task can explore, a value of '1' means the
  114. * task is rated interactive.)
  115. *
  116. * Ie. nice +19 tasks can never get 'interactive' enough to be
  117. * reinserted into the active array. And only heavily CPU-hog nice -20
  118. * tasks will be expired. Default nice 0 tasks are somewhere between,
  119. * it takes some effort for them to get interactive, but it's not
  120. * too hard.
  121. */
  122. #define CURRENT_BONUS(p) \
  123. (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
  124. MAX_SLEEP_AVG)
  125. #define GRANULARITY (10 * HZ / 1000 ? : 1)
  126. #ifdef CONFIG_SMP
  127. #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
  128. (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
  129. num_online_cpus())
  130. #else
  131. #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
  132. (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
  133. #endif
  134. #define SCALE(v1,v1_max,v2_max) \
  135. (v1) * (v2_max) / (v1_max)
  136. #define DELTA(p) \
  137. (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
  138. INTERACTIVE_DELTA)
  139. #define TASK_INTERACTIVE(p) \
  140. ((p)->prio <= (p)->static_prio - DELTA(p))
  141. #define INTERACTIVE_SLEEP(p) \
  142. (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
  143. (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
  144. #define TASK_PREEMPTS_CURR(p, rq) \
  145. ((p)->prio < (rq)->curr->prio)
  146. /*
  147. * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
  148. * to time slice values: [800ms ... 100ms ... 5ms]
  149. *
  150. * The higher a thread's priority, the bigger timeslices
  151. * it gets during one round of execution. But even the lowest
  152. * priority thread gets MIN_TIMESLICE worth of execution time.
  153. */
  154. #define SCALE_PRIO(x, prio) \
  155. max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
  156. static unsigned int static_prio_timeslice(int static_prio)
  157. {
  158. if (static_prio < NICE_TO_PRIO(0))
  159. return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
  160. else
  161. return SCALE_PRIO(DEF_TIMESLICE, static_prio);
  162. }
  163. static inline unsigned int task_timeslice(struct task_struct *p)
  164. {
  165. return static_prio_timeslice(p->static_prio);
  166. }
  167. /*
  168. * These are the runqueue data structures:
  169. */
  170. struct prio_array {
  171. unsigned int nr_active;
  172. DECLARE_BITMAP(bitmap, MAX_PRIO+1); /* include 1 bit for delimiter */
  173. struct list_head queue[MAX_PRIO];
  174. };
  175. /*
  176. * This is the main, per-CPU runqueue data structure.
  177. *
  178. * Locking rule: those places that want to lock multiple runqueues
  179. * (such as the load balancing or the thread migration code), lock
  180. * acquire operations must be ordered by ascending &runqueue.
  181. */
  182. struct rq {
  183. spinlock_t lock;
  184. /*
  185. * nr_running and cpu_load should be in the same cacheline because
  186. * remote CPUs use both these fields when doing load calculation.
  187. */
  188. unsigned long nr_running;
  189. unsigned long raw_weighted_load;
  190. #ifdef CONFIG_SMP
  191. unsigned long cpu_load[3];
  192. #endif
  193. unsigned long long nr_switches;
  194. /*
  195. * This is part of a global counter where only the total sum
  196. * over all CPUs matters. A task can increase this counter on
  197. * one CPU and if it got migrated afterwards it may decrease
  198. * it on another CPU. Always updated under the runqueue lock:
  199. */
  200. unsigned long nr_uninterruptible;
  201. unsigned long expired_timestamp;
  202. unsigned long long timestamp_last_tick;
  203. struct task_struct *curr, *idle;
  204. struct mm_struct *prev_mm;
  205. struct prio_array *active, *expired, arrays[2];
  206. int best_expired_prio;
  207. atomic_t nr_iowait;
  208. #ifdef CONFIG_SMP
  209. struct sched_domain *sd;
  210. /* For active balancing */
  211. int active_balance;
  212. int push_cpu;
  213. struct task_struct *migration_thread;
  214. struct list_head migration_queue;
  215. #endif
  216. #ifdef CONFIG_SCHEDSTATS
  217. /* latency stats */
  218. struct sched_info rq_sched_info;
  219. /* sys_sched_yield() stats */
  220. unsigned long yld_exp_empty;
  221. unsigned long yld_act_empty;
  222. unsigned long yld_both_empty;
  223. unsigned long yld_cnt;
  224. /* schedule() stats */
  225. unsigned long sched_switch;
  226. unsigned long sched_cnt;
  227. unsigned long sched_goidle;
  228. /* try_to_wake_up() stats */
  229. unsigned long ttwu_cnt;
  230. unsigned long ttwu_local;
  231. #endif
  232. struct lock_class_key rq_lock_key;
  233. };
  234. static DEFINE_PER_CPU(struct rq, runqueues);
  235. /*
  236. * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
  237. * See detach_destroy_domains: synchronize_sched for details.
  238. *
  239. * The domain tree of any CPU may only be accessed from within
  240. * preempt-disabled sections.
  241. */
  242. #define for_each_domain(cpu, __sd) \
  243. for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
  244. #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
  245. #define this_rq() (&__get_cpu_var(runqueues))
  246. #define task_rq(p) cpu_rq(task_cpu(p))
  247. #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
  248. #ifndef prepare_arch_switch
  249. # define prepare_arch_switch(next) do { } while (0)
  250. #endif
  251. #ifndef finish_arch_switch
  252. # define finish_arch_switch(prev) do { } while (0)
  253. #endif
  254. #ifndef __ARCH_WANT_UNLOCKED_CTXSW
  255. static inline int task_running(struct rq *rq, struct task_struct *p)
  256. {
  257. return rq->curr == p;
  258. }
  259. static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
  260. {
  261. }
  262. static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
  263. {
  264. #ifdef CONFIG_DEBUG_SPINLOCK
  265. /* this is a valid case when another task releases the spinlock */
  266. rq->lock.owner = current;
  267. #endif
  268. /*
  269. * If we are tracking spinlock dependencies then we have to
  270. * fix up the runqueue lock - which gets 'carried over' from
  271. * prev into current:
  272. */
  273. spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
  274. spin_unlock_irq(&rq->lock);
  275. }
  276. #else /* __ARCH_WANT_UNLOCKED_CTXSW */
  277. static inline int task_running(struct rq *rq, struct task_struct *p)
  278. {
  279. #ifdef CONFIG_SMP
  280. return p->oncpu;
  281. #else
  282. return rq->curr == p;
  283. #endif
  284. }
  285. static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
  286. {
  287. #ifdef CONFIG_SMP
  288. /*
  289. * We can optimise this out completely for !SMP, because the
  290. * SMP rebalancing from interrupt is the only thing that cares
  291. * here.
  292. */
  293. next->oncpu = 1;
  294. #endif
  295. #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
  296. spin_unlock_irq(&rq->lock);
  297. #else
  298. spin_unlock(&rq->lock);
  299. #endif
  300. }
  301. static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
  302. {
  303. #ifdef CONFIG_SMP
  304. /*
  305. * After ->oncpu is cleared, the task can be moved to a different CPU.
  306. * We must ensure this doesn't happen until the switch is completely
  307. * finished.
  308. */
  309. smp_wmb();
  310. prev->oncpu = 0;
  311. #endif
  312. #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
  313. local_irq_enable();
  314. #endif
  315. }
  316. #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
  317. /*
  318. * __task_rq_lock - lock the runqueue a given task resides on.
  319. * Must be called interrupts disabled.
  320. */
  321. static inline struct rq *__task_rq_lock(struct task_struct *p)
  322. __acquires(rq->lock)
  323. {
  324. struct rq *rq;
  325. repeat_lock_task:
  326. rq = task_rq(p);
  327. spin_lock(&rq->lock);
  328. if (unlikely(rq != task_rq(p))) {
  329. spin_unlock(&rq->lock);
  330. goto repeat_lock_task;
  331. }
  332. return rq;
  333. }
  334. /*
  335. * task_rq_lock - lock the runqueue a given task resides on and disable
  336. * interrupts. Note the ordering: we can safely lookup the task_rq without
  337. * explicitly disabling preemption.
  338. */
  339. static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
  340. __acquires(rq->lock)
  341. {
  342. struct rq *rq;
  343. repeat_lock_task:
  344. local_irq_save(*flags);
  345. rq = task_rq(p);
  346. spin_lock(&rq->lock);
  347. if (unlikely(rq != task_rq(p))) {
  348. spin_unlock_irqrestore(&rq->lock, *flags);
  349. goto repeat_lock_task;
  350. }
  351. return rq;
  352. }
  353. static inline void __task_rq_unlock(struct rq *rq)
  354. __releases(rq->lock)
  355. {
  356. spin_unlock(&rq->lock);
  357. }
  358. static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
  359. __releases(rq->lock)
  360. {
  361. spin_unlock_irqrestore(&rq->lock, *flags);
  362. }
  363. #ifdef CONFIG_SCHEDSTATS
  364. /*
  365. * bump this up when changing the output format or the meaning of an existing
  366. * format, so that tools can adapt (or abort)
  367. */
  368. #define SCHEDSTAT_VERSION 12
  369. static int show_schedstat(struct seq_file *seq, void *v)
  370. {
  371. int cpu;
  372. seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
  373. seq_printf(seq, "timestamp %lu\n", jiffies);
  374. for_each_online_cpu(cpu) {
  375. struct rq *rq = cpu_rq(cpu);
  376. #ifdef CONFIG_SMP
  377. struct sched_domain *sd;
  378. int dcnt = 0;
  379. #endif
  380. /* runqueue-specific stats */
  381. seq_printf(seq,
  382. "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
  383. cpu, rq->yld_both_empty,
  384. rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
  385. rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
  386. rq->ttwu_cnt, rq->ttwu_local,
  387. rq->rq_sched_info.cpu_time,
  388. rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
  389. seq_printf(seq, "\n");
  390. #ifdef CONFIG_SMP
  391. /* domain-specific stats */
  392. preempt_disable();
  393. for_each_domain(cpu, sd) {
  394. enum idle_type itype;
  395. char mask_str[NR_CPUS];
  396. cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
  397. seq_printf(seq, "domain%d %s", dcnt++, mask_str);
  398. for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
  399. itype++) {
  400. seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
  401. sd->lb_cnt[itype],
  402. sd->lb_balanced[itype],
  403. sd->lb_failed[itype],
  404. sd->lb_imbalance[itype],
  405. sd->lb_gained[itype],
  406. sd->lb_hot_gained[itype],
  407. sd->lb_nobusyq[itype],
  408. sd->lb_nobusyg[itype]);
  409. }
  410. seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
  411. sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
  412. sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
  413. sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
  414. sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
  415. }
  416. preempt_enable();
  417. #endif
  418. }
  419. return 0;
  420. }
  421. static int schedstat_open(struct inode *inode, struct file *file)
  422. {
  423. unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
  424. char *buf = kmalloc(size, GFP_KERNEL);
  425. struct seq_file *m;
  426. int res;
  427. if (!buf)
  428. return -ENOMEM;
  429. res = single_open(file, show_schedstat, NULL);
  430. if (!res) {
  431. m = file->private_data;
  432. m->buf = buf;
  433. m->size = size;
  434. } else
  435. kfree(buf);
  436. return res;
  437. }
  438. struct file_operations proc_schedstat_operations = {
  439. .open = schedstat_open,
  440. .read = seq_read,
  441. .llseek = seq_lseek,
  442. .release = single_release,
  443. };
  444. # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
  445. # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
  446. #else /* !CONFIG_SCHEDSTATS */
  447. # define schedstat_inc(rq, field) do { } while (0)
  448. # define schedstat_add(rq, field, amt) do { } while (0)
  449. #endif
  450. /*
  451. * rq_lock - lock a given runqueue and disable interrupts.
  452. */
  453. static inline struct rq *this_rq_lock(void)
  454. __acquires(rq->lock)
  455. {
  456. struct rq *rq;
  457. local_irq_disable();
  458. rq = this_rq();
  459. spin_lock(&rq->lock);
  460. return rq;
  461. }
  462. #ifdef CONFIG_SCHEDSTATS
  463. /*
  464. * Called when a process is dequeued from the active array and given
  465. * the cpu. We should note that with the exception of interactive
  466. * tasks, the expired queue will become the active queue after the active
  467. * queue is empty, without explicitly dequeuing and requeuing tasks in the
  468. * expired queue. (Interactive tasks may be requeued directly to the
  469. * active queue, thus delaying tasks in the expired queue from running;
  470. * see scheduler_tick()).
  471. *
  472. * This function is only called from sched_info_arrive(), rather than
  473. * dequeue_task(). Even though a task may be queued and dequeued multiple
  474. * times as it is shuffled about, we're really interested in knowing how
  475. * long it was from the *first* time it was queued to the time that it
  476. * finally hit a cpu.
  477. */
  478. static inline void sched_info_dequeued(struct task_struct *t)
  479. {
  480. t->sched_info.last_queued = 0;
  481. }
  482. /*
  483. * Called when a task finally hits the cpu. We can now calculate how
  484. * long it was waiting to run. We also note when it began so that we
  485. * can keep stats on how long its timeslice is.
  486. */
  487. static void sched_info_arrive(struct task_struct *t)
  488. {
  489. unsigned long now = jiffies, diff = 0;
  490. struct rq *rq = task_rq(t);
  491. if (t->sched_info.last_queued)
  492. diff = now - t->sched_info.last_queued;
  493. sched_info_dequeued(t);
  494. t->sched_info.run_delay += diff;
  495. t->sched_info.last_arrival = now;
  496. t->sched_info.pcnt++;
  497. if (!rq)
  498. return;
  499. rq->rq_sched_info.run_delay += diff;
  500. rq->rq_sched_info.pcnt++;
  501. }
  502. /*
  503. * Called when a process is queued into either the active or expired
  504. * array. The time is noted and later used to determine how long we
  505. * had to wait for us to reach the cpu. Since the expired queue will
  506. * become the active queue after active queue is empty, without dequeuing
  507. * and requeuing any tasks, we are interested in queuing to either. It
  508. * is unusual but not impossible for tasks to be dequeued and immediately
  509. * requeued in the same or another array: this can happen in sched_yield(),
  510. * set_user_nice(), and even load_balance() as it moves tasks from runqueue
  511. * to runqueue.
  512. *
  513. * This function is only called from enqueue_task(), but also only updates
  514. * the timestamp if it is already not set. It's assumed that
  515. * sched_info_dequeued() will clear that stamp when appropriate.
  516. */
  517. static inline void sched_info_queued(struct task_struct *t)
  518. {
  519. if (!t->sched_info.last_queued)
  520. t->sched_info.last_queued = jiffies;
  521. }
  522. /*
  523. * Called when a process ceases being the active-running process, either
  524. * voluntarily or involuntarily. Now we can calculate how long we ran.
  525. */
  526. static inline void sched_info_depart(struct task_struct *t)
  527. {
  528. struct rq *rq = task_rq(t);
  529. unsigned long diff = jiffies - t->sched_info.last_arrival;
  530. t->sched_info.cpu_time += diff;
  531. if (rq)
  532. rq->rq_sched_info.cpu_time += diff;
  533. }
  534. /*
  535. * Called when tasks are switched involuntarily due, typically, to expiring
  536. * their time slice. (This may also be called when switching to or from
  537. * the idle task.) We are only called when prev != next.
  538. */
  539. static inline void
  540. sched_info_switch(struct task_struct *prev, struct task_struct *next)
  541. {
  542. struct rq *rq = task_rq(prev);
  543. /*
  544. * prev now departs the cpu. It's not interesting to record
  545. * stats about how efficient we were at scheduling the idle
  546. * process, however.
  547. */
  548. if (prev != rq->idle)
  549. sched_info_depart(prev);
  550. if (next != rq->idle)
  551. sched_info_arrive(next);
  552. }
  553. #else
  554. #define sched_info_queued(t) do { } while (0)
  555. #define sched_info_switch(t, next) do { } while (0)
  556. #endif /* CONFIG_SCHEDSTATS */
  557. /*
  558. * Adding/removing a task to/from a priority array:
  559. */
  560. static void dequeue_task(struct task_struct *p, struct prio_array *array)
  561. {
  562. array->nr_active--;
  563. list_del(&p->run_list);
  564. if (list_empty(array->queue + p->prio))
  565. __clear_bit(p->prio, array->bitmap);
  566. }
  567. static void enqueue_task(struct task_struct *p, struct prio_array *array)
  568. {
  569. sched_info_queued(p);
  570. list_add_tail(&p->run_list, array->queue + p->prio);
  571. __set_bit(p->prio, array->bitmap);
  572. array->nr_active++;
  573. p->array = array;
  574. }
  575. /*
  576. * Put task to the end of the run list without the overhead of dequeue
  577. * followed by enqueue.
  578. */
  579. static void requeue_task(struct task_struct *p, struct prio_array *array)
  580. {
  581. list_move_tail(&p->run_list, array->queue + p->prio);
  582. }
  583. static inline void
  584. enqueue_task_head(struct task_struct *p, struct prio_array *array)
  585. {
  586. list_add(&p->run_list, array->queue + p->prio);
  587. __set_bit(p->prio, array->bitmap);
  588. array->nr_active++;
  589. p->array = array;
  590. }
  591. /*
  592. * __normal_prio - return the priority that is based on the static
  593. * priority but is modified by bonuses/penalties.
  594. *
  595. * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
  596. * into the -5 ... 0 ... +5 bonus/penalty range.
  597. *
  598. * We use 25% of the full 0...39 priority range so that:
  599. *
  600. * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
  601. * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
  602. *
  603. * Both properties are important to certain workloads.
  604. */
  605. static inline int __normal_prio(struct task_struct *p)
  606. {
  607. int bonus, prio;
  608. bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
  609. prio = p->static_prio - bonus;
  610. if (prio < MAX_RT_PRIO)
  611. prio = MAX_RT_PRIO;
  612. if (prio > MAX_PRIO-1)
  613. prio = MAX_PRIO-1;
  614. return prio;
  615. }
  616. /*
  617. * To aid in avoiding the subversion of "niceness" due to uneven distribution
  618. * of tasks with abnormal "nice" values across CPUs the contribution that
  619. * each task makes to its run queue's load is weighted according to its
  620. * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
  621. * scaled version of the new time slice allocation that they receive on time
  622. * slice expiry etc.
  623. */
  624. /*
  625. * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
  626. * If static_prio_timeslice() is ever changed to break this assumption then
  627. * this code will need modification
  628. */
  629. #define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
  630. #define LOAD_WEIGHT(lp) \
  631. (((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
  632. #define PRIO_TO_LOAD_WEIGHT(prio) \
  633. LOAD_WEIGHT(static_prio_timeslice(prio))
  634. #define RTPRIO_TO_LOAD_WEIGHT(rp) \
  635. (PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
  636. static void set_load_weight(struct task_struct *p)
  637. {
  638. if (has_rt_policy(p)) {
  639. #ifdef CONFIG_SMP
  640. if (p == task_rq(p)->migration_thread)
  641. /*
  642. * The migration thread does the actual balancing.
  643. * Giving its load any weight will skew balancing
  644. * adversely.
  645. */
  646. p->load_weight = 0;
  647. else
  648. #endif
  649. p->load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
  650. } else
  651. p->load_weight = PRIO_TO_LOAD_WEIGHT(p->static_prio);
  652. }
  653. static inline void
  654. inc_raw_weighted_load(struct rq *rq, const struct task_struct *p)
  655. {
  656. rq->raw_weighted_load += p->load_weight;
  657. }
  658. static inline void
  659. dec_raw_weighted_load(struct rq *rq, const struct task_struct *p)
  660. {
  661. rq->raw_weighted_load -= p->load_weight;
  662. }
  663. static inline void inc_nr_running(struct task_struct *p, struct rq *rq)
  664. {
  665. rq->nr_running++;
  666. inc_raw_weighted_load(rq, p);
  667. }
  668. static inline void dec_nr_running(struct task_struct *p, struct rq *rq)
  669. {
  670. rq->nr_running--;
  671. dec_raw_weighted_load(rq, p);
  672. }
  673. /*
  674. * Calculate the expected normal priority: i.e. priority
  675. * without taking RT-inheritance into account. Might be
  676. * boosted by interactivity modifiers. Changes upon fork,
  677. * setprio syscalls, and whenever the interactivity
  678. * estimator recalculates.
  679. */
  680. static inline int normal_prio(struct task_struct *p)
  681. {
  682. int prio;
  683. if (has_rt_policy(p))
  684. prio = MAX_RT_PRIO-1 - p->rt_priority;
  685. else
  686. prio = __normal_prio(p);
  687. return prio;
  688. }
  689. /*
  690. * Calculate the current priority, i.e. the priority
  691. * taken into account by the scheduler. This value might
  692. * be boosted by RT tasks, or might be boosted by
  693. * interactivity modifiers. Will be RT if the task got
  694. * RT-boosted. If not then it returns p->normal_prio.
  695. */
  696. static int effective_prio(struct task_struct *p)
  697. {
  698. p->normal_prio = normal_prio(p);
  699. /*
  700. * If we are RT tasks or we were boosted to RT priority,
  701. * keep the priority unchanged. Otherwise, update priority
  702. * to the normal priority:
  703. */
  704. if (!rt_prio(p->prio))
  705. return p->normal_prio;
  706. return p->prio;
  707. }
  708. /*
  709. * __activate_task - move a task to the runqueue.
  710. */
  711. static void __activate_task(struct task_struct *p, struct rq *rq)
  712. {
  713. struct prio_array *target = rq->active;
  714. if (batch_task(p))
  715. target = rq->expired;
  716. enqueue_task(p, target);
  717. inc_nr_running(p, rq);
  718. }
  719. /*
  720. * __activate_idle_task - move idle task to the _front_ of runqueue.
  721. */
  722. static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
  723. {
  724. enqueue_task_head(p, rq->active);
  725. inc_nr_running(p, rq);
  726. }
  727. /*
  728. * Recalculate p->normal_prio and p->prio after having slept,
  729. * updating the sleep-average too:
  730. */
  731. static int recalc_task_prio(struct task_struct *p, unsigned long long now)
  732. {
  733. /* Caller must always ensure 'now >= p->timestamp' */
  734. unsigned long sleep_time = now - p->timestamp;
  735. if (batch_task(p))
  736. sleep_time = 0;
  737. if (likely(sleep_time > 0)) {
  738. /*
  739. * This ceiling is set to the lowest priority that would allow
  740. * a task to be reinserted into the active array on timeslice
  741. * completion.
  742. */
  743. unsigned long ceiling = INTERACTIVE_SLEEP(p);
  744. if (p->mm && sleep_time > ceiling && p->sleep_avg < ceiling) {
  745. /*
  746. * Prevents user tasks from achieving best priority
  747. * with one single large enough sleep.
  748. */
  749. p->sleep_avg = ceiling;
  750. /*
  751. * Using INTERACTIVE_SLEEP() as a ceiling places a
  752. * nice(0) task 1ms sleep away from promotion, and
  753. * gives it 700ms to round-robin with no chance of
  754. * being demoted. This is more than generous, so
  755. * mark this sleep as non-interactive to prevent the
  756. * on-runqueue bonus logic from intervening should
  757. * this task not receive cpu immediately.
  758. */
  759. p->sleep_type = SLEEP_NONINTERACTIVE;
  760. } else {
  761. /*
  762. * Tasks waking from uninterruptible sleep are
  763. * limited in their sleep_avg rise as they
  764. * are likely to be waiting on I/O
  765. */
  766. if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
  767. if (p->sleep_avg >= ceiling)
  768. sleep_time = 0;
  769. else if (p->sleep_avg + sleep_time >=
  770. ceiling) {
  771. p->sleep_avg = ceiling;
  772. sleep_time = 0;
  773. }
  774. }
  775. /*
  776. * This code gives a bonus to interactive tasks.
  777. *
  778. * The boost works by updating the 'average sleep time'
  779. * value here, based on ->timestamp. The more time a
  780. * task spends sleeping, the higher the average gets -
  781. * and the higher the priority boost gets as well.
  782. */
  783. p->sleep_avg += sleep_time;
  784. }
  785. if (p->sleep_avg > NS_MAX_SLEEP_AVG)
  786. p->sleep_avg = NS_MAX_SLEEP_AVG;
  787. }
  788. return effective_prio(p);
  789. }
  790. /*
  791. * activate_task - move a task to the runqueue and do priority recalculation
  792. *
  793. * Update all the scheduling statistics stuff. (sleep average
  794. * calculation, priority modifiers, etc.)
  795. */
  796. static void activate_task(struct task_struct *p, struct rq *rq, int local)
  797. {
  798. unsigned long long now;
  799. now = sched_clock();
  800. #ifdef CONFIG_SMP
  801. if (!local) {
  802. /* Compensate for drifting sched_clock */
  803. struct rq *this_rq = this_rq();
  804. now = (now - this_rq->timestamp_last_tick)
  805. + rq->timestamp_last_tick;
  806. }
  807. #endif
  808. if (!rt_task(p))
  809. p->prio = recalc_task_prio(p, now);
  810. /*
  811. * This checks to make sure it's not an uninterruptible task
  812. * that is now waking up.
  813. */
  814. if (p->sleep_type == SLEEP_NORMAL) {
  815. /*
  816. * Tasks which were woken up by interrupts (ie. hw events)
  817. * are most likely of interactive nature. So we give them
  818. * the credit of extending their sleep time to the period
  819. * of time they spend on the runqueue, waiting for execution
  820. * on a CPU, first time around:
  821. */
  822. if (in_interrupt())
  823. p->sleep_type = SLEEP_INTERRUPTED;
  824. else {
  825. /*
  826. * Normal first-time wakeups get a credit too for
  827. * on-runqueue time, but it will be weighted down:
  828. */
  829. p->sleep_type = SLEEP_INTERACTIVE;
  830. }
  831. }
  832. p->timestamp = now;
  833. __activate_task(p, rq);
  834. }
  835. /*
  836. * deactivate_task - remove a task from the runqueue.
  837. */
  838. static void deactivate_task(struct task_struct *p, struct rq *rq)
  839. {
  840. dec_nr_running(p, rq);
  841. dequeue_task(p, p->array);
  842. p->array = NULL;
  843. }
  844. /*
  845. * resched_task - mark a task 'to be rescheduled now'.
  846. *
  847. * On UP this means the setting of the need_resched flag, on SMP it
  848. * might also involve a cross-CPU call to trigger the scheduler on
  849. * the target CPU.
  850. */
  851. #ifdef CONFIG_SMP
  852. #ifndef tsk_is_polling
  853. #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
  854. #endif
  855. static void resched_task(struct task_struct *p)
  856. {
  857. int cpu;
  858. assert_spin_locked(&task_rq(p)->lock);
  859. if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
  860. return;
  861. set_tsk_thread_flag(p, TIF_NEED_RESCHED);
  862. cpu = task_cpu(p);
  863. if (cpu == smp_processor_id())
  864. return;
  865. /* NEED_RESCHED must be visible before we test polling */
  866. smp_mb();
  867. if (!tsk_is_polling(p))
  868. smp_send_reschedule(cpu);
  869. }
  870. #else
  871. static inline void resched_task(struct task_struct *p)
  872. {
  873. assert_spin_locked(&task_rq(p)->lock);
  874. set_tsk_need_resched(p);
  875. }
  876. #endif
  877. /**
  878. * task_curr - is this task currently executing on a CPU?
  879. * @p: the task in question.
  880. */
  881. inline int task_curr(const struct task_struct *p)
  882. {
  883. return cpu_curr(task_cpu(p)) == p;
  884. }
  885. /* Used instead of source_load when we know the type == 0 */
  886. unsigned long weighted_cpuload(const int cpu)
  887. {
  888. return cpu_rq(cpu)->raw_weighted_load;
  889. }
  890. #ifdef CONFIG_SMP
  891. struct migration_req {
  892. struct list_head list;
  893. struct task_struct *task;
  894. int dest_cpu;
  895. struct completion done;
  896. };
  897. /*
  898. * The task's runqueue lock must be held.
  899. * Returns true if you have to wait for migration thread.
  900. */
  901. static int
  902. migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
  903. {
  904. struct rq *rq = task_rq(p);
  905. /*
  906. * If the task is not on a runqueue (and not running), then
  907. * it is sufficient to simply update the task's cpu field.
  908. */
  909. if (!p->array && !task_running(rq, p)) {
  910. set_task_cpu(p, dest_cpu);
  911. return 0;
  912. }
  913. init_completion(&req->done);
  914. req->task = p;
  915. req->dest_cpu = dest_cpu;
  916. list_add(&req->list, &rq->migration_queue);
  917. return 1;
  918. }
  919. /*
  920. * wait_task_inactive - wait for a thread to unschedule.
  921. *
  922. * The caller must ensure that the task *will* unschedule sometime soon,
  923. * else this function might spin for a *long* time. This function can't
  924. * be called with interrupts off, or it may introduce deadlock with
  925. * smp_call_function() if an IPI is sent by the same process we are
  926. * waiting to become inactive.
  927. */
  928. void wait_task_inactive(struct task_struct *p)
  929. {
  930. unsigned long flags;
  931. struct rq *rq;
  932. int preempted;
  933. repeat:
  934. rq = task_rq_lock(p, &flags);
  935. /* Must be off runqueue entirely, not preempted. */
  936. if (unlikely(p->array || task_running(rq, p))) {
  937. /* If it's preempted, we yield. It could be a while. */
  938. preempted = !task_running(rq, p);
  939. task_rq_unlock(rq, &flags);
  940. cpu_relax();
  941. if (preempted)
  942. yield();
  943. goto repeat;
  944. }
  945. task_rq_unlock(rq, &flags);
  946. }
  947. /***
  948. * kick_process - kick a running thread to enter/exit the kernel
  949. * @p: the to-be-kicked thread
  950. *
  951. * Cause a process which is running on another CPU to enter
  952. * kernel-mode, without any delay. (to get signals handled.)
  953. *
  954. * NOTE: this function doesnt have to take the runqueue lock,
  955. * because all it wants to ensure is that the remote task enters
  956. * the kernel. If the IPI races and the task has been migrated
  957. * to another CPU then no harm is done and the purpose has been
  958. * achieved as well.
  959. */
  960. void kick_process(struct task_struct *p)
  961. {
  962. int cpu;
  963. preempt_disable();
  964. cpu = task_cpu(p);
  965. if ((cpu != smp_processor_id()) && task_curr(p))
  966. smp_send_reschedule(cpu);
  967. preempt_enable();
  968. }
  969. /*
  970. * Return a low guess at the load of a migration-source cpu weighted
  971. * according to the scheduling class and "nice" value.
  972. *
  973. * We want to under-estimate the load of migration sources, to
  974. * balance conservatively.
  975. */
  976. static inline unsigned long source_load(int cpu, int type)
  977. {
  978. struct rq *rq = cpu_rq(cpu);
  979. if (type == 0)
  980. return rq->raw_weighted_load;
  981. return min(rq->cpu_load[type-1], rq->raw_weighted_load);
  982. }
  983. /*
  984. * Return a high guess at the load of a migration-target cpu weighted
  985. * according to the scheduling class and "nice" value.
  986. */
  987. static inline unsigned long target_load(int cpu, int type)
  988. {
  989. struct rq *rq = cpu_rq(cpu);
  990. if (type == 0)
  991. return rq->raw_weighted_load;
  992. return max(rq->cpu_load[type-1], rq->raw_weighted_load);
  993. }
  994. /*
  995. * Return the average load per task on the cpu's run queue
  996. */
  997. static inline unsigned long cpu_avg_load_per_task(int cpu)
  998. {
  999. struct rq *rq = cpu_rq(cpu);
  1000. unsigned long n = rq->nr_running;
  1001. return n ? rq->raw_weighted_load / n : SCHED_LOAD_SCALE;
  1002. }
  1003. /*
  1004. * find_idlest_group finds and returns the least busy CPU group within the
  1005. * domain.
  1006. */
  1007. static struct sched_group *
  1008. find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
  1009. {
  1010. struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
  1011. unsigned long min_load = ULONG_MAX, this_load = 0;
  1012. int load_idx = sd->forkexec_idx;
  1013. int imbalance = 100 + (sd->imbalance_pct-100)/2;
  1014. do {
  1015. unsigned long load, avg_load;
  1016. int local_group;
  1017. int i;
  1018. /* Skip over this group if it has no CPUs allowed */
  1019. if (!cpus_intersects(group->cpumask, p->cpus_allowed))
  1020. goto nextgroup;
  1021. local_group = cpu_isset(this_cpu, group->cpumask);
  1022. /* Tally up the load of all CPUs in the group */
  1023. avg_load = 0;
  1024. for_each_cpu_mask(i, group->cpumask) {
  1025. /* Bias balancing toward cpus of our domain */
  1026. if (local_group)
  1027. load = source_load(i, load_idx);
  1028. else
  1029. load = target_load(i, load_idx);
  1030. avg_load += load;
  1031. }
  1032. /* Adjust by relative CPU power of the group */
  1033. avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
  1034. if (local_group) {
  1035. this_load = avg_load;
  1036. this = group;
  1037. } else if (avg_load < min_load) {
  1038. min_load = avg_load;
  1039. idlest = group;
  1040. }
  1041. nextgroup:
  1042. group = group->next;
  1043. } while (group != sd->groups);
  1044. if (!idlest || 100*this_load < imbalance*min_load)
  1045. return NULL;
  1046. return idlest;
  1047. }
  1048. /*
  1049. * find_idlest_queue - find the idlest runqueue among the cpus in group.
  1050. */
  1051. static int
  1052. find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  1053. {
  1054. cpumask_t tmp;
  1055. unsigned long load, min_load = ULONG_MAX;
  1056. int idlest = -1;
  1057. int i;
  1058. /* Traverse only the allowed CPUs */
  1059. cpus_and(tmp, group->cpumask, p->cpus_allowed);
  1060. for_each_cpu_mask(i, tmp) {
  1061. load = weighted_cpuload(i);
  1062. if (load < min_load || (load == min_load && i == this_cpu)) {
  1063. min_load = load;
  1064. idlest = i;
  1065. }
  1066. }
  1067. return idlest;
  1068. }
  1069. /*
  1070. * sched_balance_self: balance the current task (running on cpu) in domains
  1071. * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
  1072. * SD_BALANCE_EXEC.
  1073. *
  1074. * Balance, ie. select the least loaded group.
  1075. *
  1076. * Returns the target CPU number, or the same CPU if no balancing is needed.
  1077. *
  1078. * preempt must be disabled.
  1079. */
  1080. static int sched_balance_self(int cpu, int flag)
  1081. {
  1082. struct task_struct *t = current;
  1083. struct sched_domain *tmp, *sd = NULL;
  1084. for_each_domain(cpu, tmp) {
  1085. /*
  1086. * If power savings logic is enabled for a domain, stop there.
  1087. */
  1088. if (tmp->flags & SD_POWERSAVINGS_BALANCE)
  1089. break;
  1090. if (tmp->flags & flag)
  1091. sd = tmp;
  1092. }
  1093. while (sd) {
  1094. cpumask_t span;
  1095. struct sched_group *group;
  1096. int new_cpu;
  1097. int weight;
  1098. span = sd->span;
  1099. group = find_idlest_group(sd, t, cpu);
  1100. if (!group)
  1101. goto nextlevel;
  1102. new_cpu = find_idlest_cpu(group, t, cpu);
  1103. if (new_cpu == -1 || new_cpu == cpu)
  1104. goto nextlevel;
  1105. /* Now try balancing at a lower domain level */
  1106. cpu = new_cpu;
  1107. nextlevel:
  1108. sd = NULL;
  1109. weight = cpus_weight(span);
  1110. for_each_domain(cpu, tmp) {
  1111. if (weight <= cpus_weight(tmp->span))
  1112. break;
  1113. if (tmp->flags & flag)
  1114. sd = tmp;
  1115. }
  1116. /* while loop will break here if sd == NULL */
  1117. }
  1118. return cpu;
  1119. }
  1120. #endif /* CONFIG_SMP */
  1121. /*
  1122. * wake_idle() will wake a task on an idle cpu if task->cpu is
  1123. * not idle and an idle cpu is available. The span of cpus to
  1124. * search starts with cpus closest then further out as needed,
  1125. * so we always favor a closer, idle cpu.
  1126. *
  1127. * Returns the CPU we should wake onto.
  1128. */
  1129. #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
  1130. static int wake_idle(int cpu, struct task_struct *p)
  1131. {
  1132. cpumask_t tmp;
  1133. struct sched_domain *sd;
  1134. int i;
  1135. if (idle_cpu(cpu))
  1136. return cpu;
  1137. for_each_domain(cpu, sd) {
  1138. if (sd->flags & SD_WAKE_IDLE) {
  1139. cpus_and(tmp, sd->span, p->cpus_allowed);
  1140. for_each_cpu_mask(i, tmp) {
  1141. if (idle_cpu(i))
  1142. return i;
  1143. }
  1144. }
  1145. else
  1146. break;
  1147. }
  1148. return cpu;
  1149. }
  1150. #else
  1151. static inline int wake_idle(int cpu, struct task_struct *p)
  1152. {
  1153. return cpu;
  1154. }
  1155. #endif
  1156. /***
  1157. * try_to_wake_up - wake up a thread
  1158. * @p: the to-be-woken-up thread
  1159. * @state: the mask of task states that can be woken
  1160. * @sync: do a synchronous wakeup?
  1161. *
  1162. * Put it on the run-queue if it's not already there. The "current"
  1163. * thread is always on the run-queue (except when the actual
  1164. * re-schedule is in progress), and as such you're allowed to do
  1165. * the simpler "current->state = TASK_RUNNING" to mark yourself
  1166. * runnable without the overhead of this.
  1167. *
  1168. * returns failure only if the task is already active.
  1169. */
  1170. static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
  1171. {
  1172. int cpu, this_cpu, success = 0;
  1173. unsigned long flags;
  1174. long old_state;
  1175. struct rq *rq;
  1176. #ifdef CONFIG_SMP
  1177. struct sched_domain *sd, *this_sd = NULL;
  1178. unsigned long load, this_load;
  1179. int new_cpu;
  1180. #endif
  1181. rq = task_rq_lock(p, &flags);
  1182. old_state = p->state;
  1183. if (!(old_state & state))
  1184. goto out;
  1185. if (p->array)
  1186. goto out_running;
  1187. cpu = task_cpu(p);
  1188. this_cpu = smp_processor_id();
  1189. #ifdef CONFIG_SMP
  1190. if (unlikely(task_running(rq, p)))
  1191. goto out_activate;
  1192. new_cpu = cpu;
  1193. schedstat_inc(rq, ttwu_cnt);
  1194. if (cpu == this_cpu) {
  1195. schedstat_inc(rq, ttwu_local);
  1196. goto out_set_cpu;
  1197. }
  1198. for_each_domain(this_cpu, sd) {
  1199. if (cpu_isset(cpu, sd->span)) {
  1200. schedstat_inc(sd, ttwu_wake_remote);
  1201. this_sd = sd;
  1202. break;
  1203. }
  1204. }
  1205. if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
  1206. goto out_set_cpu;
  1207. /*
  1208. * Check for affine wakeup and passive balancing possibilities.
  1209. */
  1210. if (this_sd) {
  1211. int idx = this_sd->wake_idx;
  1212. unsigned int imbalance;
  1213. imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
  1214. load = source_load(cpu, idx);
  1215. this_load = target_load(this_cpu, idx);
  1216. new_cpu = this_cpu; /* Wake to this CPU if we can */
  1217. if (this_sd->flags & SD_WAKE_AFFINE) {
  1218. unsigned long tl = this_load;
  1219. unsigned long tl_per_task = cpu_avg_load_per_task(this_cpu);
  1220. /*
  1221. * If sync wakeup then subtract the (maximum possible)
  1222. * effect of the currently running task from the load
  1223. * of the current CPU:
  1224. */
  1225. if (sync)
  1226. tl -= current->load_weight;
  1227. if ((tl <= load &&
  1228. tl + target_load(cpu, idx) <= tl_per_task) ||
  1229. 100*(tl + p->load_weight) <= imbalance*load) {
  1230. /*
  1231. * This domain has SD_WAKE_AFFINE and
  1232. * p is cache cold in this domain, and
  1233. * there is no bad imbalance.
  1234. */
  1235. schedstat_inc(this_sd, ttwu_move_affine);
  1236. goto out_set_cpu;
  1237. }
  1238. }
  1239. /*
  1240. * Start passive balancing when half the imbalance_pct
  1241. * limit is reached.
  1242. */
  1243. if (this_sd->flags & SD_WAKE_BALANCE) {
  1244. if (imbalance*this_load <= 100*load) {
  1245. schedstat_inc(this_sd, ttwu_move_balance);
  1246. goto out_set_cpu;
  1247. }
  1248. }
  1249. }
  1250. new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
  1251. out_set_cpu:
  1252. new_cpu = wake_idle(new_cpu, p);
  1253. if (new_cpu != cpu) {
  1254. set_task_cpu(p, new_cpu);
  1255. task_rq_unlock(rq, &flags);
  1256. /* might preempt at this point */
  1257. rq = task_rq_lock(p, &flags);
  1258. old_state = p->state;
  1259. if (!(old_state & state))
  1260. goto out;
  1261. if (p->array)
  1262. goto out_running;
  1263. this_cpu = smp_processor_id();
  1264. cpu = task_cpu(p);
  1265. }
  1266. out_activate:
  1267. #endif /* CONFIG_SMP */
  1268. if (old_state == TASK_UNINTERRUPTIBLE) {
  1269. rq->nr_uninterruptible--;
  1270. /*
  1271. * Tasks on involuntary sleep don't earn
  1272. * sleep_avg beyond just interactive state.
  1273. */
  1274. p->sleep_type = SLEEP_NONINTERACTIVE;
  1275. } else
  1276. /*
  1277. * Tasks that have marked their sleep as noninteractive get
  1278. * woken up with their sleep average not weighted in an
  1279. * interactive way.
  1280. */
  1281. if (old_state & TASK_NONINTERACTIVE)
  1282. p->sleep_type = SLEEP_NONINTERACTIVE;
  1283. activate_task(p, rq, cpu == this_cpu);
  1284. /*
  1285. * Sync wakeups (i.e. those types of wakeups where the waker
  1286. * has indicated that it will leave the CPU in short order)
  1287. * don't trigger a preemption, if the woken up task will run on
  1288. * this cpu. (in this case the 'I will reschedule' promise of
  1289. * the waker guarantees that the freshly woken up task is going
  1290. * to be considered on this CPU.)
  1291. */
  1292. if (!sync || cpu != this_cpu) {
  1293. if (TASK_PREEMPTS_CURR(p, rq))
  1294. resched_task(rq->curr);
  1295. }
  1296. success = 1;
  1297. out_running:
  1298. p->state = TASK_RUNNING;
  1299. out:
  1300. task_rq_unlock(rq, &flags);
  1301. return success;
  1302. }
  1303. int fastcall wake_up_process(struct task_struct *p)
  1304. {
  1305. return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
  1306. TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
  1307. }
  1308. EXPORT_SYMBOL(wake_up_process);
  1309. int fastcall wake_up_state(struct task_struct *p, unsigned int state)
  1310. {
  1311. return try_to_wake_up(p, state, 0);
  1312. }
  1313. /*
  1314. * Perform scheduler related setup for a newly forked process p.
  1315. * p is forked by current.
  1316. */
  1317. void fastcall sched_fork(struct task_struct *p, int clone_flags)
  1318. {
  1319. int cpu = get_cpu();
  1320. #ifdef CONFIG_SMP
  1321. cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
  1322. #endif
  1323. set_task_cpu(p, cpu);
  1324. /*
  1325. * We mark the process as running here, but have not actually
  1326. * inserted it onto the runqueue yet. This guarantees that
  1327. * nobody will actually run it, and a signal or other external
  1328. * event cannot wake it up and insert it on the runqueue either.
  1329. */
  1330. p->state = TASK_RUNNING;
  1331. /*
  1332. * Make sure we do not leak PI boosting priority to the child:
  1333. */
  1334. p->prio = current->normal_prio;
  1335. INIT_LIST_HEAD(&p->run_list);
  1336. p->array = NULL;
  1337. #ifdef CONFIG_SCHEDSTATS
  1338. memset(&p->sched_info, 0, sizeof(p->sched_info));
  1339. #endif
  1340. #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
  1341. p->oncpu = 0;
  1342. #endif
  1343. #ifdef CONFIG_PREEMPT
  1344. /* Want to start with kernel preemption disabled. */
  1345. task_thread_info(p)->preempt_count = 1;
  1346. #endif
  1347. /*
  1348. * Share the timeslice between parent and child, thus the
  1349. * total amount of pending timeslices in the system doesn't change,
  1350. * resulting in more scheduling fairness.
  1351. */
  1352. local_irq_disable();
  1353. p->time_slice = (current->time_slice + 1) >> 1;
  1354. /*
  1355. * The remainder of the first timeslice might be recovered by
  1356. * the parent if the child exits early enough.
  1357. */
  1358. p->first_time_slice = 1;
  1359. current->time_slice >>= 1;
  1360. p->timestamp = sched_clock();
  1361. if (unlikely(!current->time_slice)) {
  1362. /*
  1363. * This case is rare, it happens when the parent has only
  1364. * a single jiffy left from its timeslice. Taking the
  1365. * runqueue lock is not a problem.
  1366. */
  1367. current->time_slice = 1;
  1368. scheduler_tick();
  1369. }
  1370. local_irq_enable();
  1371. put_cpu();
  1372. }
  1373. /*
  1374. * wake_up_new_task - wake up a newly created task for the first time.
  1375. *
  1376. * This function will do some initial scheduler statistics housekeeping
  1377. * that must be done for every newly created context, then puts the task
  1378. * on the runqueue and wakes it.
  1379. */
  1380. void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
  1381. {
  1382. struct rq *rq, *this_rq;
  1383. unsigned long flags;
  1384. int this_cpu, cpu;
  1385. rq = task_rq_lock(p, &flags);
  1386. BUG_ON(p->state != TASK_RUNNING);
  1387. this_cpu = smp_processor_id();
  1388. cpu = task_cpu(p);
  1389. /*
  1390. * We decrease the sleep average of forking parents
  1391. * and children as well, to keep max-interactive tasks
  1392. * from forking tasks that are max-interactive. The parent
  1393. * (current) is done further down, under its lock.
  1394. */
  1395. p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
  1396. CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
  1397. p->prio = effective_prio(p);
  1398. if (likely(cpu == this_cpu)) {
  1399. if (!(clone_flags & CLONE_VM)) {
  1400. /*
  1401. * The VM isn't cloned, so we're in a good position to
  1402. * do child-runs-first in anticipation of an exec. This
  1403. * usually avoids a lot of COW overhead.
  1404. */
  1405. if (unlikely(!current->array))
  1406. __activate_task(p, rq);
  1407. else {
  1408. p->prio = current->prio;
  1409. p->normal_prio = current->normal_prio;
  1410. list_add_tail(&p->run_list, &current->run_list);
  1411. p->array = current->array;
  1412. p->array->nr_active++;
  1413. inc_nr_running(p, rq);
  1414. }
  1415. set_need_resched();
  1416. } else
  1417. /* Run child last */
  1418. __activate_task(p, rq);
  1419. /*
  1420. * We skip the following code due to cpu == this_cpu
  1421. *
  1422. * task_rq_unlock(rq, &flags);
  1423. * this_rq = task_rq_lock(current, &flags);
  1424. */
  1425. this_rq = rq;
  1426. } else {
  1427. this_rq = cpu_rq(this_cpu);
  1428. /*
  1429. * Not the local CPU - must adjust timestamp. This should
  1430. * get optimised away in the !CONFIG_SMP case.
  1431. */
  1432. p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
  1433. + rq->timestamp_last_tick;
  1434. __activate_task(p, rq);
  1435. if (TASK_PREEMPTS_CURR(p, rq))
  1436. resched_task(rq->curr);
  1437. /*
  1438. * Parent and child are on different CPUs, now get the
  1439. * parent runqueue to update the parent's ->sleep_avg:
  1440. */
  1441. task_rq_unlock(rq, &flags);
  1442. this_rq = task_rq_lock(current, &flags);
  1443. }
  1444. current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
  1445. PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
  1446. task_rq_unlock(this_rq, &flags);
  1447. }
  1448. /*
  1449. * Potentially available exiting-child timeslices are
  1450. * retrieved here - this way the parent does not get
  1451. * penalized for creating too many threads.
  1452. *
  1453. * (this cannot be used to 'generate' timeslices
  1454. * artificially, because any timeslice recovered here
  1455. * was given away by the parent in the first place.)
  1456. */
  1457. void fastcall sched_exit(struct task_struct *p)
  1458. {
  1459. unsigned long flags;
  1460. struct rq *rq;
  1461. /*
  1462. * If the child was a (relative-) CPU hog then decrease
  1463. * the sleep_avg of the parent as well.
  1464. */
  1465. rq = task_rq_lock(p->parent, &flags);
  1466. if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
  1467. p->parent->time_slice += p->time_slice;
  1468. if (unlikely(p->parent->time_slice > task_timeslice(p)))
  1469. p->parent->time_slice = task_timeslice(p);
  1470. }
  1471. if (p->sleep_avg < p->parent->sleep_avg)
  1472. p->parent->sleep_avg = p->parent->sleep_avg /
  1473. (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
  1474. (EXIT_WEIGHT + 1);
  1475. task_rq_unlock(rq, &flags);
  1476. }
  1477. /**
  1478. * prepare_task_switch - prepare to switch tasks
  1479. * @rq: the runqueue preparing to switch
  1480. * @next: the task we are going to switch to.
  1481. *
  1482. * This is called with the rq lock held and interrupts off. It must
  1483. * be paired with a subsequent finish_task_switch after the context
  1484. * switch.
  1485. *
  1486. * prepare_task_switch sets up locking and calls architecture specific
  1487. * hooks.
  1488. */
  1489. static inline void prepare_task_switch(struct rq *rq, struct task_struct *next)
  1490. {
  1491. prepare_lock_switch(rq, next);
  1492. prepare_arch_switch(next);
  1493. }
  1494. /**
  1495. * finish_task_switch - clean up after a task-switch
  1496. * @rq: runqueue associated with task-switch
  1497. * @prev: the thread we just switched away from.
  1498. *
  1499. * finish_task_switch must be called after the context switch, paired
  1500. * with a prepare_task_switch call before the context switch.
  1501. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  1502. * and do any other architecture-specific cleanup actions.
  1503. *
  1504. * Note that we may have delayed dropping an mm in context_switch(). If
  1505. * so, we finish that here outside of the runqueue lock. (Doing it
  1506. * with the lock held can cause deadlocks; see schedule() for
  1507. * details.)
  1508. */
  1509. static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
  1510. __releases(rq->lock)
  1511. {
  1512. struct mm_struct *mm = rq->prev_mm;
  1513. unsigned long prev_task_flags;
  1514. rq->prev_mm = NULL;
  1515. /*
  1516. * A task struct has one reference for the use as "current".
  1517. * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
  1518. * calls schedule one last time. The schedule call will never return,
  1519. * and the scheduled task must drop that reference.
  1520. * The test for EXIT_ZOMBIE must occur while the runqueue locks are
  1521. * still held, otherwise prev could be scheduled on another cpu, die
  1522. * there before we look at prev->state, and then the reference would
  1523. * be dropped twice.
  1524. * Manfred Spraul <manfred@colorfullife.com>
  1525. */
  1526. prev_task_flags = prev->flags;
  1527. finish_arch_switch(prev);
  1528. finish_lock_switch(rq, prev);
  1529. if (mm)
  1530. mmdrop(mm);
  1531. if (unlikely(prev_task_flags & PF_DEAD)) {
  1532. /*
  1533. * Remove function-return probe instances associated with this
  1534. * task and put them back on the free list.
  1535. */
  1536. kprobe_flush_task(prev);
  1537. put_task_struct(prev);
  1538. }
  1539. }
  1540. /**
  1541. * schedule_tail - first thing a freshly forked thread must call.
  1542. * @prev: the thread we just switched away from.
  1543. */
  1544. asmlinkage void schedule_tail(struct task_struct *prev)
  1545. __releases(rq->lock)
  1546. {
  1547. struct rq *rq = this_rq();
  1548. finish_task_switch(rq, prev);
  1549. #ifdef __ARCH_WANT_UNLOCKED_CTXSW
  1550. /* In this case, finish_task_switch does not reenable preemption */
  1551. preempt_enable();
  1552. #endif
  1553. if (current->set_child_tid)
  1554. put_user(current->pid, current->set_child_tid);
  1555. }
  1556. /*
  1557. * context_switch - switch to the new MM and the new
  1558. * thread's register state.
  1559. */
  1560. static inline struct task_struct *
  1561. context_switch(struct rq *rq, struct task_struct *prev,
  1562. struct task_struct *next)
  1563. {
  1564. struct mm_struct *mm = next->mm;
  1565. struct mm_struct *oldmm = prev->active_mm;
  1566. if (unlikely(!mm)) {
  1567. next->active_mm = oldmm;
  1568. atomic_inc(&oldmm->mm_count);
  1569. enter_lazy_tlb(oldmm, next);
  1570. } else
  1571. switch_mm(oldmm, mm, next);
  1572. if (unlikely(!prev->mm)) {
  1573. prev->active_mm = NULL;
  1574. WARN_ON(rq->prev_mm);
  1575. rq->prev_mm = oldmm;
  1576. }
  1577. spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
  1578. /* Here we just switch the register state and the stack. */
  1579. switch_to(prev, next, prev);
  1580. return prev;
  1581. }
  1582. /*
  1583. * nr_running, nr_uninterruptible and nr_context_switches:
  1584. *
  1585. * externally visible scheduler statistics: current number of runnable
  1586. * threads, current number of uninterruptible-sleeping threads, total
  1587. * number of context switches performed since bootup.
  1588. */
  1589. unsigned long nr_running(void)
  1590. {
  1591. unsigned long i, sum = 0;
  1592. for_each_online_cpu(i)
  1593. sum += cpu_rq(i)->nr_running;
  1594. return sum;
  1595. }
  1596. unsigned long nr_uninterruptible(void)
  1597. {
  1598. unsigned long i, sum = 0;
  1599. for_each_possible_cpu(i)
  1600. sum += cpu_rq(i)->nr_uninterruptible;
  1601. /*
  1602. * Since we read the counters lockless, it might be slightly
  1603. * inaccurate. Do not allow it to go below zero though:
  1604. */
  1605. if (unlikely((long)sum < 0))
  1606. sum = 0;
  1607. return sum;
  1608. }
  1609. unsigned long long nr_context_switches(void)
  1610. {
  1611. int i;
  1612. unsigned long long sum = 0;
  1613. for_each_possible_cpu(i)
  1614. sum += cpu_rq(i)->nr_switches;
  1615. return sum;
  1616. }
  1617. unsigned long nr_iowait(void)
  1618. {
  1619. unsigned long i, sum = 0;
  1620. for_each_possible_cpu(i)
  1621. sum += atomic_read(&cpu_rq(i)->nr_iowait);
  1622. return sum;
  1623. }
  1624. unsigned long nr_active(void)
  1625. {
  1626. unsigned long i, running = 0, uninterruptible = 0;
  1627. for_each_online_cpu(i) {
  1628. running += cpu_rq(i)->nr_running;
  1629. uninterruptible += cpu_rq(i)->nr_uninterruptible;
  1630. }
  1631. if (unlikely((long)uninterruptible < 0))
  1632. uninterruptible = 0;
  1633. return running + uninterruptible;
  1634. }
  1635. #ifdef CONFIG_SMP
  1636. /*
  1637. * Is this task likely cache-hot:
  1638. */
  1639. static inline int
  1640. task_hot(struct task_struct *p, unsigned long long now, struct sched_domain *sd)
  1641. {
  1642. return (long long)(now - p->last_ran) < (long long)sd->cache_hot_time;
  1643. }
  1644. /*
  1645. * double_rq_lock - safely lock two runqueues
  1646. *
  1647. * Note this does not disable interrupts like task_rq_lock,
  1648. * you need to do so manually before calling.
  1649. */
  1650. static void double_rq_lock(struct rq *rq1, struct rq *rq2)
  1651. __acquires(rq1->lock)
  1652. __acquires(rq2->lock)
  1653. {
  1654. if (rq1 == rq2) {
  1655. spin_lock(&rq1->lock);
  1656. __acquire(rq2->lock); /* Fake it out ;) */
  1657. } else {
  1658. if (rq1 < rq2) {
  1659. spin_lock(&rq1->lock);
  1660. spin_lock(&rq2->lock);
  1661. } else {
  1662. spin_lock(&rq2->lock);
  1663. spin_lock(&rq1->lock);
  1664. }
  1665. }
  1666. }
  1667. /*
  1668. * double_rq_unlock - safely unlock two runqueues
  1669. *
  1670. * Note this does not restore interrupts like task_rq_unlock,
  1671. * you need to do so manually after calling.
  1672. */
  1673. static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
  1674. __releases(rq1->lock)
  1675. __releases(rq2->lock)
  1676. {
  1677. spin_unlock(&rq1->lock);
  1678. if (rq1 != rq2)
  1679. spin_unlock(&rq2->lock);
  1680. else
  1681. __release(rq2->lock);
  1682. }
  1683. /*
  1684. * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
  1685. */
  1686. static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
  1687. __releases(this_rq->lock)
  1688. __acquires(busiest->lock)
  1689. __acquires(this_rq->lock)
  1690. {
  1691. if (unlikely(!spin_trylock(&busiest->lock))) {
  1692. if (busiest < this_rq) {
  1693. spin_unlock(&this_rq->lock);
  1694. spin_lock(&busiest->lock);
  1695. spin_lock(&this_rq->lock);
  1696. } else
  1697. spin_lock(&busiest->lock);
  1698. }
  1699. }
  1700. /*
  1701. * If dest_cpu is allowed for this process, migrate the task to it.
  1702. * This is accomplished by forcing the cpu_allowed mask to only
  1703. * allow dest_cpu, which will force the cpu onto dest_cpu. Then
  1704. * the cpu_allowed mask is restored.
  1705. */
  1706. static void sched_migrate_task(struct task_struct *p, int dest_cpu)
  1707. {
  1708. struct migration_req req;
  1709. unsigned long flags;
  1710. struct rq *rq;
  1711. rq = task_rq_lock(p, &flags);
  1712. if (!cpu_isset(dest_cpu, p->cpus_allowed)
  1713. || unlikely(cpu_is_offline(dest_cpu)))
  1714. goto out;
  1715. /* force the process onto the specified CPU */
  1716. if (migrate_task(p, dest_cpu, &req)) {
  1717. /* Need to wait for migration thread (might exit: take ref). */
  1718. struct task_struct *mt = rq->migration_thread;
  1719. get_task_struct(mt);
  1720. task_rq_unlock(rq, &flags);
  1721. wake_up_process(mt);
  1722. put_task_struct(mt);
  1723. wait_for_completion(&req.done);
  1724. return;
  1725. }
  1726. out:
  1727. task_rq_unlock(rq, &flags);
  1728. }
  1729. /*
  1730. * sched_exec - execve() is a valuable balancing opportunity, because at
  1731. * this point the task has the smallest effective memory and cache footprint.
  1732. */
  1733. void sched_exec(void)
  1734. {
  1735. int new_cpu, this_cpu = get_cpu();
  1736. new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
  1737. put_cpu();
  1738. if (new_cpu != this_cpu)
  1739. sched_migrate_task(current, new_cpu);
  1740. }
  1741. /*
  1742. * pull_task - move a task from a remote runqueue to the local runqueue.
  1743. * Both runqueues must be locked.
  1744. */
  1745. static void pull_task(struct rq *src_rq, struct prio_array *src_array,
  1746. struct task_struct *p, struct rq *this_rq,
  1747. struct prio_array *this_array, int this_cpu)
  1748. {
  1749. dequeue_task(p, src_array);
  1750. dec_nr_running(p, src_rq);
  1751. set_task_cpu(p, this_cpu);
  1752. inc_nr_running(p, this_rq);
  1753. enqueue_task(p, this_array);
  1754. p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
  1755. + this_rq->timestamp_last_tick;
  1756. /*
  1757. * Note that idle threads have a prio of MAX_PRIO, for this test
  1758. * to be always true for them.
  1759. */
  1760. if (TASK_PREEMPTS_CURR(p, this_rq))
  1761. resched_task(this_rq->curr);
  1762. }
  1763. /*
  1764. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  1765. */
  1766. static
  1767. int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
  1768. struct sched_domain *sd, enum idle_type idle,
  1769. int *all_pinned)
  1770. {
  1771. /*
  1772. * We do not migrate tasks that are:
  1773. * 1) running (obviously), or
  1774. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  1775. * 3) are cache-hot on their current CPU.
  1776. */
  1777. if (!cpu_isset(this_cpu, p->cpus_allowed))
  1778. return 0;
  1779. *all_pinned = 0;
  1780. if (task_running(rq, p))
  1781. return 0;
  1782. /*
  1783. * Aggressive migration if:
  1784. * 1) task is cache cold, or
  1785. * 2) too many balance attempts have failed.
  1786. */
  1787. if (sd->nr_balance_failed > sd->cache_nice_tries)
  1788. return 1;
  1789. if (task_hot(p, rq->timestamp_last_tick, sd))
  1790. return 0;
  1791. return 1;
  1792. }
  1793. #define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
  1794. /*
  1795. * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
  1796. * load from busiest to this_rq, as part of a balancing operation within
  1797. * "domain". Returns the number of tasks moved.
  1798. *
  1799. * Called with both runqueues locked.
  1800. */
  1801. static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
  1802. unsigned long max_nr_move, unsigned long max_load_move,
  1803. struct sched_domain *sd, enum idle_type idle,
  1804. int *all_pinned)
  1805. {
  1806. int idx, pulled = 0, pinned = 0, this_best_prio, best_prio,
  1807. best_prio_seen, skip_for_load;
  1808. struct prio_array *array, *dst_array;
  1809. struct list_head *head, *curr;
  1810. struct task_struct *tmp;
  1811. long rem_load_move;
  1812. if (max_nr_move == 0 || max_load_move == 0)
  1813. goto out;
  1814. rem_load_move = max_load_move;
  1815. pinned = 1;
  1816. this_best_prio = rq_best_prio(this_rq);
  1817. best_prio = rq_best_prio(busiest);
  1818. /*
  1819. * Enable handling of the case where there is more than one task
  1820. * with the best priority. If the current running task is one
  1821. * of those with prio==best_prio we know it won't be moved
  1822. * and therefore it's safe to override the skip (based on load) of
  1823. * any task we find with that prio.
  1824. */
  1825. best_prio_seen = best_prio == busiest->curr->prio;
  1826. /*
  1827. * We first consider expired tasks. Those will likely not be
  1828. * executed in the near future, and they are most likely to
  1829. * be cache-cold, thus switching CPUs has the least effect
  1830. * on them.
  1831. */
  1832. if (busiest->expired->nr_active) {
  1833. array = busiest->expired;
  1834. dst_array = this_rq->expired;
  1835. } else {
  1836. array = busiest->active;
  1837. dst_array = this_rq->active;
  1838. }
  1839. new_array:
  1840. /* Start searching at priority 0: */
  1841. idx = 0;
  1842. skip_bitmap:
  1843. if (!idx)
  1844. idx = sched_find_first_bit(array->bitmap);
  1845. else
  1846. idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
  1847. if (idx >= MAX_PRIO) {
  1848. if (array == busiest->expired && busiest->active->nr_active) {
  1849. array = busiest->active;
  1850. dst_array = this_rq->active;
  1851. goto new_array;
  1852. }
  1853. goto out;
  1854. }
  1855. head = array->queue + idx;
  1856. curr = head->prev;
  1857. skip_queue:
  1858. tmp = list_entry(curr, struct task_struct, run_list);
  1859. curr = curr->prev;
  1860. /*
  1861. * To help distribute high priority tasks accross CPUs we don't
  1862. * skip a task if it will be the highest priority task (i.e. smallest
  1863. * prio value) on its new queue regardless of its load weight
  1864. */
  1865. skip_for_load = tmp->load_weight > rem_load_move;
  1866. if (skip_for_load && idx < this_best_prio)
  1867. skip_for_load = !best_prio_seen && idx == best_prio;
  1868. if (skip_for_load ||
  1869. !can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
  1870. best_prio_seen |= idx == best_prio;
  1871. if (curr != head)
  1872. goto skip_queue;
  1873. idx++;
  1874. goto skip_bitmap;
  1875. }
  1876. #ifdef CONFIG_SCHEDSTATS
  1877. if (task_hot(tmp, busiest->timestamp_last_tick, sd))
  1878. schedstat_inc(sd, lb_hot_gained[idle]);
  1879. #endif
  1880. pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
  1881. pulled++;
  1882. rem_load_move -= tmp->load_weight;
  1883. /*
  1884. * We only want to steal up to the prescribed number of tasks
  1885. * and the prescribed amount of weighted load.
  1886. */
  1887. if (pulled < max_nr_move && rem_load_move > 0) {
  1888. if (idx < this_best_prio)
  1889. this_best_prio = idx;
  1890. if (curr != head)
  1891. goto skip_queue;
  1892. idx++;
  1893. goto skip_bitmap;
  1894. }
  1895. out:
  1896. /*
  1897. * Right now, this is the only place pull_task() is called,
  1898. * so we can safely collect pull_task() stats here rather than
  1899. * inside pull_task().
  1900. */
  1901. schedstat_add(sd, lb_gained[idle], pulled);
  1902. if (all_pinned)
  1903. *all_pinned = pinned;
  1904. return pulled;
  1905. }
  1906. /*
  1907. * find_busiest_group finds and returns the busiest CPU group within the
  1908. * domain. It calculates and returns the amount of weighted load which
  1909. * should be moved to restore balance via the imbalance parameter.
  1910. */
  1911. static struct sched_group *
  1912. find_busiest_group(struct sched_domain *sd, int this_cpu,
  1913. unsigned long *imbalance, enum idle_type idle, int *sd_idle)
  1914. {
  1915. struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
  1916. unsigned long max_load, avg_load, total_load, this_load, total_pwr;
  1917. unsigned long max_pull;
  1918. unsigned long busiest_load_per_task, busiest_nr_running;
  1919. unsigned long this_load_per_task, this_nr_running;
  1920. int load_idx;
  1921. #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
  1922. int power_savings_balance = 1;
  1923. unsigned long leader_nr_running = 0, min_load_per_task = 0;
  1924. unsigned long min_nr_running = ULONG_MAX;
  1925. struct sched_group *group_min = NULL, *group_leader = NULL;
  1926. #endif
  1927. max_load = this_load = total_load = total_pwr = 0;
  1928. busiest_load_per_task = busiest_nr_running = 0;
  1929. this_load_per_task = this_nr_running = 0;
  1930. if (idle == NOT_IDLE)
  1931. load_idx = sd->busy_idx;
  1932. else if (idle == NEWLY_IDLE)
  1933. load_idx = sd->newidle_idx;
  1934. else
  1935. load_idx = sd->idle_idx;
  1936. do {
  1937. unsigned long load, group_capacity;
  1938. int local_group;
  1939. int i;
  1940. unsigned long sum_nr_running, sum_weighted_load;
  1941. local_group = cpu_isset(this_cpu, group->cpumask);
  1942. /* Tally up the load of all CPUs in the group */
  1943. sum_weighted_load = sum_nr_running = avg_load = 0;
  1944. for_each_cpu_mask(i, group->cpumask) {
  1945. struct rq *rq = cpu_rq(i);
  1946. if (*sd_idle && !idle_cpu(i))
  1947. *sd_idle = 0;
  1948. /* Bias balancing toward cpus of our domain */
  1949. if (local_group)
  1950. load = target_load(i, load_idx);
  1951. else
  1952. load = source_load(i, load_idx);
  1953. avg_load += load;
  1954. sum_nr_running += rq->nr_running;
  1955. sum_weighted_load += rq->raw_weighted_load;
  1956. }
  1957. total_load += avg_load;
  1958. total_pwr += group->cpu_power;
  1959. /* Adjust by relative CPU power of the group */
  1960. avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
  1961. group_capacity = group->cpu_power / SCHED_LOAD_SCALE;
  1962. if (local_group) {
  1963. this_load = avg_load;
  1964. this = group;
  1965. this_nr_running = sum_nr_running;
  1966. this_load_per_task = sum_weighted_load;
  1967. } else if (avg_load > max_load &&
  1968. sum_nr_running > group_capacity) {
  1969. max_load = avg_load;
  1970. busiest = group;
  1971. busiest_nr_running = sum_nr_running;
  1972. busiest_load_per_task = sum_weighted_load;
  1973. }
  1974. #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
  1975. /*
  1976. * Busy processors will not participate in power savings
  1977. * balance.
  1978. */
  1979. if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
  1980. goto group_next;
  1981. /*
  1982. * If the local group is idle or completely loaded
  1983. * no need to do power savings balance at this domain
  1984. */
  1985. if (local_group && (this_nr_running >= group_capacity ||
  1986. !this_nr_running))
  1987. power_savings_balance = 0;
  1988. /*
  1989. * If a group is already running at full capacity or idle,
  1990. * don't include that group in power savings calculations
  1991. */
  1992. if (!power_savings_balance || sum_nr_running >= group_capacity
  1993. || !sum_nr_running)
  1994. goto group_next;
  1995. /*
  1996. * Calculate the group which has the least non-idle load.
  1997. * This is the group from where we need to pick up the load
  1998. * for saving power
  1999. */
  2000. if ((sum_nr_running < min_nr_running) ||
  2001. (sum_nr_running == min_nr_running &&
  2002. first_cpu(group->cpumask) <
  2003. first_cpu(group_min->cpumask))) {
  2004. group_min = group;
  2005. min_nr_running = sum_nr_running;
  2006. min_load_per_task = sum_weighted_load /
  2007. sum_nr_running;
  2008. }
  2009. /*
  2010. * Calculate the group which is almost near its
  2011. * capacity but still has some space to pick up some load
  2012. * from other group and save more power
  2013. */
  2014. if (sum_nr_running <= group_capacity - 1) {
  2015. if (sum_nr_running > leader_nr_running ||
  2016. (sum_nr_running == leader_nr_running &&
  2017. first_cpu(group->cpumask) >
  2018. first_cpu(group_leader->cpumask))) {
  2019. group_leader = group;
  2020. leader_nr_running = sum_nr_running;
  2021. }
  2022. }
  2023. group_next:
  2024. #endif
  2025. group = group->next;
  2026. } while (group != sd->groups);
  2027. if (!busiest || this_load >= max_load || busiest_nr_running == 0)
  2028. goto out_balanced;
  2029. avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
  2030. if (this_load >= avg_load ||
  2031. 100*max_load <= sd->imbalance_pct*this_load)
  2032. goto out_balanced;
  2033. busiest_load_per_task /= busiest_nr_running;
  2034. /*
  2035. * We're trying to get all the cpus to the average_load, so we don't
  2036. * want to push ourselves above the average load, nor do we wish to
  2037. * reduce the max loaded cpu below the average load, as either of these
  2038. * actions would just result in more rebalancing later, and ping-pong
  2039. * tasks around. Thus we look for the minimum possible imbalance.
  2040. * Negative imbalances (*we* are more loaded than anyone else) will
  2041. * be counted as no imbalance for these purposes -- we can't fix that
  2042. * by pulling tasks to us. Be careful of negative numbers as they'll
  2043. * appear as very large values with unsigned longs.
  2044. */
  2045. if (max_load <= busiest_load_per_task)
  2046. goto out_balanced;
  2047. /*
  2048. * In the presence of smp nice balancing, certain scenarios can have
  2049. * max load less than avg load(as we skip the groups at or below
  2050. * its cpu_power, while calculating max_load..)
  2051. */
  2052. if (max_load < avg_load) {
  2053. *imbalance = 0;
  2054. goto small_imbalance;
  2055. }
  2056. /* Don't want to pull so many tasks that a group would go idle */
  2057. max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
  2058. /* How much load to actually move to equalise the imbalance */
  2059. *imbalance = min(max_pull * busiest->cpu_power,
  2060. (avg_load - this_load) * this->cpu_power)
  2061. / SCHED_LOAD_SCALE;
  2062. /*
  2063. * if *imbalance is less than the average load per runnable task
  2064. * there is no gaurantee that any tasks will be moved so we'll have
  2065. * a think about bumping its value to force at least one task to be
  2066. * moved
  2067. */
  2068. if (*imbalance < busiest_load_per_task) {
  2069. unsigned long tmp, pwr_now, pwr_move;
  2070. unsigned int imbn;
  2071. small_imbalance:
  2072. pwr_move = pwr_now = 0;
  2073. imbn = 2;
  2074. if (this_nr_running) {
  2075. this_load_per_task /= this_nr_running;
  2076. if (busiest_load_per_task > this_load_per_task)
  2077. imbn = 1;
  2078. } else
  2079. this_load_per_task = SCHED_LOAD_SCALE;
  2080. if (max_load - this_load >= busiest_load_per_task * imbn) {
  2081. *imbalance = busiest_load_per_task;
  2082. return busiest;
  2083. }
  2084. /*
  2085. * OK, we don't have enough imbalance to justify moving tasks,
  2086. * however we may be able to increase total CPU power used by
  2087. * moving them.
  2088. */
  2089. pwr_now += busiest->cpu_power *
  2090. min(busiest_load_per_task, max_load);
  2091. pwr_now += this->cpu_power *
  2092. min(this_load_per_task, this_load);
  2093. pwr_now /= SCHED_LOAD_SCALE;
  2094. /* Amount of load we'd subtract */
  2095. tmp = busiest_load_per_task*SCHED_LOAD_SCALE/busiest->cpu_power;
  2096. if (max_load > tmp)
  2097. pwr_move += busiest->cpu_power *
  2098. min(busiest_load_per_task, max_load - tmp);
  2099. /* Amount of load we'd add */
  2100. if (max_load*busiest->cpu_power <
  2101. busiest_load_per_task*SCHED_LOAD_SCALE)
  2102. tmp = max_load*busiest->cpu_power/this->cpu_power;
  2103. else
  2104. tmp = busiest_load_per_task*SCHED_LOAD_SCALE/this->cpu_power;
  2105. pwr_move += this->cpu_power*min(this_load_per_task, this_load + tmp);
  2106. pwr_move /= SCHED_LOAD_SCALE;
  2107. /* Move if we gain throughput */
  2108. if (pwr_move <= pwr_now)
  2109. goto out_balanced;
  2110. *imbalance = busiest_load_per_task;
  2111. }
  2112. return busiest;
  2113. out_balanced:
  2114. #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
  2115. if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
  2116. goto ret;
  2117. if (this == group_leader && group_leader != group_min) {
  2118. *imbalance = min_load_per_task;
  2119. return group_min;
  2120. }
  2121. ret:
  2122. #endif
  2123. *imbalance = 0;
  2124. return NULL;
  2125. }
  2126. /*
  2127. * find_busiest_queue - find the busiest runqueue among the cpus in group.
  2128. */
  2129. static struct rq *
  2130. find_busiest_queue(struct sched_group *group, enum idle_type idle,
  2131. unsigned long imbalance)
  2132. {
  2133. struct rq *busiest = NULL, *rq;
  2134. unsigned long max_load = 0;
  2135. int i;
  2136. for_each_cpu_mask(i, group->cpumask) {
  2137. rq = cpu_rq(i);
  2138. if (rq->nr_running == 1 && rq->raw_weighted_load > imbalance)
  2139. continue;
  2140. if (rq->raw_weighted_load > max_load) {
  2141. max_load = rq->raw_weighted_load;
  2142. busiest = rq;
  2143. }
  2144. }
  2145. return busiest;
  2146. }
  2147. /*
  2148. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  2149. * so long as it is large enough.
  2150. */
  2151. #define MAX_PINNED_INTERVAL 512
  2152. static inline unsigned long minus_1_or_zero(unsigned long n)
  2153. {
  2154. return n > 0 ? n - 1 : 0;
  2155. }
  2156. /*
  2157. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  2158. * tasks if there is an imbalance.
  2159. *
  2160. * Called with this_rq unlocked.
  2161. */
  2162. static int load_balance(int this_cpu, struct rq *this_rq,
  2163. struct sched_domain *sd, enum idle_type idle)
  2164. {
  2165. int nr_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
  2166. struct sched_group *group;
  2167. unsigned long imbalance;
  2168. struct rq *busiest;
  2169. if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
  2170. !sched_smt_power_savings)
  2171. sd_idle = 1;
  2172. schedstat_inc(sd, lb_cnt[idle]);
  2173. group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
  2174. if (!group) {
  2175. schedstat_inc(sd, lb_nobusyg[idle]);
  2176. goto out_balanced;
  2177. }
  2178. busiest = find_busiest_queue(group, idle, imbalance);
  2179. if (!busiest) {
  2180. schedstat_inc(sd, lb_nobusyq[idle]);
  2181. goto out_balanced;
  2182. }
  2183. BUG_ON(busiest == this_rq);
  2184. schedstat_add(sd, lb_imbalance[idle], imbalance);
  2185. nr_moved = 0;
  2186. if (busiest->nr_running > 1) {
  2187. /*
  2188. * Attempt to move tasks. If find_busiest_group has found
  2189. * an imbalance but busiest->nr_running <= 1, the group is
  2190. * still unbalanced. nr_moved simply stays zero, so it is
  2191. * correctly treated as an imbalance.
  2192. */
  2193. double_rq_lock(this_rq, busiest);
  2194. nr_moved = move_tasks(this_rq, this_cpu, busiest,
  2195. minus_1_or_zero(busiest->nr_running),
  2196. imbalance, sd, idle, &all_pinned);
  2197. double_rq_unlock(this_rq, busiest);
  2198. /* All tasks on this runqueue were pinned by CPU affinity */
  2199. if (unlikely(all_pinned))
  2200. goto out_balanced;
  2201. }
  2202. if (!nr_moved) {
  2203. schedstat_inc(sd, lb_failed[idle]);
  2204. sd->nr_balance_failed++;
  2205. if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
  2206. spin_lock(&busiest->lock);
  2207. /* don't kick the migration_thread, if the curr
  2208. * task on busiest cpu can't be moved to this_cpu
  2209. */
  2210. if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
  2211. spin_unlock(&busiest->lock);
  2212. all_pinned = 1;
  2213. goto out_one_pinned;
  2214. }
  2215. if (!busiest->active_balance) {
  2216. busiest->active_balance = 1;
  2217. busiest->push_cpu = this_cpu;
  2218. active_balance = 1;
  2219. }
  2220. spin_unlock(&busiest->lock);
  2221. if (active_balance)
  2222. wake_up_process(busiest->migration_thread);
  2223. /*
  2224. * We've kicked active balancing, reset the failure
  2225. * counter.
  2226. */
  2227. sd->nr_balance_failed = sd->cache_nice_tries+1;
  2228. }
  2229. } else
  2230. sd->nr_balance_failed = 0;
  2231. if (likely(!active_balance)) {
  2232. /* We were unbalanced, so reset the balancing interval */
  2233. sd->balance_interval = sd->min_interval;
  2234. } else {
  2235. /*
  2236. * If we've begun active balancing, start to back off. This
  2237. * case may not be covered by the all_pinned logic if there
  2238. * is only 1 task on the busy runqueue (because we don't call
  2239. * move_tasks).
  2240. */
  2241. if (sd->balance_interval < sd->max_interval)
  2242. sd->balance_interval *= 2;
  2243. }
  2244. if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
  2245. !sched_smt_power_savings)
  2246. return -1;
  2247. return nr_moved;
  2248. out_balanced:
  2249. schedstat_inc(sd, lb_balanced[idle]);
  2250. sd->nr_balance_failed = 0;
  2251. out_one_pinned:
  2252. /* tune up the balancing interval */
  2253. if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
  2254. (sd->balance_interval < sd->max_interval))
  2255. sd->balance_interval *= 2;
  2256. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
  2257. !sched_smt_power_savings)
  2258. return -1;
  2259. return 0;
  2260. }
  2261. /*
  2262. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  2263. * tasks if there is an imbalance.
  2264. *
  2265. * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
  2266. * this_rq is locked.
  2267. */
  2268. static int
  2269. load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
  2270. {
  2271. struct sched_group *group;
  2272. struct rq *busiest = NULL;
  2273. unsigned long imbalance;
  2274. int nr_moved = 0;
  2275. int sd_idle = 0;
  2276. if (sd->flags & SD_SHARE_CPUPOWER && !sched_smt_power_savings)
  2277. sd_idle = 1;
  2278. schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
  2279. group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
  2280. if (!group) {
  2281. schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
  2282. goto out_balanced;
  2283. }
  2284. busiest = find_busiest_queue(group, NEWLY_IDLE, imbalance);
  2285. if (!busiest) {
  2286. schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
  2287. goto out_balanced;
  2288. }
  2289. BUG_ON(busiest == this_rq);
  2290. schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
  2291. nr_moved = 0;
  2292. if (busiest->nr_running > 1) {
  2293. /* Attempt to move tasks */
  2294. double_lock_balance(this_rq, busiest);
  2295. nr_moved = move_tasks(this_rq, this_cpu, busiest,
  2296. minus_1_or_zero(busiest->nr_running),
  2297. imbalance, sd, NEWLY_IDLE, NULL);
  2298. spin_unlock(&busiest->lock);
  2299. }
  2300. if (!nr_moved) {
  2301. schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
  2302. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
  2303. return -1;
  2304. } else
  2305. sd->nr_balance_failed = 0;
  2306. return nr_moved;
  2307. out_balanced:
  2308. schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
  2309. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
  2310. !sched_smt_power_savings)
  2311. return -1;
  2312. sd->nr_balance_failed = 0;
  2313. return 0;
  2314. }
  2315. /*
  2316. * idle_balance is called by schedule() if this_cpu is about to become
  2317. * idle. Attempts to pull tasks from other CPUs.
  2318. */
  2319. static void idle_balance(int this_cpu, struct rq *this_rq)
  2320. {
  2321. struct sched_domain *sd;
  2322. for_each_domain(this_cpu, sd) {
  2323. if (sd->flags & SD_BALANCE_NEWIDLE) {
  2324. /* If we've pulled tasks over stop searching: */
  2325. if (load_balance_newidle(this_cpu, this_rq, sd))
  2326. break;
  2327. }
  2328. }
  2329. }
  2330. /*
  2331. * active_load_balance is run by migration threads. It pushes running tasks
  2332. * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
  2333. * running on each physical CPU where possible, and avoids physical /
  2334. * logical imbalances.
  2335. *
  2336. * Called with busiest_rq locked.
  2337. */
  2338. static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
  2339. {
  2340. int target_cpu = busiest_rq->push_cpu;
  2341. struct sched_domain *sd;
  2342. struct rq *target_rq;
  2343. /* Is there any task to move? */
  2344. if (busiest_rq->nr_running <= 1)
  2345. return;
  2346. target_rq = cpu_rq(target_cpu);
  2347. /*
  2348. * This condition is "impossible", if it occurs
  2349. * we need to fix it. Originally reported by
  2350. * Bjorn Helgaas on a 128-cpu setup.
  2351. */
  2352. BUG_ON(busiest_rq == target_rq);
  2353. /* move a task from busiest_rq to target_rq */
  2354. double_lock_balance(busiest_rq, target_rq);
  2355. /* Search for an sd spanning us and the target CPU. */
  2356. for_each_domain(target_cpu, sd) {
  2357. if ((sd->flags & SD_LOAD_BALANCE) &&
  2358. cpu_isset(busiest_cpu, sd->span))
  2359. break;
  2360. }
  2361. if (likely(sd)) {
  2362. schedstat_inc(sd, alb_cnt);
  2363. if (move_tasks(target_rq, target_cpu, busiest_rq, 1,
  2364. RTPRIO_TO_LOAD_WEIGHT(100), sd, SCHED_IDLE,
  2365. NULL))
  2366. schedstat_inc(sd, alb_pushed);
  2367. else
  2368. schedstat_inc(sd, alb_failed);
  2369. }
  2370. spin_unlock(&target_rq->lock);
  2371. }
  2372. /*
  2373. * rebalance_tick will get called every timer tick, on every CPU.
  2374. *
  2375. * It checks each scheduling domain to see if it is due to be balanced,
  2376. * and initiates a balancing operation if so.
  2377. *
  2378. * Balancing parameters are set up in arch_init_sched_domains.
  2379. */
  2380. /* Don't have all balancing operations going off at once: */
  2381. static inline unsigned long cpu_offset(int cpu)
  2382. {
  2383. return jiffies + cpu * HZ / NR_CPUS;
  2384. }
  2385. static void
  2386. rebalance_tick(int this_cpu, struct rq *this_rq, enum idle_type idle)
  2387. {
  2388. unsigned long this_load, interval, j = cpu_offset(this_cpu);
  2389. struct sched_domain *sd;
  2390. int i, scale;
  2391. this_load = this_rq->raw_weighted_load;
  2392. /* Update our load: */
  2393. for (i = 0, scale = 1; i < 3; i++, scale <<= 1) {
  2394. unsigned long old_load, new_load;
  2395. old_load = this_rq->cpu_load[i];
  2396. new_load = this_load;
  2397. /*
  2398. * Round up the averaging division if load is increasing. This
  2399. * prevents us from getting stuck on 9 if the load is 10, for
  2400. * example.
  2401. */
  2402. if (new_load > old_load)
  2403. new_load += scale-1;
  2404. this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
  2405. }
  2406. for_each_domain(this_cpu, sd) {
  2407. if (!(sd->flags & SD_LOAD_BALANCE))
  2408. continue;
  2409. interval = sd->balance_interval;
  2410. if (idle != SCHED_IDLE)
  2411. interval *= sd->busy_factor;
  2412. /* scale ms to jiffies */
  2413. interval = msecs_to_jiffies(interval);
  2414. if (unlikely(!interval))
  2415. interval = 1;
  2416. if (j - sd->last_balance >= interval) {
  2417. if (load_balance(this_cpu, this_rq, sd, idle)) {
  2418. /*
  2419. * We've pulled tasks over so either we're no
  2420. * longer idle, or one of our SMT siblings is
  2421. * not idle.
  2422. */
  2423. idle = NOT_IDLE;
  2424. }
  2425. sd->last_balance += interval;
  2426. }
  2427. }
  2428. }
  2429. #else
  2430. /*
  2431. * on UP we do not need to balance between CPUs:
  2432. */
  2433. static inline void rebalance_tick(int cpu, struct rq *rq, enum idle_type idle)
  2434. {
  2435. }
  2436. static inline void idle_balance(int cpu, struct rq *rq)
  2437. {
  2438. }
  2439. #endif
  2440. static inline int wake_priority_sleeper(struct rq *rq)
  2441. {
  2442. int ret = 0;
  2443. #ifdef CONFIG_SCHED_SMT
  2444. spin_lock(&rq->lock);
  2445. /*
  2446. * If an SMT sibling task has been put to sleep for priority
  2447. * reasons reschedule the idle task to see if it can now run.
  2448. */
  2449. if (rq->nr_running) {
  2450. resched_task(rq->idle);
  2451. ret = 1;
  2452. }
  2453. spin_unlock(&rq->lock);
  2454. #endif
  2455. return ret;
  2456. }
  2457. DEFINE_PER_CPU(struct kernel_stat, kstat);
  2458. EXPORT_PER_CPU_SYMBOL(kstat);
  2459. /*
  2460. * This is called on clock ticks and on context switches.
  2461. * Bank in p->sched_time the ns elapsed since the last tick or switch.
  2462. */
  2463. static inline void
  2464. update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now)
  2465. {
  2466. p->sched_time += now - max(p->timestamp, rq->timestamp_last_tick);
  2467. }
  2468. /*
  2469. * Return current->sched_time plus any more ns on the sched_clock
  2470. * that have not yet been banked.
  2471. */
  2472. unsigned long long current_sched_time(const struct task_struct *p)
  2473. {
  2474. unsigned long long ns;
  2475. unsigned long flags;
  2476. local_irq_save(flags);
  2477. ns = max(p->timestamp, task_rq(p)->timestamp_last_tick);
  2478. ns = p->sched_time + sched_clock() - ns;
  2479. local_irq_restore(flags);
  2480. return ns;
  2481. }
  2482. /*
  2483. * We place interactive tasks back into the active array, if possible.
  2484. *
  2485. * To guarantee that this does not starve expired tasks we ignore the
  2486. * interactivity of a task if the first expired task had to wait more
  2487. * than a 'reasonable' amount of time. This deadline timeout is
  2488. * load-dependent, as the frequency of array switched decreases with
  2489. * increasing number of running tasks. We also ignore the interactivity
  2490. * if a better static_prio task has expired:
  2491. */
  2492. static inline int expired_starving(struct rq *rq)
  2493. {
  2494. if (rq->curr->static_prio > rq->best_expired_prio)
  2495. return 1;
  2496. if (!STARVATION_LIMIT || !rq->expired_timestamp)
  2497. return 0;
  2498. if (jiffies - rq->expired_timestamp > STARVATION_LIMIT * rq->nr_running)
  2499. return 1;
  2500. return 0;
  2501. }
  2502. /*
  2503. * Account user cpu time to a process.
  2504. * @p: the process that the cpu time gets accounted to
  2505. * @hardirq_offset: the offset to subtract from hardirq_count()
  2506. * @cputime: the cpu time spent in user space since the last update
  2507. */
  2508. void account_user_time(struct task_struct *p, cputime_t cputime)
  2509. {
  2510. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2511. cputime64_t tmp;
  2512. p->utime = cputime_add(p->utime, cputime);
  2513. /* Add user time to cpustat. */
  2514. tmp = cputime_to_cputime64(cputime);
  2515. if (TASK_NICE(p) > 0)
  2516. cpustat->nice = cputime64_add(cpustat->nice, tmp);
  2517. else
  2518. cpustat->user = cputime64_add(cpustat->user, tmp);
  2519. }
  2520. /*
  2521. * Account system cpu time to a process.
  2522. * @p: the process that the cpu time gets accounted to
  2523. * @hardirq_offset: the offset to subtract from hardirq_count()
  2524. * @cputime: the cpu time spent in kernel space since the last update
  2525. */
  2526. void account_system_time(struct task_struct *p, int hardirq_offset,
  2527. cputime_t cputime)
  2528. {
  2529. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2530. struct rq *rq = this_rq();
  2531. cputime64_t tmp;
  2532. p->stime = cputime_add(p->stime, cputime);
  2533. /* Add system time to cpustat. */
  2534. tmp = cputime_to_cputime64(cputime);
  2535. if (hardirq_count() - hardirq_offset)
  2536. cpustat->irq = cputime64_add(cpustat->irq, tmp);
  2537. else if (softirq_count())
  2538. cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
  2539. else if (p != rq->idle)
  2540. cpustat->system = cputime64_add(cpustat->system, tmp);
  2541. else if (atomic_read(&rq->nr_iowait) > 0)
  2542. cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
  2543. else
  2544. cpustat->idle = cputime64_add(cpustat->idle, tmp);
  2545. /* Account for system time used */
  2546. acct_update_integrals(p);
  2547. }
  2548. /*
  2549. * Account for involuntary wait time.
  2550. * @p: the process from which the cpu time has been stolen
  2551. * @steal: the cpu time spent in involuntary wait
  2552. */
  2553. void account_steal_time(struct task_struct *p, cputime_t steal)
  2554. {
  2555. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2556. cputime64_t tmp = cputime_to_cputime64(steal);
  2557. struct rq *rq = this_rq();
  2558. if (p == rq->idle) {
  2559. p->stime = cputime_add(p->stime, steal);
  2560. if (atomic_read(&rq->nr_iowait) > 0)
  2561. cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
  2562. else
  2563. cpustat->idle = cputime64_add(cpustat->idle, tmp);
  2564. } else
  2565. cpustat->steal = cputime64_add(cpustat->steal, tmp);
  2566. }
  2567. /*
  2568. * This function gets called by the timer code, with HZ frequency.
  2569. * We call it with interrupts disabled.
  2570. *
  2571. * It also gets called by the fork code, when changing the parent's
  2572. * timeslices.
  2573. */
  2574. void scheduler_tick(void)
  2575. {
  2576. unsigned long long now = sched_clock();
  2577. struct task_struct *p = current;
  2578. int cpu = smp_processor_id();
  2579. struct rq *rq = cpu_rq(cpu);
  2580. update_cpu_clock(p, rq, now);
  2581. rq->timestamp_last_tick = now;
  2582. if (p == rq->idle) {
  2583. if (wake_priority_sleeper(rq))
  2584. goto out;
  2585. rebalance_tick(cpu, rq, SCHED_IDLE);
  2586. return;
  2587. }
  2588. /* Task might have expired already, but not scheduled off yet */
  2589. if (p->array != rq->active) {
  2590. set_tsk_need_resched(p);
  2591. goto out;
  2592. }
  2593. spin_lock(&rq->lock);
  2594. /*
  2595. * The task was running during this tick - update the
  2596. * time slice counter. Note: we do not update a thread's
  2597. * priority until it either goes to sleep or uses up its
  2598. * timeslice. This makes it possible for interactive tasks
  2599. * to use up their timeslices at their highest priority levels.
  2600. */
  2601. if (rt_task(p)) {
  2602. /*
  2603. * RR tasks need a special form of timeslice management.
  2604. * FIFO tasks have no timeslices.
  2605. */
  2606. if ((p->policy == SCHED_RR) && !--p->time_slice) {
  2607. p->time_slice = task_timeslice(p);
  2608. p->first_time_slice = 0;
  2609. set_tsk_need_resched(p);
  2610. /* put it at the end of the queue: */
  2611. requeue_task(p, rq->active);
  2612. }
  2613. goto out_unlock;
  2614. }
  2615. if (!--p->time_slice) {
  2616. dequeue_task(p, rq->active);
  2617. set_tsk_need_resched(p);
  2618. p->prio = effective_prio(p);
  2619. p->time_slice = task_timeslice(p);
  2620. p->first_time_slice = 0;
  2621. if (!rq->expired_timestamp)
  2622. rq->expired_timestamp = jiffies;
  2623. if (!TASK_INTERACTIVE(p) || expired_starving(rq)) {
  2624. enqueue_task(p, rq->expired);
  2625. if (p->static_prio < rq->best_expired_prio)
  2626. rq->best_expired_prio = p->static_prio;
  2627. } else
  2628. enqueue_task(p, rq->active);
  2629. } else {
  2630. /*
  2631. * Prevent a too long timeslice allowing a task to monopolize
  2632. * the CPU. We do this by splitting up the timeslice into
  2633. * smaller pieces.
  2634. *
  2635. * Note: this does not mean the task's timeslices expire or
  2636. * get lost in any way, they just might be preempted by
  2637. * another task of equal priority. (one with higher
  2638. * priority would have preempted this task already.) We
  2639. * requeue this task to the end of the list on this priority
  2640. * level, which is in essence a round-robin of tasks with
  2641. * equal priority.
  2642. *
  2643. * This only applies to tasks in the interactive
  2644. * delta range with at least TIMESLICE_GRANULARITY to requeue.
  2645. */
  2646. if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
  2647. p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
  2648. (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
  2649. (p->array == rq->active)) {
  2650. requeue_task(p, rq->active);
  2651. set_tsk_need_resched(p);
  2652. }
  2653. }
  2654. out_unlock:
  2655. spin_unlock(&rq->lock);
  2656. out:
  2657. rebalance_tick(cpu, rq, NOT_IDLE);
  2658. }
  2659. #ifdef CONFIG_SCHED_SMT
  2660. static inline void wakeup_busy_runqueue(struct rq *rq)
  2661. {
  2662. /* If an SMT runqueue is sleeping due to priority reasons wake it up */
  2663. if (rq->curr == rq->idle && rq->nr_running)
  2664. resched_task(rq->idle);
  2665. }
  2666. /*
  2667. * Called with interrupt disabled and this_rq's runqueue locked.
  2668. */
  2669. static void wake_sleeping_dependent(int this_cpu)
  2670. {
  2671. struct sched_domain *tmp, *sd = NULL;
  2672. int i;
  2673. for_each_domain(this_cpu, tmp) {
  2674. if (tmp->flags & SD_SHARE_CPUPOWER) {
  2675. sd = tmp;
  2676. break;
  2677. }
  2678. }
  2679. if (!sd)
  2680. return;
  2681. for_each_cpu_mask(i, sd->span) {
  2682. struct rq *smt_rq = cpu_rq(i);
  2683. if (i == this_cpu)
  2684. continue;
  2685. if (unlikely(!spin_trylock(&smt_rq->lock)))
  2686. continue;
  2687. wakeup_busy_runqueue(smt_rq);
  2688. spin_unlock(&smt_rq->lock);
  2689. }
  2690. }
  2691. /*
  2692. * number of 'lost' timeslices this task wont be able to fully
  2693. * utilize, if another task runs on a sibling. This models the
  2694. * slowdown effect of other tasks running on siblings:
  2695. */
  2696. static inline unsigned long
  2697. smt_slice(struct task_struct *p, struct sched_domain *sd)
  2698. {
  2699. return p->time_slice * (100 - sd->per_cpu_gain) / 100;
  2700. }
  2701. /*
  2702. * To minimise lock contention and not have to drop this_rq's runlock we only
  2703. * trylock the sibling runqueues and bypass those runqueues if we fail to
  2704. * acquire their lock. As we only trylock the normal locking order does not
  2705. * need to be obeyed.
  2706. */
  2707. static int
  2708. dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
  2709. {
  2710. struct sched_domain *tmp, *sd = NULL;
  2711. int ret = 0, i;
  2712. /* kernel/rt threads do not participate in dependent sleeping */
  2713. if (!p->mm || rt_task(p))
  2714. return 0;
  2715. for_each_domain(this_cpu, tmp) {
  2716. if (tmp->flags & SD_SHARE_CPUPOWER) {
  2717. sd = tmp;
  2718. break;
  2719. }
  2720. }
  2721. if (!sd)
  2722. return 0;
  2723. for_each_cpu_mask(i, sd->span) {
  2724. struct task_struct *smt_curr;
  2725. struct rq *smt_rq;
  2726. if (i == this_cpu)
  2727. continue;
  2728. smt_rq = cpu_rq(i);
  2729. if (unlikely(!spin_trylock(&smt_rq->lock)))
  2730. continue;
  2731. smt_curr = smt_rq->curr;
  2732. if (!smt_curr->mm)
  2733. goto unlock;
  2734. /*
  2735. * If a user task with lower static priority than the
  2736. * running task on the SMT sibling is trying to schedule,
  2737. * delay it till there is proportionately less timeslice
  2738. * left of the sibling task to prevent a lower priority
  2739. * task from using an unfair proportion of the
  2740. * physical cpu's resources. -ck
  2741. */
  2742. if (rt_task(smt_curr)) {
  2743. /*
  2744. * With real time tasks we run non-rt tasks only
  2745. * per_cpu_gain% of the time.
  2746. */
  2747. if ((jiffies % DEF_TIMESLICE) >
  2748. (sd->per_cpu_gain * DEF_TIMESLICE / 100))
  2749. ret = 1;
  2750. } else {
  2751. if (smt_curr->static_prio < p->static_prio &&
  2752. !TASK_PREEMPTS_CURR(p, smt_rq) &&
  2753. smt_slice(smt_curr, sd) > task_timeslice(p))
  2754. ret = 1;
  2755. }
  2756. unlock:
  2757. spin_unlock(&smt_rq->lock);
  2758. }
  2759. return ret;
  2760. }
  2761. #else
  2762. static inline void wake_sleeping_dependent(int this_cpu)
  2763. {
  2764. }
  2765. static inline int
  2766. dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
  2767. {
  2768. return 0;
  2769. }
  2770. #endif
  2771. #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
  2772. void fastcall add_preempt_count(int val)
  2773. {
  2774. /*
  2775. * Underflow?
  2776. */
  2777. if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
  2778. return;
  2779. preempt_count() += val;
  2780. /*
  2781. * Spinlock count overflowing soon?
  2782. */
  2783. DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
  2784. }
  2785. EXPORT_SYMBOL(add_preempt_count);
  2786. void fastcall sub_preempt_count(int val)
  2787. {
  2788. /*
  2789. * Underflow?
  2790. */
  2791. if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
  2792. return;
  2793. /*
  2794. * Is the spinlock portion underflowing?
  2795. */
  2796. if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
  2797. !(preempt_count() & PREEMPT_MASK)))
  2798. return;
  2799. preempt_count() -= val;
  2800. }
  2801. EXPORT_SYMBOL(sub_preempt_count);
  2802. #endif
  2803. static inline int interactive_sleep(enum sleep_type sleep_type)
  2804. {
  2805. return (sleep_type == SLEEP_INTERACTIVE ||
  2806. sleep_type == SLEEP_INTERRUPTED);
  2807. }
  2808. /*
  2809. * schedule() is the main scheduler function.
  2810. */
  2811. asmlinkage void __sched schedule(void)
  2812. {
  2813. struct task_struct *prev, *next;
  2814. struct prio_array *array;
  2815. struct list_head *queue;
  2816. unsigned long long now;
  2817. unsigned long run_time;
  2818. int cpu, idx, new_prio;
  2819. long *switch_count;
  2820. struct rq *rq;
  2821. /*
  2822. * Test if we are atomic. Since do_exit() needs to call into
  2823. * schedule() atomically, we ignore that path for now.
  2824. * Otherwise, whine if we are scheduling when we should not be.
  2825. */
  2826. if (unlikely(in_atomic() && !current->exit_state)) {
  2827. printk(KERN_ERR "BUG: scheduling while atomic: "
  2828. "%s/0x%08x/%d\n",
  2829. current->comm, preempt_count(), current->pid);
  2830. dump_stack();
  2831. }
  2832. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  2833. need_resched:
  2834. preempt_disable();
  2835. prev = current;
  2836. release_kernel_lock(prev);
  2837. need_resched_nonpreemptible:
  2838. rq = this_rq();
  2839. /*
  2840. * The idle thread is not allowed to schedule!
  2841. * Remove this check after it has been exercised a bit.
  2842. */
  2843. if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
  2844. printk(KERN_ERR "bad: scheduling from the idle thread!\n");
  2845. dump_stack();
  2846. }
  2847. schedstat_inc(rq, sched_cnt);
  2848. now = sched_clock();
  2849. if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
  2850. run_time = now - prev->timestamp;
  2851. if (unlikely((long long)(now - prev->timestamp) < 0))
  2852. run_time = 0;
  2853. } else
  2854. run_time = NS_MAX_SLEEP_AVG;
  2855. /*
  2856. * Tasks charged proportionately less run_time at high sleep_avg to
  2857. * delay them losing their interactive status
  2858. */
  2859. run_time /= (CURRENT_BONUS(prev) ? : 1);
  2860. spin_lock_irq(&rq->lock);
  2861. if (unlikely(prev->flags & PF_DEAD))
  2862. prev->state = EXIT_DEAD;
  2863. switch_count = &prev->nivcsw;
  2864. if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
  2865. switch_count = &prev->nvcsw;
  2866. if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
  2867. unlikely(signal_pending(prev))))
  2868. prev->state = TASK_RUNNING;
  2869. else {
  2870. if (prev->state == TASK_UNINTERRUPTIBLE)
  2871. rq->nr_uninterruptible++;
  2872. deactivate_task(prev, rq);
  2873. }
  2874. }
  2875. cpu = smp_processor_id();
  2876. if (unlikely(!rq->nr_running)) {
  2877. idle_balance(cpu, rq);
  2878. if (!rq->nr_running) {
  2879. next = rq->idle;
  2880. rq->expired_timestamp = 0;
  2881. wake_sleeping_dependent(cpu);
  2882. goto switch_tasks;
  2883. }
  2884. }
  2885. array = rq->active;
  2886. if (unlikely(!array->nr_active)) {
  2887. /*
  2888. * Switch the active and expired arrays.
  2889. */
  2890. schedstat_inc(rq, sched_switch);
  2891. rq->active = rq->expired;
  2892. rq->expired = array;
  2893. array = rq->active;
  2894. rq->expired_timestamp = 0;
  2895. rq->best_expired_prio = MAX_PRIO;
  2896. }
  2897. idx = sched_find_first_bit(array->bitmap);
  2898. queue = array->queue + idx;
  2899. next = list_entry(queue->next, struct task_struct, run_list);
  2900. if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
  2901. unsigned long long delta = now - next->timestamp;
  2902. if (unlikely((long long)(now - next->timestamp) < 0))
  2903. delta = 0;
  2904. if (next->sleep_type == SLEEP_INTERACTIVE)
  2905. delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
  2906. array = next->array;
  2907. new_prio = recalc_task_prio(next, next->timestamp + delta);
  2908. if (unlikely(next->prio != new_prio)) {
  2909. dequeue_task(next, array);
  2910. next->prio = new_prio;
  2911. enqueue_task(next, array);
  2912. }
  2913. }
  2914. next->sleep_type = SLEEP_NORMAL;
  2915. if (dependent_sleeper(cpu, rq, next))
  2916. next = rq->idle;
  2917. switch_tasks:
  2918. if (next == rq->idle)
  2919. schedstat_inc(rq, sched_goidle);
  2920. prefetch(next);
  2921. prefetch_stack(next);
  2922. clear_tsk_need_resched(prev);
  2923. rcu_qsctr_inc(task_cpu(prev));
  2924. update_cpu_clock(prev, rq, now);
  2925. prev->sleep_avg -= run_time;
  2926. if ((long)prev->sleep_avg <= 0)
  2927. prev->sleep_avg = 0;
  2928. prev->timestamp = prev->last_ran = now;
  2929. sched_info_switch(prev, next);
  2930. if (likely(prev != next)) {
  2931. next->timestamp = now;
  2932. rq->nr_switches++;
  2933. rq->curr = next;
  2934. ++*switch_count;
  2935. prepare_task_switch(rq, next);
  2936. prev = context_switch(rq, prev, next);
  2937. barrier();
  2938. /*
  2939. * this_rq must be evaluated again because prev may have moved
  2940. * CPUs since it called schedule(), thus the 'rq' on its stack
  2941. * frame will be invalid.
  2942. */
  2943. finish_task_switch(this_rq(), prev);
  2944. } else
  2945. spin_unlock_irq(&rq->lock);
  2946. prev = current;
  2947. if (unlikely(reacquire_kernel_lock(prev) < 0))
  2948. goto need_resched_nonpreemptible;
  2949. preempt_enable_no_resched();
  2950. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2951. goto need_resched;
  2952. }
  2953. EXPORT_SYMBOL(schedule);
  2954. #ifdef CONFIG_PREEMPT
  2955. /*
  2956. * this is is the entry point to schedule() from in-kernel preemption
  2957. * off of preempt_enable. Kernel preemptions off return from interrupt
  2958. * occur there and call schedule directly.
  2959. */
  2960. asmlinkage void __sched preempt_schedule(void)
  2961. {
  2962. struct thread_info *ti = current_thread_info();
  2963. #ifdef CONFIG_PREEMPT_BKL
  2964. struct task_struct *task = current;
  2965. int saved_lock_depth;
  2966. #endif
  2967. /*
  2968. * If there is a non-zero preempt_count or interrupts are disabled,
  2969. * we do not want to preempt the current task. Just return..
  2970. */
  2971. if (unlikely(ti->preempt_count || irqs_disabled()))
  2972. return;
  2973. need_resched:
  2974. add_preempt_count(PREEMPT_ACTIVE);
  2975. /*
  2976. * We keep the big kernel semaphore locked, but we
  2977. * clear ->lock_depth so that schedule() doesnt
  2978. * auto-release the semaphore:
  2979. */
  2980. #ifdef CONFIG_PREEMPT_BKL
  2981. saved_lock_depth = task->lock_depth;
  2982. task->lock_depth = -1;
  2983. #endif
  2984. schedule();
  2985. #ifdef CONFIG_PREEMPT_BKL
  2986. task->lock_depth = saved_lock_depth;
  2987. #endif
  2988. sub_preempt_count(PREEMPT_ACTIVE);
  2989. /* we could miss a preemption opportunity between schedule and now */
  2990. barrier();
  2991. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2992. goto need_resched;
  2993. }
  2994. EXPORT_SYMBOL(preempt_schedule);
  2995. /*
  2996. * this is is the entry point to schedule() from kernel preemption
  2997. * off of irq context.
  2998. * Note, that this is called and return with irqs disabled. This will
  2999. * protect us against recursive calling from irq.
  3000. */
  3001. asmlinkage void __sched preempt_schedule_irq(void)
  3002. {
  3003. struct thread_info *ti = current_thread_info();
  3004. #ifdef CONFIG_PREEMPT_BKL
  3005. struct task_struct *task = current;
  3006. int saved_lock_depth;
  3007. #endif
  3008. /* Catch callers which need to be fixed*/
  3009. BUG_ON(ti->preempt_count || !irqs_disabled());
  3010. need_resched:
  3011. add_preempt_count(PREEMPT_ACTIVE);
  3012. /*
  3013. * We keep the big kernel semaphore locked, but we
  3014. * clear ->lock_depth so that schedule() doesnt
  3015. * auto-release the semaphore:
  3016. */
  3017. #ifdef CONFIG_PREEMPT_BKL
  3018. saved_lock_depth = task->lock_depth;
  3019. task->lock_depth = -1;
  3020. #endif
  3021. local_irq_enable();
  3022. schedule();
  3023. local_irq_disable();
  3024. #ifdef CONFIG_PREEMPT_BKL
  3025. task->lock_depth = saved_lock_depth;
  3026. #endif
  3027. sub_preempt_count(PREEMPT_ACTIVE);
  3028. /* we could miss a preemption opportunity between schedule and now */
  3029. barrier();
  3030. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  3031. goto need_resched;
  3032. }
  3033. #endif /* CONFIG_PREEMPT */
  3034. int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
  3035. void *key)
  3036. {
  3037. return try_to_wake_up(curr->private, mode, sync);
  3038. }
  3039. EXPORT_SYMBOL(default_wake_function);
  3040. /*
  3041. * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
  3042. * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
  3043. * number) then we wake all the non-exclusive tasks and one exclusive task.
  3044. *
  3045. * There are circumstances in which we can try to wake a task which has already
  3046. * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
  3047. * zero in this (rare) case, and we handle it by continuing to scan the queue.
  3048. */
  3049. static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
  3050. int nr_exclusive, int sync, void *key)
  3051. {
  3052. struct list_head *tmp, *next;
  3053. list_for_each_safe(tmp, next, &q->task_list) {
  3054. wait_queue_t *curr = list_entry(tmp, wait_queue_t, task_list);
  3055. unsigned flags = curr->flags;
  3056. if (curr->func(curr, mode, sync, key) &&
  3057. (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
  3058. break;
  3059. }
  3060. }
  3061. /**
  3062. * __wake_up - wake up threads blocked on a waitqueue.
  3063. * @q: the waitqueue
  3064. * @mode: which threads
  3065. * @nr_exclusive: how many wake-one or wake-many threads to wake up
  3066. * @key: is directly passed to the wakeup function
  3067. */
  3068. void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
  3069. int nr_exclusive, void *key)
  3070. {
  3071. unsigned long flags;
  3072. spin_lock_irqsave(&q->lock, flags);
  3073. __wake_up_common(q, mode, nr_exclusive, 0, key);
  3074. spin_unlock_irqrestore(&q->lock, flags);
  3075. }
  3076. EXPORT_SYMBOL(__wake_up);
  3077. /*
  3078. * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
  3079. */
  3080. void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
  3081. {
  3082. __wake_up_common(q, mode, 1, 0, NULL);
  3083. }
  3084. /**
  3085. * __wake_up_sync - wake up threads blocked on a waitqueue.
  3086. * @q: the waitqueue
  3087. * @mode: which threads
  3088. * @nr_exclusive: how many wake-one or wake-many threads to wake up
  3089. *
  3090. * The sync wakeup differs that the waker knows that it will schedule
  3091. * away soon, so while the target thread will be woken up, it will not
  3092. * be migrated to another CPU - ie. the two threads are 'synchronized'
  3093. * with each other. This can prevent needless bouncing between CPUs.
  3094. *
  3095. * On UP it can prevent extra preemption.
  3096. */
  3097. void fastcall
  3098. __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
  3099. {
  3100. unsigned long flags;
  3101. int sync = 1;
  3102. if (unlikely(!q))
  3103. return;
  3104. if (unlikely(!nr_exclusive))
  3105. sync = 0;
  3106. spin_lock_irqsave(&q->lock, flags);
  3107. __wake_up_common(q, mode, nr_exclusive, sync, NULL);
  3108. spin_unlock_irqrestore(&q->lock, flags);
  3109. }
  3110. EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
  3111. void fastcall complete(struct completion *x)
  3112. {
  3113. unsigned long flags;
  3114. spin_lock_irqsave(&x->wait.lock, flags);
  3115. x->done++;
  3116. __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
  3117. 1, 0, NULL);
  3118. spin_unlock_irqrestore(&x->wait.lock, flags);
  3119. }
  3120. EXPORT_SYMBOL(complete);
  3121. void fastcall complete_all(struct completion *x)
  3122. {
  3123. unsigned long flags;
  3124. spin_lock_irqsave(&x->wait.lock, flags);
  3125. x->done += UINT_MAX/2;
  3126. __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
  3127. 0, 0, NULL);
  3128. spin_unlock_irqrestore(&x->wait.lock, flags);
  3129. }
  3130. EXPORT_SYMBOL(complete_all);
  3131. void fastcall __sched wait_for_completion(struct completion *x)
  3132. {
  3133. might_sleep();
  3134. spin_lock_irq(&x->wait.lock);
  3135. if (!x->done) {
  3136. DECLARE_WAITQUEUE(wait, current);
  3137. wait.flags |= WQ_FLAG_EXCLUSIVE;
  3138. __add_wait_queue_tail(&x->wait, &wait);
  3139. do {
  3140. __set_current_state(TASK_UNINTERRUPTIBLE);
  3141. spin_unlock_irq(&x->wait.lock);
  3142. schedule();
  3143. spin_lock_irq(&x->wait.lock);
  3144. } while (!x->done);
  3145. __remove_wait_queue(&x->wait, &wait);
  3146. }
  3147. x->done--;
  3148. spin_unlock_irq(&x->wait.lock);
  3149. }
  3150. EXPORT_SYMBOL(wait_for_completion);
  3151. unsigned long fastcall __sched
  3152. wait_for_completion_timeout(struct completion *x, unsigned long timeout)
  3153. {
  3154. might_sleep();
  3155. spin_lock_irq(&x->wait.lock);
  3156. if (!x->done) {
  3157. DECLARE_WAITQUEUE(wait, current);
  3158. wait.flags |= WQ_FLAG_EXCLUSIVE;
  3159. __add_wait_queue_tail(&x->wait, &wait);
  3160. do {
  3161. __set_current_state(TASK_UNINTERRUPTIBLE);
  3162. spin_unlock_irq(&x->wait.lock);
  3163. timeout = schedule_timeout(timeout);
  3164. spin_lock_irq(&x->wait.lock);
  3165. if (!timeout) {
  3166. __remove_wait_queue(&x->wait, &wait);
  3167. goto out;
  3168. }
  3169. } while (!x->done);
  3170. __remove_wait_queue(&x->wait, &wait);
  3171. }
  3172. x->done--;
  3173. out:
  3174. spin_unlock_irq(&x->wait.lock);
  3175. return timeout;
  3176. }
  3177. EXPORT_SYMBOL(wait_for_completion_timeout);
  3178. int fastcall __sched wait_for_completion_interruptible(struct completion *x)
  3179. {
  3180. int ret = 0;
  3181. might_sleep();
  3182. spin_lock_irq(&x->wait.lock);
  3183. if (!x->done) {
  3184. DECLARE_WAITQUEUE(wait, current);
  3185. wait.flags |= WQ_FLAG_EXCLUSIVE;
  3186. __add_wait_queue_tail(&x->wait, &wait);
  3187. do {
  3188. if (signal_pending(current)) {
  3189. ret = -ERESTARTSYS;
  3190. __remove_wait_queue(&x->wait, &wait);
  3191. goto out;
  3192. }
  3193. __set_current_state(TASK_INTERRUPTIBLE);
  3194. spin_unlock_irq(&x->wait.lock);
  3195. schedule();
  3196. spin_lock_irq(&x->wait.lock);
  3197. } while (!x->done);
  3198. __remove_wait_queue(&x->wait, &wait);
  3199. }
  3200. x->done--;
  3201. out:
  3202. spin_unlock_irq(&x->wait.lock);
  3203. return ret;
  3204. }
  3205. EXPORT_SYMBOL(wait_for_completion_interruptible);
  3206. unsigned long fastcall __sched
  3207. wait_for_completion_interruptible_timeout(struct completion *x,
  3208. unsigned long timeout)
  3209. {
  3210. might_sleep();
  3211. spin_lock_irq(&x->wait.lock);
  3212. if (!x->done) {
  3213. DECLARE_WAITQUEUE(wait, current);
  3214. wait.flags |= WQ_FLAG_EXCLUSIVE;
  3215. __add_wait_queue_tail(&x->wait, &wait);
  3216. do {
  3217. if (signal_pending(current)) {
  3218. timeout = -ERESTARTSYS;
  3219. __remove_wait_queue(&x->wait, &wait);
  3220. goto out;
  3221. }
  3222. __set_current_state(TASK_INTERRUPTIBLE);
  3223. spin_unlock_irq(&x->wait.lock);
  3224. timeout = schedule_timeout(timeout);
  3225. spin_lock_irq(&x->wait.lock);
  3226. if (!timeout) {
  3227. __remove_wait_queue(&x->wait, &wait);
  3228. goto out;
  3229. }
  3230. } while (!x->done);
  3231. __remove_wait_queue(&x->wait, &wait);
  3232. }
  3233. x->done--;
  3234. out:
  3235. spin_unlock_irq(&x->wait.lock);
  3236. return timeout;
  3237. }
  3238. EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
  3239. #define SLEEP_ON_VAR \
  3240. unsigned long flags; \
  3241. wait_queue_t wait; \
  3242. init_waitqueue_entry(&wait, current);
  3243. #define SLEEP_ON_HEAD \
  3244. spin_lock_irqsave(&q->lock,flags); \
  3245. __add_wait_queue(q, &wait); \
  3246. spin_unlock(&q->lock);
  3247. #define SLEEP_ON_TAIL \
  3248. spin_lock_irq(&q->lock); \
  3249. __remove_wait_queue(q, &wait); \
  3250. spin_unlock_irqrestore(&q->lock, flags);
  3251. void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
  3252. {
  3253. SLEEP_ON_VAR
  3254. current->state = TASK_INTERRUPTIBLE;
  3255. SLEEP_ON_HEAD
  3256. schedule();
  3257. SLEEP_ON_TAIL
  3258. }
  3259. EXPORT_SYMBOL(interruptible_sleep_on);
  3260. long fastcall __sched
  3261. interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
  3262. {
  3263. SLEEP_ON_VAR
  3264. current->state = TASK_INTERRUPTIBLE;
  3265. SLEEP_ON_HEAD
  3266. timeout = schedule_timeout(timeout);
  3267. SLEEP_ON_TAIL
  3268. return timeout;
  3269. }
  3270. EXPORT_SYMBOL(interruptible_sleep_on_timeout);
  3271. void fastcall __sched sleep_on(wait_queue_head_t *q)
  3272. {
  3273. SLEEP_ON_VAR
  3274. current->state = TASK_UNINTERRUPTIBLE;
  3275. SLEEP_ON_HEAD
  3276. schedule();
  3277. SLEEP_ON_TAIL
  3278. }
  3279. EXPORT_SYMBOL(sleep_on);
  3280. long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
  3281. {
  3282. SLEEP_ON_VAR
  3283. current->state = TASK_UNINTERRUPTIBLE;
  3284. SLEEP_ON_HEAD
  3285. timeout = schedule_timeout(timeout);
  3286. SLEEP_ON_TAIL
  3287. return timeout;
  3288. }
  3289. EXPORT_SYMBOL(sleep_on_timeout);
  3290. #ifdef CONFIG_RT_MUTEXES
  3291. /*
  3292. * rt_mutex_setprio - set the current priority of a task
  3293. * @p: task
  3294. * @prio: prio value (kernel-internal form)
  3295. *
  3296. * This function changes the 'effective' priority of a task. It does
  3297. * not touch ->normal_prio like __setscheduler().
  3298. *
  3299. * Used by the rt_mutex code to implement priority inheritance logic.
  3300. */
  3301. void rt_mutex_setprio(struct task_struct *p, int prio)
  3302. {
  3303. struct prio_array *array;
  3304. unsigned long flags;
  3305. struct rq *rq;
  3306. int oldprio;
  3307. BUG_ON(prio < 0 || prio > MAX_PRIO);
  3308. rq = task_rq_lock(p, &flags);
  3309. oldprio = p->prio;
  3310. array = p->array;
  3311. if (array)
  3312. dequeue_task(p, array);
  3313. p->prio = prio;
  3314. if (array) {
  3315. /*
  3316. * If changing to an RT priority then queue it
  3317. * in the active array!
  3318. */
  3319. if (rt_task(p))
  3320. array = rq->active;
  3321. enqueue_task(p, array);
  3322. /*
  3323. * Reschedule if we are currently running on this runqueue and
  3324. * our priority decreased, or if we are not currently running on
  3325. * this runqueue and our priority is higher than the current's
  3326. */
  3327. if (task_running(rq, p)) {
  3328. if (p->prio > oldprio)
  3329. resched_task(rq->curr);
  3330. } else if (TASK_PREEMPTS_CURR(p, rq))
  3331. resched_task(rq->curr);
  3332. }
  3333. task_rq_unlock(rq, &flags);
  3334. }
  3335. #endif
  3336. void set_user_nice(struct task_struct *p, long nice)
  3337. {
  3338. struct prio_array *array;
  3339. int old_prio, delta;
  3340. unsigned long flags;
  3341. struct rq *rq;
  3342. if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
  3343. return;
  3344. /*
  3345. * We have to be careful, if called from sys_setpriority(),
  3346. * the task might be in the middle of scheduling on another CPU.
  3347. */
  3348. rq = task_rq_lock(p, &flags);
  3349. /*
  3350. * The RT priorities are set via sched_setscheduler(), but we still
  3351. * allow the 'normal' nice value to be set - but as expected
  3352. * it wont have any effect on scheduling until the task is
  3353. * not SCHED_NORMAL/SCHED_BATCH:
  3354. */
  3355. if (has_rt_policy(p)) {
  3356. p->static_prio = NICE_TO_PRIO(nice);
  3357. goto out_unlock;
  3358. }
  3359. array = p->array;
  3360. if (array) {
  3361. dequeue_task(p, array);
  3362. dec_raw_weighted_load(rq, p);
  3363. }
  3364. p->static_prio = NICE_TO_PRIO(nice);
  3365. set_load_weight(p);
  3366. old_prio = p->prio;
  3367. p->prio = effective_prio(p);
  3368. delta = p->prio - old_prio;
  3369. if (array) {
  3370. enqueue_task(p, array);
  3371. inc_raw_weighted_load(rq, p);
  3372. /*
  3373. * If the task increased its priority or is running and
  3374. * lowered its priority, then reschedule its CPU:
  3375. */
  3376. if (delta < 0 || (delta > 0 && task_running(rq, p)))
  3377. resched_task(rq->curr);
  3378. }
  3379. out_unlock:
  3380. task_rq_unlock(rq, &flags);
  3381. }
  3382. EXPORT_SYMBOL(set_user_nice);
  3383. /*
  3384. * can_nice - check if a task can reduce its nice value
  3385. * @p: task
  3386. * @nice: nice value
  3387. */
  3388. int can_nice(const struct task_struct *p, const int nice)
  3389. {
  3390. /* convert nice value [19,-20] to rlimit style value [1,40] */
  3391. int nice_rlim = 20 - nice;
  3392. return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
  3393. capable(CAP_SYS_NICE));
  3394. }
  3395. #ifdef __ARCH_WANT_SYS_NICE
  3396. /*
  3397. * sys_nice - change the priority of the current process.
  3398. * @increment: priority increment
  3399. *
  3400. * sys_setpriority is a more generic, but much slower function that
  3401. * does similar things.
  3402. */
  3403. asmlinkage long sys_nice(int increment)
  3404. {
  3405. long nice, retval;
  3406. /*
  3407. * Setpriority might change our priority at the same moment.
  3408. * We don't have to worry. Conceptually one call occurs first
  3409. * and we have a single winner.
  3410. */
  3411. if (increment < -40)
  3412. increment = -40;
  3413. if (increment > 40)
  3414. increment = 40;
  3415. nice = PRIO_TO_NICE(current->static_prio) + increment;
  3416. if (nice < -20)
  3417. nice = -20;
  3418. if (nice > 19)
  3419. nice = 19;
  3420. if (increment < 0 && !can_nice(current, nice))
  3421. return -EPERM;
  3422. retval = security_task_setnice(current, nice);
  3423. if (retval)
  3424. return retval;
  3425. set_user_nice(current, nice);
  3426. return 0;
  3427. }
  3428. #endif
  3429. /**
  3430. * task_prio - return the priority value of a given task.
  3431. * @p: the task in question.
  3432. *
  3433. * This is the priority value as seen by users in /proc.
  3434. * RT tasks are offset by -200. Normal tasks are centered
  3435. * around 0, value goes from -16 to +15.
  3436. */
  3437. int task_prio(const struct task_struct *p)
  3438. {
  3439. return p->prio - MAX_RT_PRIO;
  3440. }
  3441. /**
  3442. * task_nice - return the nice value of a given task.
  3443. * @p: the task in question.
  3444. */
  3445. int task_nice(const struct task_struct *p)
  3446. {
  3447. return TASK_NICE(p);
  3448. }
  3449. EXPORT_SYMBOL_GPL(task_nice);
  3450. /**
  3451. * idle_cpu - is a given cpu idle currently?
  3452. * @cpu: the processor in question.
  3453. */
  3454. int idle_cpu(int cpu)
  3455. {
  3456. return cpu_curr(cpu) == cpu_rq(cpu)->idle;
  3457. }
  3458. /**
  3459. * idle_task - return the idle task for a given cpu.
  3460. * @cpu: the processor in question.
  3461. */
  3462. struct task_struct *idle_task(int cpu)
  3463. {
  3464. return cpu_rq(cpu)->idle;
  3465. }
  3466. /**
  3467. * find_process_by_pid - find a process with a matching PID value.
  3468. * @pid: the pid in question.
  3469. */
  3470. static inline struct task_struct *find_process_by_pid(pid_t pid)
  3471. {
  3472. return pid ? find_task_by_pid(pid) : current;
  3473. }
  3474. /* Actually do priority change: must hold rq lock. */
  3475. static void __setscheduler(struct task_struct *p, int policy, int prio)
  3476. {
  3477. BUG_ON(p->array);
  3478. p->policy = policy;
  3479. p->rt_priority = prio;
  3480. p->normal_prio = normal_prio(p);
  3481. /* we are holding p->pi_lock already */
  3482. p->prio = rt_mutex_getprio(p);
  3483. /*
  3484. * SCHED_BATCH tasks are treated as perpetual CPU hogs:
  3485. */
  3486. if (policy == SCHED_BATCH)
  3487. p->sleep_avg = 0;
  3488. set_load_weight(p);
  3489. }
  3490. /**
  3491. * sched_setscheduler - change the scheduling policy and/or RT priority of
  3492. * a thread.
  3493. * @p: the task in question.
  3494. * @policy: new policy.
  3495. * @param: structure containing the new RT priority.
  3496. */
  3497. int sched_setscheduler(struct task_struct *p, int policy,
  3498. struct sched_param *param)
  3499. {
  3500. int retval, oldprio, oldpolicy = -1;
  3501. struct prio_array *array;
  3502. unsigned long flags;
  3503. struct rq *rq;
  3504. /* may grab non-irq protected spin_locks */
  3505. BUG_ON(in_interrupt());
  3506. recheck:
  3507. /* double check policy once rq lock held */
  3508. if (policy < 0)
  3509. policy = oldpolicy = p->policy;
  3510. else if (policy != SCHED_FIFO && policy != SCHED_RR &&
  3511. policy != SCHED_NORMAL && policy != SCHED_BATCH)
  3512. return -EINVAL;
  3513. /*
  3514. * Valid priorities for SCHED_FIFO and SCHED_RR are
  3515. * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
  3516. * SCHED_BATCH is 0.
  3517. */
  3518. if (param->sched_priority < 0 ||
  3519. (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
  3520. (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
  3521. return -EINVAL;
  3522. if ((policy == SCHED_NORMAL || policy == SCHED_BATCH)
  3523. != (param->sched_priority == 0))
  3524. return -EINVAL;
  3525. /*
  3526. * Allow unprivileged RT tasks to decrease priority:
  3527. */
  3528. if (!capable(CAP_SYS_NICE)) {
  3529. /*
  3530. * can't change policy, except between SCHED_NORMAL
  3531. * and SCHED_BATCH:
  3532. */
  3533. if (((policy != SCHED_NORMAL && p->policy != SCHED_BATCH) &&
  3534. (policy != SCHED_BATCH && p->policy != SCHED_NORMAL)) &&
  3535. !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
  3536. return -EPERM;
  3537. /* can't increase priority */
  3538. if ((policy != SCHED_NORMAL && policy != SCHED_BATCH) &&
  3539. param->sched_priority > p->rt_priority &&
  3540. param->sched_priority >
  3541. p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
  3542. return -EPERM;
  3543. /* can't change other user's priorities */
  3544. if ((current->euid != p->euid) &&
  3545. (current->euid != p->uid))
  3546. return -EPERM;
  3547. }
  3548. retval = security_task_setscheduler(p, policy, param);
  3549. if (retval)
  3550. return retval;
  3551. /*
  3552. * make sure no PI-waiters arrive (or leave) while we are
  3553. * changing the priority of the task:
  3554. */
  3555. spin_lock_irqsave(&p->pi_lock, flags);
  3556. /*
  3557. * To be able to change p->policy safely, the apropriate
  3558. * runqueue lock must be held.
  3559. */
  3560. rq = __task_rq_lock(p);
  3561. /* recheck policy now with rq lock held */
  3562. if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
  3563. policy = oldpolicy = -1;
  3564. __task_rq_unlock(rq);
  3565. spin_unlock_irqrestore(&p->pi_lock, flags);
  3566. goto recheck;
  3567. }
  3568. array = p->array;
  3569. if (array)
  3570. deactivate_task(p, rq);
  3571. oldprio = p->prio;
  3572. __setscheduler(p, policy, param->sched_priority);
  3573. if (array) {
  3574. __activate_task(p, rq);
  3575. /*
  3576. * Reschedule if we are currently running on this runqueue and
  3577. * our priority decreased, or if we are not currently running on
  3578. * this runqueue and our priority is higher than the current's
  3579. */
  3580. if (task_running(rq, p)) {
  3581. if (p->prio > oldprio)
  3582. resched_task(rq->curr);
  3583. } else if (TASK_PREEMPTS_CURR(p, rq))
  3584. resched_task(rq->curr);
  3585. }
  3586. __task_rq_unlock(rq);
  3587. spin_unlock_irqrestore(&p->pi_lock, flags);
  3588. rt_mutex_adjust_pi(p);
  3589. return 0;
  3590. }
  3591. EXPORT_SYMBOL_GPL(sched_setscheduler);
  3592. static int
  3593. do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
  3594. {
  3595. struct sched_param lparam;
  3596. struct task_struct *p;
  3597. int retval;
  3598. if (!param || pid < 0)
  3599. return -EINVAL;
  3600. if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
  3601. return -EFAULT;
  3602. read_lock_irq(&tasklist_lock);
  3603. p = find_process_by_pid(pid);
  3604. if (!p) {
  3605. read_unlock_irq(&tasklist_lock);
  3606. return -ESRCH;
  3607. }
  3608. get_task_struct(p);
  3609. read_unlock_irq(&tasklist_lock);
  3610. retval = sched_setscheduler(p, policy, &lparam);
  3611. put_task_struct(p);
  3612. return retval;
  3613. }
  3614. /**
  3615. * sys_sched_setscheduler - set/change the scheduler policy and RT priority
  3616. * @pid: the pid in question.
  3617. * @policy: new policy.
  3618. * @param: structure containing the new RT priority.
  3619. */
  3620. asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
  3621. struct sched_param __user *param)
  3622. {
  3623. /* negative values for policy are not valid */
  3624. if (policy < 0)
  3625. return -EINVAL;
  3626. return do_sched_setscheduler(pid, policy, param);
  3627. }
  3628. /**
  3629. * sys_sched_setparam - set/change the RT priority of a thread
  3630. * @pid: the pid in question.
  3631. * @param: structure containing the new RT priority.
  3632. */
  3633. asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
  3634. {
  3635. return do_sched_setscheduler(pid, -1, param);
  3636. }
  3637. /**
  3638. * sys_sched_getscheduler - get the policy (scheduling class) of a thread
  3639. * @pid: the pid in question.
  3640. */
  3641. asmlinkage long sys_sched_getscheduler(pid_t pid)
  3642. {
  3643. struct task_struct *p;
  3644. int retval = -EINVAL;
  3645. if (pid < 0)
  3646. goto out_nounlock;
  3647. retval = -ESRCH;
  3648. read_lock(&tasklist_lock);
  3649. p = find_process_by_pid(pid);
  3650. if (p) {
  3651. retval = security_task_getscheduler(p);
  3652. if (!retval)
  3653. retval = p->policy;
  3654. }
  3655. read_unlock(&tasklist_lock);
  3656. out_nounlock:
  3657. return retval;
  3658. }
  3659. /**
  3660. * sys_sched_getscheduler - get the RT priority of a thread
  3661. * @pid: the pid in question.
  3662. * @param: structure containing the RT priority.
  3663. */
  3664. asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
  3665. {
  3666. struct sched_param lp;
  3667. struct task_struct *p;
  3668. int retval = -EINVAL;
  3669. if (!param || pid < 0)
  3670. goto out_nounlock;
  3671. read_lock(&tasklist_lock);
  3672. p = find_process_by_pid(pid);
  3673. retval = -ESRCH;
  3674. if (!p)
  3675. goto out_unlock;
  3676. retval = security_task_getscheduler(p);
  3677. if (retval)
  3678. goto out_unlock;
  3679. lp.sched_priority = p->rt_priority;
  3680. read_unlock(&tasklist_lock);
  3681. /*
  3682. * This one might sleep, we cannot do it with a spinlock held ...
  3683. */
  3684. retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  3685. out_nounlock:
  3686. return retval;
  3687. out_unlock:
  3688. read_unlock(&tasklist_lock);
  3689. return retval;
  3690. }
  3691. long sched_setaffinity(pid_t pid, cpumask_t new_mask)
  3692. {
  3693. cpumask_t cpus_allowed;
  3694. struct task_struct *p;
  3695. int retval;
  3696. lock_cpu_hotplug();
  3697. read_lock(&tasklist_lock);
  3698. p = find_process_by_pid(pid);
  3699. if (!p) {
  3700. read_unlock(&tasklist_lock);
  3701. unlock_cpu_hotplug();
  3702. return -ESRCH;
  3703. }
  3704. /*
  3705. * It is not safe to call set_cpus_allowed with the
  3706. * tasklist_lock held. We will bump the task_struct's
  3707. * usage count and then drop tasklist_lock.
  3708. */
  3709. get_task_struct(p);
  3710. read_unlock(&tasklist_lock);
  3711. retval = -EPERM;
  3712. if ((current->euid != p->euid) && (current->euid != p->uid) &&
  3713. !capable(CAP_SYS_NICE))
  3714. goto out_unlock;
  3715. retval = security_task_setscheduler(p, 0, NULL);
  3716. if (retval)
  3717. goto out_unlock;
  3718. cpus_allowed = cpuset_cpus_allowed(p);
  3719. cpus_and(new_mask, new_mask, cpus_allowed);
  3720. retval = set_cpus_allowed(p, new_mask);
  3721. out_unlock:
  3722. put_task_struct(p);
  3723. unlock_cpu_hotplug();
  3724. return retval;
  3725. }
  3726. static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
  3727. cpumask_t *new_mask)
  3728. {
  3729. if (len < sizeof(cpumask_t)) {
  3730. memset(new_mask, 0, sizeof(cpumask_t));
  3731. } else if (len > sizeof(cpumask_t)) {
  3732. len = sizeof(cpumask_t);
  3733. }
  3734. return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
  3735. }
  3736. /**
  3737. * sys_sched_setaffinity - set the cpu affinity of a process
  3738. * @pid: pid of the process
  3739. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3740. * @user_mask_ptr: user-space pointer to the new cpu mask
  3741. */
  3742. asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
  3743. unsigned long __user *user_mask_ptr)
  3744. {
  3745. cpumask_t new_mask;
  3746. int retval;
  3747. retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
  3748. if (retval)
  3749. return retval;
  3750. return sched_setaffinity(pid, new_mask);
  3751. }
  3752. /*
  3753. * Represents all cpu's present in the system
  3754. * In systems capable of hotplug, this map could dynamically grow
  3755. * as new cpu's are detected in the system via any platform specific
  3756. * method, such as ACPI for e.g.
  3757. */
  3758. cpumask_t cpu_present_map __read_mostly;
  3759. EXPORT_SYMBOL(cpu_present_map);
  3760. #ifndef CONFIG_SMP
  3761. cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
  3762. cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
  3763. #endif
  3764. long sched_getaffinity(pid_t pid, cpumask_t *mask)
  3765. {
  3766. struct task_struct *p;
  3767. int retval;
  3768. lock_cpu_hotplug();
  3769. read_lock(&tasklist_lock);
  3770. retval = -ESRCH;
  3771. p = find_process_by_pid(pid);
  3772. if (!p)
  3773. goto out_unlock;
  3774. retval = security_task_getscheduler(p);
  3775. if (retval)
  3776. goto out_unlock;
  3777. cpus_and(*mask, p->cpus_allowed, cpu_online_map);
  3778. out_unlock:
  3779. read_unlock(&tasklist_lock);
  3780. unlock_cpu_hotplug();
  3781. if (retval)
  3782. return retval;
  3783. return 0;
  3784. }
  3785. /**
  3786. * sys_sched_getaffinity - get the cpu affinity of a process
  3787. * @pid: pid of the process
  3788. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3789. * @user_mask_ptr: user-space pointer to hold the current cpu mask
  3790. */
  3791. asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
  3792. unsigned long __user *user_mask_ptr)
  3793. {
  3794. int ret;
  3795. cpumask_t mask;
  3796. if (len < sizeof(cpumask_t))
  3797. return -EINVAL;
  3798. ret = sched_getaffinity(pid, &mask);
  3799. if (ret < 0)
  3800. return ret;
  3801. if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
  3802. return -EFAULT;
  3803. return sizeof(cpumask_t);
  3804. }
  3805. /**
  3806. * sys_sched_yield - yield the current processor to other threads.
  3807. *
  3808. * this function yields the current CPU by moving the calling thread
  3809. * to the expired array. If there are no other threads running on this
  3810. * CPU then this function will return.
  3811. */
  3812. asmlinkage long sys_sched_yield(void)
  3813. {
  3814. struct rq *rq = this_rq_lock();
  3815. struct prio_array *array = current->array, *target = rq->expired;
  3816. schedstat_inc(rq, yld_cnt);
  3817. /*
  3818. * We implement yielding by moving the task into the expired
  3819. * queue.
  3820. *
  3821. * (special rule: RT tasks will just roundrobin in the active
  3822. * array.)
  3823. */
  3824. if (rt_task(current))
  3825. target = rq->active;
  3826. if (array->nr_active == 1) {
  3827. schedstat_inc(rq, yld_act_empty);
  3828. if (!rq->expired->nr_active)
  3829. schedstat_inc(rq, yld_both_empty);
  3830. } else if (!rq->expired->nr_active)
  3831. schedstat_inc(rq, yld_exp_empty);
  3832. if (array != target) {
  3833. dequeue_task(current, array);
  3834. enqueue_task(current, target);
  3835. } else
  3836. /*
  3837. * requeue_task is cheaper so perform that if possible.
  3838. */
  3839. requeue_task(current, array);
  3840. /*
  3841. * Since we are going to call schedule() anyway, there's
  3842. * no need to preempt or enable interrupts:
  3843. */
  3844. __release(rq->lock);
  3845. spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
  3846. _raw_spin_unlock(&rq->lock);
  3847. preempt_enable_no_resched();
  3848. schedule();
  3849. return 0;
  3850. }
  3851. static inline int __resched_legal(void)
  3852. {
  3853. if (unlikely(preempt_count()))
  3854. return 0;
  3855. if (unlikely(system_state != SYSTEM_RUNNING))
  3856. return 0;
  3857. return 1;
  3858. }
  3859. static void __cond_resched(void)
  3860. {
  3861. #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
  3862. __might_sleep(__FILE__, __LINE__);
  3863. #endif
  3864. /*
  3865. * The BKS might be reacquired before we have dropped
  3866. * PREEMPT_ACTIVE, which could trigger a second
  3867. * cond_resched() call.
  3868. */
  3869. do {
  3870. add_preempt_count(PREEMPT_ACTIVE);
  3871. schedule();
  3872. sub_preempt_count(PREEMPT_ACTIVE);
  3873. } while (need_resched());
  3874. }
  3875. int __sched cond_resched(void)
  3876. {
  3877. if (need_resched() && __resched_legal()) {
  3878. __cond_resched();
  3879. return 1;
  3880. }
  3881. return 0;
  3882. }
  3883. EXPORT_SYMBOL(cond_resched);
  3884. /*
  3885. * cond_resched_lock() - if a reschedule is pending, drop the given lock,
  3886. * call schedule, and on return reacquire the lock.
  3887. *
  3888. * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
  3889. * operations here to prevent schedule() from being called twice (once via
  3890. * spin_unlock(), once by hand).
  3891. */
  3892. int cond_resched_lock(spinlock_t *lock)
  3893. {
  3894. int ret = 0;
  3895. if (need_lockbreak(lock)) {
  3896. spin_unlock(lock);
  3897. cpu_relax();
  3898. ret = 1;
  3899. spin_lock(lock);
  3900. }
  3901. if (need_resched() && __resched_legal()) {
  3902. spin_release(&lock->dep_map, 1, _THIS_IP_);
  3903. _raw_spin_unlock(lock);
  3904. preempt_enable_no_resched();
  3905. __cond_resched();
  3906. ret = 1;
  3907. spin_lock(lock);
  3908. }
  3909. return ret;
  3910. }
  3911. EXPORT_SYMBOL(cond_resched_lock);
  3912. int __sched cond_resched_softirq(void)
  3913. {
  3914. BUG_ON(!in_softirq());
  3915. if (need_resched() && __resched_legal()) {
  3916. raw_local_irq_disable();
  3917. _local_bh_enable();
  3918. raw_local_irq_enable();
  3919. __cond_resched();
  3920. local_bh_disable();
  3921. return 1;
  3922. }
  3923. return 0;
  3924. }
  3925. EXPORT_SYMBOL(cond_resched_softirq);
  3926. /**
  3927. * yield - yield the current processor to other threads.
  3928. *
  3929. * this is a shortcut for kernel-space yielding - it marks the
  3930. * thread runnable and calls sys_sched_yield().
  3931. */
  3932. void __sched yield(void)
  3933. {
  3934. set_current_state(TASK_RUNNING);
  3935. sys_sched_yield();
  3936. }
  3937. EXPORT_SYMBOL(yield);
  3938. /*
  3939. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  3940. * that process accounting knows that this is a task in IO wait state.
  3941. *
  3942. * But don't do that if it is a deliberate, throttling IO wait (this task
  3943. * has set its backing_dev_info: the queue against which it should throttle)
  3944. */
  3945. void __sched io_schedule(void)
  3946. {
  3947. struct rq *rq = &__raw_get_cpu_var(runqueues);
  3948. atomic_inc(&rq->nr_iowait);
  3949. schedule();
  3950. atomic_dec(&rq->nr_iowait);
  3951. }
  3952. EXPORT_SYMBOL(io_schedule);
  3953. long __sched io_schedule_timeout(long timeout)
  3954. {
  3955. struct rq *rq = &__raw_get_cpu_var(runqueues);
  3956. long ret;
  3957. atomic_inc(&rq->nr_iowait);
  3958. ret = schedule_timeout(timeout);
  3959. atomic_dec(&rq->nr_iowait);
  3960. return ret;
  3961. }
  3962. /**
  3963. * sys_sched_get_priority_max - return maximum RT priority.
  3964. * @policy: scheduling class.
  3965. *
  3966. * this syscall returns the maximum rt_priority that can be used
  3967. * by a given scheduling class.
  3968. */
  3969. asmlinkage long sys_sched_get_priority_max(int policy)
  3970. {
  3971. int ret = -EINVAL;
  3972. switch (policy) {
  3973. case SCHED_FIFO:
  3974. case SCHED_RR:
  3975. ret = MAX_USER_RT_PRIO-1;
  3976. break;
  3977. case SCHED_NORMAL:
  3978. case SCHED_BATCH:
  3979. ret = 0;
  3980. break;
  3981. }
  3982. return ret;
  3983. }
  3984. /**
  3985. * sys_sched_get_priority_min - return minimum RT priority.
  3986. * @policy: scheduling class.
  3987. *
  3988. * this syscall returns the minimum rt_priority that can be used
  3989. * by a given scheduling class.
  3990. */
  3991. asmlinkage long sys_sched_get_priority_min(int policy)
  3992. {
  3993. int ret = -EINVAL;
  3994. switch (policy) {
  3995. case SCHED_FIFO:
  3996. case SCHED_RR:
  3997. ret = 1;
  3998. break;
  3999. case SCHED_NORMAL:
  4000. case SCHED_BATCH:
  4001. ret = 0;
  4002. }
  4003. return ret;
  4004. }
  4005. /**
  4006. * sys_sched_rr_get_interval - return the default timeslice of a process.
  4007. * @pid: pid of the process.
  4008. * @interval: userspace pointer to the timeslice value.
  4009. *
  4010. * this syscall writes the default timeslice value of a given process
  4011. * into the user-space timespec buffer. A value of '0' means infinity.
  4012. */
  4013. asmlinkage
  4014. long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
  4015. {
  4016. struct task_struct *p;
  4017. int retval = -EINVAL;
  4018. struct timespec t;
  4019. if (pid < 0)
  4020. goto out_nounlock;
  4021. retval = -ESRCH;
  4022. read_lock(&tasklist_lock);
  4023. p = find_process_by_pid(pid);
  4024. if (!p)
  4025. goto out_unlock;
  4026. retval = security_task_getscheduler(p);
  4027. if (retval)
  4028. goto out_unlock;
  4029. jiffies_to_timespec(p->policy == SCHED_FIFO ?
  4030. 0 : task_timeslice(p), &t);
  4031. read_unlock(&tasklist_lock);
  4032. retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
  4033. out_nounlock:
  4034. return retval;
  4035. out_unlock:
  4036. read_unlock(&tasklist_lock);
  4037. return retval;
  4038. }
  4039. static inline struct task_struct *eldest_child(struct task_struct *p)
  4040. {
  4041. if (list_empty(&p->children))
  4042. return NULL;
  4043. return list_entry(p->children.next,struct task_struct,sibling);
  4044. }
  4045. static inline struct task_struct *older_sibling(struct task_struct *p)
  4046. {
  4047. if (p->sibling.prev==&p->parent->children)
  4048. return NULL;
  4049. return list_entry(p->sibling.prev,struct task_struct,sibling);
  4050. }
  4051. static inline struct task_struct *younger_sibling(struct task_struct *p)
  4052. {
  4053. if (p->sibling.next==&p->parent->children)
  4054. return NULL;
  4055. return list_entry(p->sibling.next,struct task_struct,sibling);
  4056. }
  4057. static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
  4058. static void show_task(struct task_struct *p)
  4059. {
  4060. struct task_struct *relative;
  4061. unsigned long free = 0;
  4062. unsigned state;
  4063. printk("%-13.13s ", p->comm);
  4064. state = p->state ? __ffs(p->state) + 1 : 0;
  4065. if (state < ARRAY_SIZE(stat_nam))
  4066. printk(stat_nam[state]);
  4067. else
  4068. printk("?");
  4069. #if (BITS_PER_LONG == 32)
  4070. if (state == TASK_RUNNING)
  4071. printk(" running ");
  4072. else
  4073. printk(" %08lX ", thread_saved_pc(p));
  4074. #else
  4075. if (state == TASK_RUNNING)
  4076. printk(" running task ");
  4077. else
  4078. printk(" %016lx ", thread_saved_pc(p));
  4079. #endif
  4080. #ifdef CONFIG_DEBUG_STACK_USAGE
  4081. {
  4082. unsigned long *n = end_of_stack(p);
  4083. while (!*n)
  4084. n++;
  4085. free = (unsigned long)n - (unsigned long)end_of_stack(p);
  4086. }
  4087. #endif
  4088. printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
  4089. if ((relative = eldest_child(p)))
  4090. printk("%5d ", relative->pid);
  4091. else
  4092. printk(" ");
  4093. if ((relative = younger_sibling(p)))
  4094. printk("%7d", relative->pid);
  4095. else
  4096. printk(" ");
  4097. if ((relative = older_sibling(p)))
  4098. printk(" %5d", relative->pid);
  4099. else
  4100. printk(" ");
  4101. if (!p->mm)
  4102. printk(" (L-TLB)\n");
  4103. else
  4104. printk(" (NOTLB)\n");
  4105. if (state != TASK_RUNNING)
  4106. show_stack(p, NULL);
  4107. }
  4108. void show_state(void)
  4109. {
  4110. struct task_struct *g, *p;
  4111. #if (BITS_PER_LONG == 32)
  4112. printk("\n"
  4113. " sibling\n");
  4114. printk(" task PC pid father child younger older\n");
  4115. #else
  4116. printk("\n"
  4117. " sibling\n");
  4118. printk(" task PC pid father child younger older\n");
  4119. #endif
  4120. read_lock(&tasklist_lock);
  4121. do_each_thread(g, p) {
  4122. /*
  4123. * reset the NMI-timeout, listing all files on a slow
  4124. * console might take alot of time:
  4125. */
  4126. touch_nmi_watchdog();
  4127. show_task(p);
  4128. } while_each_thread(g, p);
  4129. read_unlock(&tasklist_lock);
  4130. debug_show_all_locks();
  4131. }
  4132. /**
  4133. * init_idle - set up an idle thread for a given CPU
  4134. * @idle: task in question
  4135. * @cpu: cpu the idle task belongs to
  4136. *
  4137. * NOTE: this function does not set the idle thread's NEED_RESCHED
  4138. * flag, to make booting more robust.
  4139. */
  4140. void __devinit init_idle(struct task_struct *idle, int cpu)
  4141. {
  4142. struct rq *rq = cpu_rq(cpu);
  4143. unsigned long flags;
  4144. idle->timestamp = sched_clock();
  4145. idle->sleep_avg = 0;
  4146. idle->array = NULL;
  4147. idle->prio = idle->normal_prio = MAX_PRIO;
  4148. idle->state = TASK_RUNNING;
  4149. idle->cpus_allowed = cpumask_of_cpu(cpu);
  4150. set_task_cpu(idle, cpu);
  4151. spin_lock_irqsave(&rq->lock, flags);
  4152. rq->curr = rq->idle = idle;
  4153. #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
  4154. idle->oncpu = 1;
  4155. #endif
  4156. spin_unlock_irqrestore(&rq->lock, flags);
  4157. /* Set the preempt count _outside_ the spinlocks! */
  4158. #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
  4159. task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
  4160. #else
  4161. task_thread_info(idle)->preempt_count = 0;
  4162. #endif
  4163. }
  4164. /*
  4165. * In a system that switches off the HZ timer nohz_cpu_mask
  4166. * indicates which cpus entered this state. This is used
  4167. * in the rcu update to wait only for active cpus. For system
  4168. * which do not switch off the HZ timer nohz_cpu_mask should
  4169. * always be CPU_MASK_NONE.
  4170. */
  4171. cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
  4172. #ifdef CONFIG_SMP
  4173. /*
  4174. * This is how migration works:
  4175. *
  4176. * 1) we queue a struct migration_req structure in the source CPU's
  4177. * runqueue and wake up that CPU's migration thread.
  4178. * 2) we down() the locked semaphore => thread blocks.
  4179. * 3) migration thread wakes up (implicitly it forces the migrated
  4180. * thread off the CPU)
  4181. * 4) it gets the migration request and checks whether the migrated
  4182. * task is still in the wrong runqueue.
  4183. * 5) if it's in the wrong runqueue then the migration thread removes
  4184. * it and puts it into the right queue.
  4185. * 6) migration thread up()s the semaphore.
  4186. * 7) we wake up and the migration is done.
  4187. */
  4188. /*
  4189. * Change a given task's CPU affinity. Migrate the thread to a
  4190. * proper CPU and schedule it away if the CPU it's executing on
  4191. * is removed from the allowed bitmask.
  4192. *
  4193. * NOTE: the caller must have a valid reference to the task, the
  4194. * task must not exit() & deallocate itself prematurely. The
  4195. * call is not atomic; no spinlocks may be held.
  4196. */
  4197. int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
  4198. {
  4199. struct migration_req req;
  4200. unsigned long flags;
  4201. struct rq *rq;
  4202. int ret = 0;
  4203. rq = task_rq_lock(p, &flags);
  4204. if (!cpus_intersects(new_mask, cpu_online_map)) {
  4205. ret = -EINVAL;
  4206. goto out;
  4207. }
  4208. p->cpus_allowed = new_mask;
  4209. /* Can the task run on the task's current CPU? If so, we're done */
  4210. if (cpu_isset(task_cpu(p), new_mask))
  4211. goto out;
  4212. if (migrate_task(p, any_online_cpu(new_mask), &req)) {
  4213. /* Need help from migration thread: drop lock and wait. */
  4214. task_rq_unlock(rq, &flags);
  4215. wake_up_process(rq->migration_thread);
  4216. wait_for_completion(&req.done);
  4217. tlb_migrate_finish(p->mm);
  4218. return 0;
  4219. }
  4220. out:
  4221. task_rq_unlock(rq, &flags);
  4222. return ret;
  4223. }
  4224. EXPORT_SYMBOL_GPL(set_cpus_allowed);
  4225. /*
  4226. * Move (not current) task off this cpu, onto dest cpu. We're doing
  4227. * this because either it can't run here any more (set_cpus_allowed()
  4228. * away from this CPU, or CPU going down), or because we're
  4229. * attempting to rebalance this task on exec (sched_exec).
  4230. *
  4231. * So we race with normal scheduler movements, but that's OK, as long
  4232. * as the task is no longer on this CPU.
  4233. *
  4234. * Returns non-zero if task was successfully migrated.
  4235. */
  4236. static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
  4237. {
  4238. struct rq *rq_dest, *rq_src;
  4239. int ret = 0;
  4240. if (unlikely(cpu_is_offline(dest_cpu)))
  4241. return ret;
  4242. rq_src = cpu_rq(src_cpu);
  4243. rq_dest = cpu_rq(dest_cpu);
  4244. double_rq_lock(rq_src, rq_dest);
  4245. /* Already moved. */
  4246. if (task_cpu(p) != src_cpu)
  4247. goto out;
  4248. /* Affinity changed (again). */
  4249. if (!cpu_isset(dest_cpu, p->cpus_allowed))
  4250. goto out;
  4251. set_task_cpu(p, dest_cpu);
  4252. if (p->array) {
  4253. /*
  4254. * Sync timestamp with rq_dest's before activating.
  4255. * The same thing could be achieved by doing this step
  4256. * afterwards, and pretending it was a local activate.
  4257. * This way is cleaner and logically correct.
  4258. */
  4259. p->timestamp = p->timestamp - rq_src->timestamp_last_tick
  4260. + rq_dest->timestamp_last_tick;
  4261. deactivate_task(p, rq_src);
  4262. activate_task(p, rq_dest, 0);
  4263. if (TASK_PREEMPTS_CURR(p, rq_dest))
  4264. resched_task(rq_dest->curr);
  4265. }
  4266. ret = 1;
  4267. out:
  4268. double_rq_unlock(rq_src, rq_dest);
  4269. return ret;
  4270. }
  4271. /*
  4272. * migration_thread - this is a highprio system thread that performs
  4273. * thread migration by bumping thread off CPU then 'pushing' onto
  4274. * another runqueue.
  4275. */
  4276. static int migration_thread(void *data)
  4277. {
  4278. int cpu = (long)data;
  4279. struct rq *rq;
  4280. rq = cpu_rq(cpu);
  4281. BUG_ON(rq->migration_thread != current);
  4282. set_current_state(TASK_INTERRUPTIBLE);
  4283. while (!kthread_should_stop()) {
  4284. struct migration_req *req;
  4285. struct list_head *head;
  4286. try_to_freeze();
  4287. spin_lock_irq(&rq->lock);
  4288. if (cpu_is_offline(cpu)) {
  4289. spin_unlock_irq(&rq->lock);
  4290. goto wait_to_die;
  4291. }
  4292. if (rq->active_balance) {
  4293. active_load_balance(rq, cpu);
  4294. rq->active_balance = 0;
  4295. }
  4296. head = &rq->migration_queue;
  4297. if (list_empty(head)) {
  4298. spin_unlock_irq(&rq->lock);
  4299. schedule();
  4300. set_current_state(TASK_INTERRUPTIBLE);
  4301. continue;
  4302. }
  4303. req = list_entry(head->next, struct migration_req, list);
  4304. list_del_init(head->next);
  4305. spin_unlock(&rq->lock);
  4306. __migrate_task(req->task, cpu, req->dest_cpu);
  4307. local_irq_enable();
  4308. complete(&req->done);
  4309. }
  4310. __set_current_state(TASK_RUNNING);
  4311. return 0;
  4312. wait_to_die:
  4313. /* Wait for kthread_stop */
  4314. set_current_state(TASK_INTERRUPTIBLE);
  4315. while (!kthread_should_stop()) {
  4316. schedule();
  4317. set_current_state(TASK_INTERRUPTIBLE);
  4318. }
  4319. __set_current_state(TASK_RUNNING);
  4320. return 0;
  4321. }
  4322. #ifdef CONFIG_HOTPLUG_CPU
  4323. /* Figure out where task on dead CPU should go, use force if neccessary. */
  4324. static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
  4325. {
  4326. unsigned long flags;
  4327. cpumask_t mask;
  4328. struct rq *rq;
  4329. int dest_cpu;
  4330. restart:
  4331. /* On same node? */
  4332. mask = node_to_cpumask(cpu_to_node(dead_cpu));
  4333. cpus_and(mask, mask, p->cpus_allowed);
  4334. dest_cpu = any_online_cpu(mask);
  4335. /* On any allowed CPU? */
  4336. if (dest_cpu == NR_CPUS)
  4337. dest_cpu = any_online_cpu(p->cpus_allowed);
  4338. /* No more Mr. Nice Guy. */
  4339. if (dest_cpu == NR_CPUS) {
  4340. rq = task_rq_lock(p, &flags);
  4341. cpus_setall(p->cpus_allowed);
  4342. dest_cpu = any_online_cpu(p->cpus_allowed);
  4343. task_rq_unlock(rq, &flags);
  4344. /*
  4345. * Don't tell them about moving exiting tasks or
  4346. * kernel threads (both mm NULL), since they never
  4347. * leave kernel.
  4348. */
  4349. if (p->mm && printk_ratelimit())
  4350. printk(KERN_INFO "process %d (%s) no "
  4351. "longer affine to cpu%d\n",
  4352. p->pid, p->comm, dead_cpu);
  4353. }
  4354. if (!__migrate_task(p, dead_cpu, dest_cpu))
  4355. goto restart;
  4356. }
  4357. /*
  4358. * While a dead CPU has no uninterruptible tasks queued at this point,
  4359. * it might still have a nonzero ->nr_uninterruptible counter, because
  4360. * for performance reasons the counter is not stricly tracking tasks to
  4361. * their home CPUs. So we just add the counter to another CPU's counter,
  4362. * to keep the global sum constant after CPU-down:
  4363. */
  4364. static void migrate_nr_uninterruptible(struct rq *rq_src)
  4365. {
  4366. struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
  4367. unsigned long flags;
  4368. local_irq_save(flags);
  4369. double_rq_lock(rq_src, rq_dest);
  4370. rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
  4371. rq_src->nr_uninterruptible = 0;
  4372. double_rq_unlock(rq_src, rq_dest);
  4373. local_irq_restore(flags);
  4374. }
  4375. /* Run through task list and migrate tasks from the dead cpu. */
  4376. static void migrate_live_tasks(int src_cpu)
  4377. {
  4378. struct task_struct *p, *t;
  4379. write_lock_irq(&tasklist_lock);
  4380. do_each_thread(t, p) {
  4381. if (p == current)
  4382. continue;
  4383. if (task_cpu(p) == src_cpu)
  4384. move_task_off_dead_cpu(src_cpu, p);
  4385. } while_each_thread(t, p);
  4386. write_unlock_irq(&tasklist_lock);
  4387. }
  4388. /* Schedules idle task to be the next runnable task on current CPU.
  4389. * It does so by boosting its priority to highest possible and adding it to
  4390. * the _front_ of the runqueue. Used by CPU offline code.
  4391. */
  4392. void sched_idle_next(void)
  4393. {
  4394. int this_cpu = smp_processor_id();
  4395. struct rq *rq = cpu_rq(this_cpu);
  4396. struct task_struct *p = rq->idle;
  4397. unsigned long flags;
  4398. /* cpu has to be offline */
  4399. BUG_ON(cpu_online(this_cpu));
  4400. /*
  4401. * Strictly not necessary since rest of the CPUs are stopped by now
  4402. * and interrupts disabled on the current cpu.
  4403. */
  4404. spin_lock_irqsave(&rq->lock, flags);
  4405. __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
  4406. /* Add idle task to the _front_ of its priority queue: */
  4407. __activate_idle_task(p, rq);
  4408. spin_unlock_irqrestore(&rq->lock, flags);
  4409. }
  4410. /*
  4411. * Ensures that the idle task is using init_mm right before its cpu goes
  4412. * offline.
  4413. */
  4414. void idle_task_exit(void)
  4415. {
  4416. struct mm_struct *mm = current->active_mm;
  4417. BUG_ON(cpu_online(smp_processor_id()));
  4418. if (mm != &init_mm)
  4419. switch_mm(mm, &init_mm, current);
  4420. mmdrop(mm);
  4421. }
  4422. static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
  4423. {
  4424. struct rq *rq = cpu_rq(dead_cpu);
  4425. /* Must be exiting, otherwise would be on tasklist. */
  4426. BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
  4427. /* Cannot have done final schedule yet: would have vanished. */
  4428. BUG_ON(p->flags & PF_DEAD);
  4429. get_task_struct(p);
  4430. /*
  4431. * Drop lock around migration; if someone else moves it,
  4432. * that's OK. No task can be added to this CPU, so iteration is
  4433. * fine.
  4434. */
  4435. spin_unlock_irq(&rq->lock);
  4436. move_task_off_dead_cpu(dead_cpu, p);
  4437. spin_lock_irq(&rq->lock);
  4438. put_task_struct(p);
  4439. }
  4440. /* release_task() removes task from tasklist, so we won't find dead tasks. */
  4441. static void migrate_dead_tasks(unsigned int dead_cpu)
  4442. {
  4443. struct rq *rq = cpu_rq(dead_cpu);
  4444. unsigned int arr, i;
  4445. for (arr = 0; arr < 2; arr++) {
  4446. for (i = 0; i < MAX_PRIO; i++) {
  4447. struct list_head *list = &rq->arrays[arr].queue[i];
  4448. while (!list_empty(list))
  4449. migrate_dead(dead_cpu, list_entry(list->next,
  4450. struct task_struct, run_list));
  4451. }
  4452. }
  4453. }
  4454. #endif /* CONFIG_HOTPLUG_CPU */
  4455. /*
  4456. * migration_call - callback that gets triggered when a CPU is added.
  4457. * Here we can start up the necessary migration thread for the new CPU.
  4458. */
  4459. static int __cpuinit
  4460. migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
  4461. {
  4462. struct task_struct *p;
  4463. int cpu = (long)hcpu;
  4464. unsigned long flags;
  4465. struct rq *rq;
  4466. switch (action) {
  4467. case CPU_UP_PREPARE:
  4468. p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
  4469. if (IS_ERR(p))
  4470. return NOTIFY_BAD;
  4471. p->flags |= PF_NOFREEZE;
  4472. kthread_bind(p, cpu);
  4473. /* Must be high prio: stop_machine expects to yield to it. */
  4474. rq = task_rq_lock(p, &flags);
  4475. __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
  4476. task_rq_unlock(rq, &flags);
  4477. cpu_rq(cpu)->migration_thread = p;
  4478. break;
  4479. case CPU_ONLINE:
  4480. /* Strictly unneccessary, as first user will wake it. */
  4481. wake_up_process(cpu_rq(cpu)->migration_thread);
  4482. break;
  4483. #ifdef CONFIG_HOTPLUG_CPU
  4484. case CPU_UP_CANCELED:
  4485. if (!cpu_rq(cpu)->migration_thread)
  4486. break;
  4487. /* Unbind it from offline cpu so it can run. Fall thru. */
  4488. kthread_bind(cpu_rq(cpu)->migration_thread,
  4489. any_online_cpu(cpu_online_map));
  4490. kthread_stop(cpu_rq(cpu)->migration_thread);
  4491. cpu_rq(cpu)->migration_thread = NULL;
  4492. break;
  4493. case CPU_DEAD:
  4494. migrate_live_tasks(cpu);
  4495. rq = cpu_rq(cpu);
  4496. kthread_stop(rq->migration_thread);
  4497. rq->migration_thread = NULL;
  4498. /* Idle task back to normal (off runqueue, low prio) */
  4499. rq = task_rq_lock(rq->idle, &flags);
  4500. deactivate_task(rq->idle, rq);
  4501. rq->idle->static_prio = MAX_PRIO;
  4502. __setscheduler(rq->idle, SCHED_NORMAL, 0);
  4503. migrate_dead_tasks(cpu);
  4504. task_rq_unlock(rq, &flags);
  4505. migrate_nr_uninterruptible(rq);
  4506. BUG_ON(rq->nr_running != 0);
  4507. /* No need to migrate the tasks: it was best-effort if
  4508. * they didn't do lock_cpu_hotplug(). Just wake up
  4509. * the requestors. */
  4510. spin_lock_irq(&rq->lock);
  4511. while (!list_empty(&rq->migration_queue)) {
  4512. struct migration_req *req;
  4513. req = list_entry(rq->migration_queue.next,
  4514. struct migration_req, list);
  4515. list_del_init(&req->list);
  4516. complete(&req->done);
  4517. }
  4518. spin_unlock_irq(&rq->lock);
  4519. break;
  4520. #endif
  4521. }
  4522. return NOTIFY_OK;
  4523. }
  4524. /* Register at highest priority so that task migration (migrate_all_tasks)
  4525. * happens before everything else.
  4526. */
  4527. static struct notifier_block __cpuinitdata migration_notifier = {
  4528. .notifier_call = migration_call,
  4529. .priority = 10
  4530. };
  4531. int __init migration_init(void)
  4532. {
  4533. void *cpu = (void *)(long)smp_processor_id();
  4534. /* Start one for the boot CPU: */
  4535. migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
  4536. migration_call(&migration_notifier, CPU_ONLINE, cpu);
  4537. register_cpu_notifier(&migration_notifier);
  4538. return 0;
  4539. }
  4540. #endif
  4541. #ifdef CONFIG_SMP
  4542. #undef SCHED_DOMAIN_DEBUG
  4543. #ifdef SCHED_DOMAIN_DEBUG
  4544. static void sched_domain_debug(struct sched_domain *sd, int cpu)
  4545. {
  4546. int level = 0;
  4547. if (!sd) {
  4548. printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
  4549. return;
  4550. }
  4551. printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
  4552. do {
  4553. int i;
  4554. char str[NR_CPUS];
  4555. struct sched_group *group = sd->groups;
  4556. cpumask_t groupmask;
  4557. cpumask_scnprintf(str, NR_CPUS, sd->span);
  4558. cpus_clear(groupmask);
  4559. printk(KERN_DEBUG);
  4560. for (i = 0; i < level + 1; i++)
  4561. printk(" ");
  4562. printk("domain %d: ", level);
  4563. if (!(sd->flags & SD_LOAD_BALANCE)) {
  4564. printk("does not load-balance\n");
  4565. if (sd->parent)
  4566. printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
  4567. break;
  4568. }
  4569. printk("span %s\n", str);
  4570. if (!cpu_isset(cpu, sd->span))
  4571. printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
  4572. if (!cpu_isset(cpu, group->cpumask))
  4573. printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
  4574. printk(KERN_DEBUG);
  4575. for (i = 0; i < level + 2; i++)
  4576. printk(" ");
  4577. printk("groups:");
  4578. do {
  4579. if (!group) {
  4580. printk("\n");
  4581. printk(KERN_ERR "ERROR: group is NULL\n");
  4582. break;
  4583. }
  4584. if (!group->cpu_power) {
  4585. printk("\n");
  4586. printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
  4587. }
  4588. if (!cpus_weight(group->cpumask)) {
  4589. printk("\n");
  4590. printk(KERN_ERR "ERROR: empty group\n");
  4591. }
  4592. if (cpus_intersects(groupmask, group->cpumask)) {
  4593. printk("\n");
  4594. printk(KERN_ERR "ERROR: repeated CPUs\n");
  4595. }
  4596. cpus_or(groupmask, groupmask, group->cpumask);
  4597. cpumask_scnprintf(str, NR_CPUS, group->cpumask);
  4598. printk(" %s", str);
  4599. group = group->next;
  4600. } while (group != sd->groups);
  4601. printk("\n");
  4602. if (!cpus_equal(sd->span, groupmask))
  4603. printk(KERN_ERR "ERROR: groups don't span domain->span\n");
  4604. level++;
  4605. sd = sd->parent;
  4606. if (sd) {
  4607. if (!cpus_subset(groupmask, sd->span))
  4608. printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
  4609. }
  4610. } while (sd);
  4611. }
  4612. #else
  4613. # define sched_domain_debug(sd, cpu) do { } while (0)
  4614. #endif
  4615. static int sd_degenerate(struct sched_domain *sd)
  4616. {
  4617. if (cpus_weight(sd->span) == 1)
  4618. return 1;
  4619. /* Following flags need at least 2 groups */
  4620. if (sd->flags & (SD_LOAD_BALANCE |
  4621. SD_BALANCE_NEWIDLE |
  4622. SD_BALANCE_FORK |
  4623. SD_BALANCE_EXEC)) {
  4624. if (sd->groups != sd->groups->next)
  4625. return 0;
  4626. }
  4627. /* Following flags don't use groups */
  4628. if (sd->flags & (SD_WAKE_IDLE |
  4629. SD_WAKE_AFFINE |
  4630. SD_WAKE_BALANCE))
  4631. return 0;
  4632. return 1;
  4633. }
  4634. static int
  4635. sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
  4636. {
  4637. unsigned long cflags = sd->flags, pflags = parent->flags;
  4638. if (sd_degenerate(parent))
  4639. return 1;
  4640. if (!cpus_equal(sd->span, parent->span))
  4641. return 0;
  4642. /* Does parent contain flags not in child? */
  4643. /* WAKE_BALANCE is a subset of WAKE_AFFINE */
  4644. if (cflags & SD_WAKE_AFFINE)
  4645. pflags &= ~SD_WAKE_BALANCE;
  4646. /* Flags needing groups don't count if only 1 group in parent */
  4647. if (parent->groups == parent->groups->next) {
  4648. pflags &= ~(SD_LOAD_BALANCE |
  4649. SD_BALANCE_NEWIDLE |
  4650. SD_BALANCE_FORK |
  4651. SD_BALANCE_EXEC);
  4652. }
  4653. if (~cflags & pflags)
  4654. return 0;
  4655. return 1;
  4656. }
  4657. /*
  4658. * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
  4659. * hold the hotplug lock.
  4660. */
  4661. static void cpu_attach_domain(struct sched_domain *sd, int cpu)
  4662. {
  4663. struct rq *rq = cpu_rq(cpu);
  4664. struct sched_domain *tmp;
  4665. /* Remove the sched domains which do not contribute to scheduling. */
  4666. for (tmp = sd; tmp; tmp = tmp->parent) {
  4667. struct sched_domain *parent = tmp->parent;
  4668. if (!parent)
  4669. break;
  4670. if (sd_parent_degenerate(tmp, parent))
  4671. tmp->parent = parent->parent;
  4672. }
  4673. if (sd && sd_degenerate(sd))
  4674. sd = sd->parent;
  4675. sched_domain_debug(sd, cpu);
  4676. rcu_assign_pointer(rq->sd, sd);
  4677. }
  4678. /* cpus with isolated domains */
  4679. static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
  4680. /* Setup the mask of cpus configured for isolated domains */
  4681. static int __init isolated_cpu_setup(char *str)
  4682. {
  4683. int ints[NR_CPUS], i;
  4684. str = get_options(str, ARRAY_SIZE(ints), ints);
  4685. cpus_clear(cpu_isolated_map);
  4686. for (i = 1; i <= ints[0]; i++)
  4687. if (ints[i] < NR_CPUS)
  4688. cpu_set(ints[i], cpu_isolated_map);
  4689. return 1;
  4690. }
  4691. __setup ("isolcpus=", isolated_cpu_setup);
  4692. /*
  4693. * init_sched_build_groups takes an array of groups, the cpumask we wish
  4694. * to span, and a pointer to a function which identifies what group a CPU
  4695. * belongs to. The return value of group_fn must be a valid index into the
  4696. * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
  4697. * keep track of groups covered with a cpumask_t).
  4698. *
  4699. * init_sched_build_groups will build a circular linked list of the groups
  4700. * covered by the given span, and will set each group's ->cpumask correctly,
  4701. * and ->cpu_power to 0.
  4702. */
  4703. static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
  4704. int (*group_fn)(int cpu))
  4705. {
  4706. struct sched_group *first = NULL, *last = NULL;
  4707. cpumask_t covered = CPU_MASK_NONE;
  4708. int i;
  4709. for_each_cpu_mask(i, span) {
  4710. int group = group_fn(i);
  4711. struct sched_group *sg = &groups[group];
  4712. int j;
  4713. if (cpu_isset(i, covered))
  4714. continue;
  4715. sg->cpumask = CPU_MASK_NONE;
  4716. sg->cpu_power = 0;
  4717. for_each_cpu_mask(j, span) {
  4718. if (group_fn(j) != group)
  4719. continue;
  4720. cpu_set(j, covered);
  4721. cpu_set(j, sg->cpumask);
  4722. }
  4723. if (!first)
  4724. first = sg;
  4725. if (last)
  4726. last->next = sg;
  4727. last = sg;
  4728. }
  4729. last->next = first;
  4730. }
  4731. #define SD_NODES_PER_DOMAIN 16
  4732. /*
  4733. * Self-tuning task migration cost measurement between source and target CPUs.
  4734. *
  4735. * This is done by measuring the cost of manipulating buffers of varying
  4736. * sizes. For a given buffer-size here are the steps that are taken:
  4737. *
  4738. * 1) the source CPU reads+dirties a shared buffer
  4739. * 2) the target CPU reads+dirties the same shared buffer
  4740. *
  4741. * We measure how long they take, in the following 4 scenarios:
  4742. *
  4743. * - source: CPU1, target: CPU2 | cost1
  4744. * - source: CPU2, target: CPU1 | cost2
  4745. * - source: CPU1, target: CPU1 | cost3
  4746. * - source: CPU2, target: CPU2 | cost4
  4747. *
  4748. * We then calculate the cost3+cost4-cost1-cost2 difference - this is
  4749. * the cost of migration.
  4750. *
  4751. * We then start off from a small buffer-size and iterate up to larger
  4752. * buffer sizes, in 5% steps - measuring each buffer-size separately, and
  4753. * doing a maximum search for the cost. (The maximum cost for a migration
  4754. * normally occurs when the working set size is around the effective cache
  4755. * size.)
  4756. */
  4757. #define SEARCH_SCOPE 2
  4758. #define MIN_CACHE_SIZE (64*1024U)
  4759. #define DEFAULT_CACHE_SIZE (5*1024*1024U)
  4760. #define ITERATIONS 1
  4761. #define SIZE_THRESH 130
  4762. #define COST_THRESH 130
  4763. /*
  4764. * The migration cost is a function of 'domain distance'. Domain
  4765. * distance is the number of steps a CPU has to iterate down its
  4766. * domain tree to share a domain with the other CPU. The farther
  4767. * two CPUs are from each other, the larger the distance gets.
  4768. *
  4769. * Note that we use the distance only to cache measurement results,
  4770. * the distance value is not used numerically otherwise. When two
  4771. * CPUs have the same distance it is assumed that the migration
  4772. * cost is the same. (this is a simplification but quite practical)
  4773. */
  4774. #define MAX_DOMAIN_DISTANCE 32
  4775. static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
  4776. { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] =
  4777. /*
  4778. * Architectures may override the migration cost and thus avoid
  4779. * boot-time calibration. Unit is nanoseconds. Mostly useful for
  4780. * virtualized hardware:
  4781. */
  4782. #ifdef CONFIG_DEFAULT_MIGRATION_COST
  4783. CONFIG_DEFAULT_MIGRATION_COST
  4784. #else
  4785. -1LL
  4786. #endif
  4787. };
  4788. /*
  4789. * Allow override of migration cost - in units of microseconds.
  4790. * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
  4791. * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
  4792. */
  4793. static int __init migration_cost_setup(char *str)
  4794. {
  4795. int ints[MAX_DOMAIN_DISTANCE+1], i;
  4796. str = get_options(str, ARRAY_SIZE(ints), ints);
  4797. printk("#ints: %d\n", ints[0]);
  4798. for (i = 1; i <= ints[0]; i++) {
  4799. migration_cost[i-1] = (unsigned long long)ints[i]*1000;
  4800. printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
  4801. }
  4802. return 1;
  4803. }
  4804. __setup ("migration_cost=", migration_cost_setup);
  4805. /*
  4806. * Global multiplier (divisor) for migration-cutoff values,
  4807. * in percentiles. E.g. use a value of 150 to get 1.5 times
  4808. * longer cache-hot cutoff times.
  4809. *
  4810. * (We scale it from 100 to 128 to long long handling easier.)
  4811. */
  4812. #define MIGRATION_FACTOR_SCALE 128
  4813. static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
  4814. static int __init setup_migration_factor(char *str)
  4815. {
  4816. get_option(&str, &migration_factor);
  4817. migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
  4818. return 1;
  4819. }
  4820. __setup("migration_factor=", setup_migration_factor);
  4821. /*
  4822. * Estimated distance of two CPUs, measured via the number of domains
  4823. * we have to pass for the two CPUs to be in the same span:
  4824. */
  4825. static unsigned long domain_distance(int cpu1, int cpu2)
  4826. {
  4827. unsigned long distance = 0;
  4828. struct sched_domain *sd;
  4829. for_each_domain(cpu1, sd) {
  4830. WARN_ON(!cpu_isset(cpu1, sd->span));
  4831. if (cpu_isset(cpu2, sd->span))
  4832. return distance;
  4833. distance++;
  4834. }
  4835. if (distance >= MAX_DOMAIN_DISTANCE) {
  4836. WARN_ON(1);
  4837. distance = MAX_DOMAIN_DISTANCE-1;
  4838. }
  4839. return distance;
  4840. }
  4841. static unsigned int migration_debug;
  4842. static int __init setup_migration_debug(char *str)
  4843. {
  4844. get_option(&str, &migration_debug);
  4845. return 1;
  4846. }
  4847. __setup("migration_debug=", setup_migration_debug);
  4848. /*
  4849. * Maximum cache-size that the scheduler should try to measure.
  4850. * Architectures with larger caches should tune this up during
  4851. * bootup. Gets used in the domain-setup code (i.e. during SMP
  4852. * bootup).
  4853. */
  4854. unsigned int max_cache_size;
  4855. static int __init setup_max_cache_size(char *str)
  4856. {
  4857. get_option(&str, &max_cache_size);
  4858. return 1;
  4859. }
  4860. __setup("max_cache_size=", setup_max_cache_size);
  4861. /*
  4862. * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
  4863. * is the operation that is timed, so we try to generate unpredictable
  4864. * cachemisses that still end up filling the L2 cache:
  4865. */
  4866. static void touch_cache(void *__cache, unsigned long __size)
  4867. {
  4868. unsigned long size = __size/sizeof(long), chunk1 = size/3,
  4869. chunk2 = 2*size/3;
  4870. unsigned long *cache = __cache;
  4871. int i;
  4872. for (i = 0; i < size/6; i += 8) {
  4873. switch (i % 6) {
  4874. case 0: cache[i]++;
  4875. case 1: cache[size-1-i]++;
  4876. case 2: cache[chunk1-i]++;
  4877. case 3: cache[chunk1+i]++;
  4878. case 4: cache[chunk2-i]++;
  4879. case 5: cache[chunk2+i]++;
  4880. }
  4881. }
  4882. }
  4883. /*
  4884. * Measure the cache-cost of one task migration. Returns in units of nsec.
  4885. */
  4886. static unsigned long long
  4887. measure_one(void *cache, unsigned long size, int source, int target)
  4888. {
  4889. cpumask_t mask, saved_mask;
  4890. unsigned long long t0, t1, t2, t3, cost;
  4891. saved_mask = current->cpus_allowed;
  4892. /*
  4893. * Flush source caches to RAM and invalidate them:
  4894. */
  4895. sched_cacheflush();
  4896. /*
  4897. * Migrate to the source CPU:
  4898. */
  4899. mask = cpumask_of_cpu(source);
  4900. set_cpus_allowed(current, mask);
  4901. WARN_ON(smp_processor_id() != source);
  4902. /*
  4903. * Dirty the working set:
  4904. */
  4905. t0 = sched_clock();
  4906. touch_cache(cache, size);
  4907. t1 = sched_clock();
  4908. /*
  4909. * Migrate to the target CPU, dirty the L2 cache and access
  4910. * the shared buffer. (which represents the working set
  4911. * of a migrated task.)
  4912. */
  4913. mask = cpumask_of_cpu(target);
  4914. set_cpus_allowed(current, mask);
  4915. WARN_ON(smp_processor_id() != target);
  4916. t2 = sched_clock();
  4917. touch_cache(cache, size);
  4918. t3 = sched_clock();
  4919. cost = t1-t0 + t3-t2;
  4920. if (migration_debug >= 2)
  4921. printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
  4922. source, target, t1-t0, t1-t0, t3-t2, cost);
  4923. /*
  4924. * Flush target caches to RAM and invalidate them:
  4925. */
  4926. sched_cacheflush();
  4927. set_cpus_allowed(current, saved_mask);
  4928. return cost;
  4929. }
  4930. /*
  4931. * Measure a series of task migrations and return the average
  4932. * result. Since this code runs early during bootup the system
  4933. * is 'undisturbed' and the average latency makes sense.
  4934. *
  4935. * The algorithm in essence auto-detects the relevant cache-size,
  4936. * so it will properly detect different cachesizes for different
  4937. * cache-hierarchies, depending on how the CPUs are connected.
  4938. *
  4939. * Architectures can prime the upper limit of the search range via
  4940. * max_cache_size, otherwise the search range defaults to 20MB...64K.
  4941. */
  4942. static unsigned long long
  4943. measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
  4944. {
  4945. unsigned long long cost1, cost2;
  4946. int i;
  4947. /*
  4948. * Measure the migration cost of 'size' bytes, over an
  4949. * average of 10 runs:
  4950. *
  4951. * (We perturb the cache size by a small (0..4k)
  4952. * value to compensate size/alignment related artifacts.
  4953. * We also subtract the cost of the operation done on
  4954. * the same CPU.)
  4955. */
  4956. cost1 = 0;
  4957. /*
  4958. * dry run, to make sure we start off cache-cold on cpu1,
  4959. * and to get any vmalloc pagefaults in advance:
  4960. */
  4961. measure_one(cache, size, cpu1, cpu2);
  4962. for (i = 0; i < ITERATIONS; i++)
  4963. cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
  4964. measure_one(cache, size, cpu2, cpu1);
  4965. for (i = 0; i < ITERATIONS; i++)
  4966. cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
  4967. /*
  4968. * (We measure the non-migrating [cached] cost on both
  4969. * cpu1 and cpu2, to handle CPUs with different speeds)
  4970. */
  4971. cost2 = 0;
  4972. measure_one(cache, size, cpu1, cpu1);
  4973. for (i = 0; i < ITERATIONS; i++)
  4974. cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
  4975. measure_one(cache, size, cpu2, cpu2);
  4976. for (i = 0; i < ITERATIONS; i++)
  4977. cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
  4978. /*
  4979. * Get the per-iteration migration cost:
  4980. */
  4981. do_div(cost1, 2*ITERATIONS);
  4982. do_div(cost2, 2*ITERATIONS);
  4983. return cost1 - cost2;
  4984. }
  4985. static unsigned long long measure_migration_cost(int cpu1, int cpu2)
  4986. {
  4987. unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
  4988. unsigned int max_size, size, size_found = 0;
  4989. long long cost = 0, prev_cost;
  4990. void *cache;
  4991. /*
  4992. * Search from max_cache_size*5 down to 64K - the real relevant
  4993. * cachesize has to lie somewhere inbetween.
  4994. */
  4995. if (max_cache_size) {
  4996. max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
  4997. size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
  4998. } else {
  4999. /*
  5000. * Since we have no estimation about the relevant
  5001. * search range
  5002. */
  5003. max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
  5004. size = MIN_CACHE_SIZE;
  5005. }
  5006. if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
  5007. printk("cpu %d and %d not both online!\n", cpu1, cpu2);
  5008. return 0;
  5009. }
  5010. /*
  5011. * Allocate the working set:
  5012. */
  5013. cache = vmalloc(max_size);
  5014. if (!cache) {
  5015. printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
  5016. return 1000000; // return 1 msec on very small boxen
  5017. }
  5018. while (size <= max_size) {
  5019. prev_cost = cost;
  5020. cost = measure_cost(cpu1, cpu2, cache, size);
  5021. /*
  5022. * Update the max:
  5023. */
  5024. if (cost > 0) {
  5025. if (max_cost < cost) {
  5026. max_cost = cost;
  5027. size_found = size;
  5028. }
  5029. }
  5030. /*
  5031. * Calculate average fluctuation, we use this to prevent
  5032. * noise from triggering an early break out of the loop:
  5033. */
  5034. fluct = abs(cost - prev_cost);
  5035. avg_fluct = (avg_fluct + fluct)/2;
  5036. if (migration_debug)
  5037. printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
  5038. cpu1, cpu2, size,
  5039. (long)cost / 1000000,
  5040. ((long)cost / 100000) % 10,
  5041. (long)max_cost / 1000000,
  5042. ((long)max_cost / 100000) % 10,
  5043. domain_distance(cpu1, cpu2),
  5044. cost, avg_fluct);
  5045. /*
  5046. * If we iterated at least 20% past the previous maximum,
  5047. * and the cost has dropped by more than 20% already,
  5048. * (taking fluctuations into account) then we assume to
  5049. * have found the maximum and break out of the loop early:
  5050. */
  5051. if (size_found && (size*100 > size_found*SIZE_THRESH))
  5052. if (cost+avg_fluct <= 0 ||
  5053. max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
  5054. if (migration_debug)
  5055. printk("-> found max.\n");
  5056. break;
  5057. }
  5058. /*
  5059. * Increase the cachesize in 10% steps:
  5060. */
  5061. size = size * 10 / 9;
  5062. }
  5063. if (migration_debug)
  5064. printk("[%d][%d] working set size found: %d, cost: %Ld\n",
  5065. cpu1, cpu2, size_found, max_cost);
  5066. vfree(cache);
  5067. /*
  5068. * A task is considered 'cache cold' if at least 2 times
  5069. * the worst-case cost of migration has passed.
  5070. *
  5071. * (this limit is only listened to if the load-balancing
  5072. * situation is 'nice' - if there is a large imbalance we
  5073. * ignore it for the sake of CPU utilization and
  5074. * processing fairness.)
  5075. */
  5076. return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
  5077. }
  5078. static void calibrate_migration_costs(const cpumask_t *cpu_map)
  5079. {
  5080. int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
  5081. unsigned long j0, j1, distance, max_distance = 0;
  5082. struct sched_domain *sd;
  5083. j0 = jiffies;
  5084. /*
  5085. * First pass - calculate the cacheflush times:
  5086. */
  5087. for_each_cpu_mask(cpu1, *cpu_map) {
  5088. for_each_cpu_mask(cpu2, *cpu_map) {
  5089. if (cpu1 == cpu2)
  5090. continue;
  5091. distance = domain_distance(cpu1, cpu2);
  5092. max_distance = max(max_distance, distance);
  5093. /*
  5094. * No result cached yet?
  5095. */
  5096. if (migration_cost[distance] == -1LL)
  5097. migration_cost[distance] =
  5098. measure_migration_cost(cpu1, cpu2);
  5099. }
  5100. }
  5101. /*
  5102. * Second pass - update the sched domain hierarchy with
  5103. * the new cache-hot-time estimations:
  5104. */
  5105. for_each_cpu_mask(cpu, *cpu_map) {
  5106. distance = 0;
  5107. for_each_domain(cpu, sd) {
  5108. sd->cache_hot_time = migration_cost[distance];
  5109. distance++;
  5110. }
  5111. }
  5112. /*
  5113. * Print the matrix:
  5114. */
  5115. if (migration_debug)
  5116. printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
  5117. max_cache_size,
  5118. #ifdef CONFIG_X86
  5119. cpu_khz/1000
  5120. #else
  5121. -1
  5122. #endif
  5123. );
  5124. if (system_state == SYSTEM_BOOTING) {
  5125. printk("migration_cost=");
  5126. for (distance = 0; distance <= max_distance; distance++) {
  5127. if (distance)
  5128. printk(",");
  5129. printk("%ld", (long)migration_cost[distance] / 1000);
  5130. }
  5131. printk("\n");
  5132. }
  5133. j1 = jiffies;
  5134. if (migration_debug)
  5135. printk("migration: %ld seconds\n", (j1-j0)/HZ);
  5136. /*
  5137. * Move back to the original CPU. NUMA-Q gets confused
  5138. * if we migrate to another quad during bootup.
  5139. */
  5140. if (raw_smp_processor_id() != orig_cpu) {
  5141. cpumask_t mask = cpumask_of_cpu(orig_cpu),
  5142. saved_mask = current->cpus_allowed;
  5143. set_cpus_allowed(current, mask);
  5144. set_cpus_allowed(current, saved_mask);
  5145. }
  5146. }
  5147. #ifdef CONFIG_NUMA
  5148. /**
  5149. * find_next_best_node - find the next node to include in a sched_domain
  5150. * @node: node whose sched_domain we're building
  5151. * @used_nodes: nodes already in the sched_domain
  5152. *
  5153. * Find the next node to include in a given scheduling domain. Simply
  5154. * finds the closest node not already in the @used_nodes map.
  5155. *
  5156. * Should use nodemask_t.
  5157. */
  5158. static int find_next_best_node(int node, unsigned long *used_nodes)
  5159. {
  5160. int i, n, val, min_val, best_node = 0;
  5161. min_val = INT_MAX;
  5162. for (i = 0; i < MAX_NUMNODES; i++) {
  5163. /* Start at @node */
  5164. n = (node + i) % MAX_NUMNODES;
  5165. if (!nr_cpus_node(n))
  5166. continue;
  5167. /* Skip already used nodes */
  5168. if (test_bit(n, used_nodes))
  5169. continue;
  5170. /* Simple min distance search */
  5171. val = node_distance(node, n);
  5172. if (val < min_val) {
  5173. min_val = val;
  5174. best_node = n;
  5175. }
  5176. }
  5177. set_bit(best_node, used_nodes);
  5178. return best_node;
  5179. }
  5180. /**
  5181. * sched_domain_node_span - get a cpumask for a node's sched_domain
  5182. * @node: node whose cpumask we're constructing
  5183. * @size: number of nodes to include in this span
  5184. *
  5185. * Given a node, construct a good cpumask for its sched_domain to span. It
  5186. * should be one that prevents unnecessary balancing, but also spreads tasks
  5187. * out optimally.
  5188. */
  5189. static cpumask_t sched_domain_node_span(int node)
  5190. {
  5191. DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
  5192. cpumask_t span, nodemask;
  5193. int i;
  5194. cpus_clear(span);
  5195. bitmap_zero(used_nodes, MAX_NUMNODES);
  5196. nodemask = node_to_cpumask(node);
  5197. cpus_or(span, span, nodemask);
  5198. set_bit(node, used_nodes);
  5199. for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
  5200. int next_node = find_next_best_node(node, used_nodes);
  5201. nodemask = node_to_cpumask(next_node);
  5202. cpus_or(span, span, nodemask);
  5203. }
  5204. return span;
  5205. }
  5206. #endif
  5207. int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
  5208. /*
  5209. * SMT sched-domains:
  5210. */
  5211. #ifdef CONFIG_SCHED_SMT
  5212. static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
  5213. static struct sched_group sched_group_cpus[NR_CPUS];
  5214. static int cpu_to_cpu_group(int cpu)
  5215. {
  5216. return cpu;
  5217. }
  5218. #endif
  5219. /*
  5220. * multi-core sched-domains:
  5221. */
  5222. #ifdef CONFIG_SCHED_MC
  5223. static DEFINE_PER_CPU(struct sched_domain, core_domains);
  5224. static struct sched_group *sched_group_core_bycpu[NR_CPUS];
  5225. #endif
  5226. #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
  5227. static int cpu_to_core_group(int cpu)
  5228. {
  5229. return first_cpu(cpu_sibling_map[cpu]);
  5230. }
  5231. #elif defined(CONFIG_SCHED_MC)
  5232. static int cpu_to_core_group(int cpu)
  5233. {
  5234. return cpu;
  5235. }
  5236. #endif
  5237. static DEFINE_PER_CPU(struct sched_domain, phys_domains);
  5238. static struct sched_group *sched_group_phys_bycpu[NR_CPUS];
  5239. static int cpu_to_phys_group(int cpu)
  5240. {
  5241. #ifdef CONFIG_SCHED_MC
  5242. cpumask_t mask = cpu_coregroup_map(cpu);
  5243. return first_cpu(mask);
  5244. #elif defined(CONFIG_SCHED_SMT)
  5245. return first_cpu(cpu_sibling_map[cpu]);
  5246. #else
  5247. return cpu;
  5248. #endif
  5249. }
  5250. #ifdef CONFIG_NUMA
  5251. /*
  5252. * The init_sched_build_groups can't handle what we want to do with node
  5253. * groups, so roll our own. Now each node has its own list of groups which
  5254. * gets dynamically allocated.
  5255. */
  5256. static DEFINE_PER_CPU(struct sched_domain, node_domains);
  5257. static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
  5258. static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
  5259. static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
  5260. static int cpu_to_allnodes_group(int cpu)
  5261. {
  5262. return cpu_to_node(cpu);
  5263. }
  5264. static void init_numa_sched_groups_power(struct sched_group *group_head)
  5265. {
  5266. struct sched_group *sg = group_head;
  5267. int j;
  5268. if (!sg)
  5269. return;
  5270. next_sg:
  5271. for_each_cpu_mask(j, sg->cpumask) {
  5272. struct sched_domain *sd;
  5273. sd = &per_cpu(phys_domains, j);
  5274. if (j != first_cpu(sd->groups->cpumask)) {
  5275. /*
  5276. * Only add "power" once for each
  5277. * physical package.
  5278. */
  5279. continue;
  5280. }
  5281. sg->cpu_power += sd->groups->cpu_power;
  5282. }
  5283. sg = sg->next;
  5284. if (sg != group_head)
  5285. goto next_sg;
  5286. }
  5287. #endif
  5288. /* Free memory allocated for various sched_group structures */
  5289. static void free_sched_groups(const cpumask_t *cpu_map)
  5290. {
  5291. int cpu;
  5292. #ifdef CONFIG_NUMA
  5293. int i;
  5294. for_each_cpu_mask(cpu, *cpu_map) {
  5295. struct sched_group *sched_group_allnodes
  5296. = sched_group_allnodes_bycpu[cpu];
  5297. struct sched_group **sched_group_nodes
  5298. = sched_group_nodes_bycpu[cpu];
  5299. if (sched_group_allnodes) {
  5300. kfree(sched_group_allnodes);
  5301. sched_group_allnodes_bycpu[cpu] = NULL;
  5302. }
  5303. if (!sched_group_nodes)
  5304. continue;
  5305. for (i = 0; i < MAX_NUMNODES; i++) {
  5306. cpumask_t nodemask = node_to_cpumask(i);
  5307. struct sched_group *oldsg, *sg = sched_group_nodes[i];
  5308. cpus_and(nodemask, nodemask, *cpu_map);
  5309. if (cpus_empty(nodemask))
  5310. continue;
  5311. if (sg == NULL)
  5312. continue;
  5313. sg = sg->next;
  5314. next_sg:
  5315. oldsg = sg;
  5316. sg = sg->next;
  5317. kfree(oldsg);
  5318. if (oldsg != sched_group_nodes[i])
  5319. goto next_sg;
  5320. }
  5321. kfree(sched_group_nodes);
  5322. sched_group_nodes_bycpu[cpu] = NULL;
  5323. }
  5324. #endif
  5325. for_each_cpu_mask(cpu, *cpu_map) {
  5326. if (sched_group_phys_bycpu[cpu]) {
  5327. kfree(sched_group_phys_bycpu[cpu]);
  5328. sched_group_phys_bycpu[cpu] = NULL;
  5329. }
  5330. #ifdef CONFIG_SCHED_MC
  5331. if (sched_group_core_bycpu[cpu]) {
  5332. kfree(sched_group_core_bycpu[cpu]);
  5333. sched_group_core_bycpu[cpu] = NULL;
  5334. }
  5335. #endif
  5336. }
  5337. }
  5338. /*
  5339. * Build sched domains for a given set of cpus and attach the sched domains
  5340. * to the individual cpus
  5341. */
  5342. static int build_sched_domains(const cpumask_t *cpu_map)
  5343. {
  5344. int i;
  5345. struct sched_group *sched_group_phys = NULL;
  5346. #ifdef CONFIG_SCHED_MC
  5347. struct sched_group *sched_group_core = NULL;
  5348. #endif
  5349. #ifdef CONFIG_NUMA
  5350. struct sched_group **sched_group_nodes = NULL;
  5351. struct sched_group *sched_group_allnodes = NULL;
  5352. /*
  5353. * Allocate the per-node list of sched groups
  5354. */
  5355. sched_group_nodes = kzalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
  5356. GFP_KERNEL);
  5357. if (!sched_group_nodes) {
  5358. printk(KERN_WARNING "Can not alloc sched group node list\n");
  5359. return -ENOMEM;
  5360. }
  5361. sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
  5362. #endif
  5363. /*
  5364. * Set up domains for cpus specified by the cpu_map.
  5365. */
  5366. for_each_cpu_mask(i, *cpu_map) {
  5367. int group;
  5368. struct sched_domain *sd = NULL, *p;
  5369. cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
  5370. cpus_and(nodemask, nodemask, *cpu_map);
  5371. #ifdef CONFIG_NUMA
  5372. if (cpus_weight(*cpu_map)
  5373. > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
  5374. if (!sched_group_allnodes) {
  5375. sched_group_allnodes
  5376. = kmalloc(sizeof(struct sched_group)
  5377. * MAX_NUMNODES,
  5378. GFP_KERNEL);
  5379. if (!sched_group_allnodes) {
  5380. printk(KERN_WARNING
  5381. "Can not alloc allnodes sched group\n");
  5382. goto error;
  5383. }
  5384. sched_group_allnodes_bycpu[i]
  5385. = sched_group_allnodes;
  5386. }
  5387. sd = &per_cpu(allnodes_domains, i);
  5388. *sd = SD_ALLNODES_INIT;
  5389. sd->span = *cpu_map;
  5390. group = cpu_to_allnodes_group(i);
  5391. sd->groups = &sched_group_allnodes[group];
  5392. p = sd;
  5393. } else
  5394. p = NULL;
  5395. sd = &per_cpu(node_domains, i);
  5396. *sd = SD_NODE_INIT;
  5397. sd->span = sched_domain_node_span(cpu_to_node(i));
  5398. sd->parent = p;
  5399. cpus_and(sd->span, sd->span, *cpu_map);
  5400. #endif
  5401. if (!sched_group_phys) {
  5402. sched_group_phys
  5403. = kmalloc(sizeof(struct sched_group) * NR_CPUS,
  5404. GFP_KERNEL);
  5405. if (!sched_group_phys) {
  5406. printk (KERN_WARNING "Can not alloc phys sched"
  5407. "group\n");
  5408. goto error;
  5409. }
  5410. sched_group_phys_bycpu[i] = sched_group_phys;
  5411. }
  5412. p = sd;
  5413. sd = &per_cpu(phys_domains, i);
  5414. group = cpu_to_phys_group(i);
  5415. *sd = SD_CPU_INIT;
  5416. sd->span = nodemask;
  5417. sd->parent = p;
  5418. sd->groups = &sched_group_phys[group];
  5419. #ifdef CONFIG_SCHED_MC
  5420. if (!sched_group_core) {
  5421. sched_group_core
  5422. = kmalloc(sizeof(struct sched_group) * NR_CPUS,
  5423. GFP_KERNEL);
  5424. if (!sched_group_core) {
  5425. printk (KERN_WARNING "Can not alloc core sched"
  5426. "group\n");
  5427. goto error;
  5428. }
  5429. sched_group_core_bycpu[i] = sched_group_core;
  5430. }
  5431. p = sd;
  5432. sd = &per_cpu(core_domains, i);
  5433. group = cpu_to_core_group(i);
  5434. *sd = SD_MC_INIT;
  5435. sd->span = cpu_coregroup_map(i);
  5436. cpus_and(sd->span, sd->span, *cpu_map);
  5437. sd->parent = p;
  5438. sd->groups = &sched_group_core[group];
  5439. #endif
  5440. #ifdef CONFIG_SCHED_SMT
  5441. p = sd;
  5442. sd = &per_cpu(cpu_domains, i);
  5443. group = cpu_to_cpu_group(i);
  5444. *sd = SD_SIBLING_INIT;
  5445. sd->span = cpu_sibling_map[i];
  5446. cpus_and(sd->span, sd->span, *cpu_map);
  5447. sd->parent = p;
  5448. sd->groups = &sched_group_cpus[group];
  5449. #endif
  5450. }
  5451. #ifdef CONFIG_SCHED_SMT
  5452. /* Set up CPU (sibling) groups */
  5453. for_each_cpu_mask(i, *cpu_map) {
  5454. cpumask_t this_sibling_map = cpu_sibling_map[i];
  5455. cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
  5456. if (i != first_cpu(this_sibling_map))
  5457. continue;
  5458. init_sched_build_groups(sched_group_cpus, this_sibling_map,
  5459. &cpu_to_cpu_group);
  5460. }
  5461. #endif
  5462. #ifdef CONFIG_SCHED_MC
  5463. /* Set up multi-core groups */
  5464. for_each_cpu_mask(i, *cpu_map) {
  5465. cpumask_t this_core_map = cpu_coregroup_map(i);
  5466. cpus_and(this_core_map, this_core_map, *cpu_map);
  5467. if (i != first_cpu(this_core_map))
  5468. continue;
  5469. init_sched_build_groups(sched_group_core, this_core_map,
  5470. &cpu_to_core_group);
  5471. }
  5472. #endif
  5473. /* Set up physical groups */
  5474. for (i = 0; i < MAX_NUMNODES; i++) {
  5475. cpumask_t nodemask = node_to_cpumask(i);
  5476. cpus_and(nodemask, nodemask, *cpu_map);
  5477. if (cpus_empty(nodemask))
  5478. continue;
  5479. init_sched_build_groups(sched_group_phys, nodemask,
  5480. &cpu_to_phys_group);
  5481. }
  5482. #ifdef CONFIG_NUMA
  5483. /* Set up node groups */
  5484. if (sched_group_allnodes)
  5485. init_sched_build_groups(sched_group_allnodes, *cpu_map,
  5486. &cpu_to_allnodes_group);
  5487. for (i = 0; i < MAX_NUMNODES; i++) {
  5488. /* Set up node groups */
  5489. struct sched_group *sg, *prev;
  5490. cpumask_t nodemask = node_to_cpumask(i);
  5491. cpumask_t domainspan;
  5492. cpumask_t covered = CPU_MASK_NONE;
  5493. int j;
  5494. cpus_and(nodemask, nodemask, *cpu_map);
  5495. if (cpus_empty(nodemask)) {
  5496. sched_group_nodes[i] = NULL;
  5497. continue;
  5498. }
  5499. domainspan = sched_domain_node_span(i);
  5500. cpus_and(domainspan, domainspan, *cpu_map);
  5501. sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
  5502. if (!sg) {
  5503. printk(KERN_WARNING "Can not alloc domain group for "
  5504. "node %d\n", i);
  5505. goto error;
  5506. }
  5507. sched_group_nodes[i] = sg;
  5508. for_each_cpu_mask(j, nodemask) {
  5509. struct sched_domain *sd;
  5510. sd = &per_cpu(node_domains, j);
  5511. sd->groups = sg;
  5512. }
  5513. sg->cpu_power = 0;
  5514. sg->cpumask = nodemask;
  5515. sg->next = sg;
  5516. cpus_or(covered, covered, nodemask);
  5517. prev = sg;
  5518. for (j = 0; j < MAX_NUMNODES; j++) {
  5519. cpumask_t tmp, notcovered;
  5520. int n = (i + j) % MAX_NUMNODES;
  5521. cpus_complement(notcovered, covered);
  5522. cpus_and(tmp, notcovered, *cpu_map);
  5523. cpus_and(tmp, tmp, domainspan);
  5524. if (cpus_empty(tmp))
  5525. break;
  5526. nodemask = node_to_cpumask(n);
  5527. cpus_and(tmp, tmp, nodemask);
  5528. if (cpus_empty(tmp))
  5529. continue;
  5530. sg = kmalloc_node(sizeof(struct sched_group),
  5531. GFP_KERNEL, i);
  5532. if (!sg) {
  5533. printk(KERN_WARNING
  5534. "Can not alloc domain group for node %d\n", j);
  5535. goto error;
  5536. }
  5537. sg->cpu_power = 0;
  5538. sg->cpumask = tmp;
  5539. sg->next = prev->next;
  5540. cpus_or(covered, covered, tmp);
  5541. prev->next = sg;
  5542. prev = sg;
  5543. }
  5544. }
  5545. #endif
  5546. /* Calculate CPU power for physical packages and nodes */
  5547. #ifdef CONFIG_SCHED_SMT
  5548. for_each_cpu_mask(i, *cpu_map) {
  5549. struct sched_domain *sd;
  5550. sd = &per_cpu(cpu_domains, i);
  5551. sd->groups->cpu_power = SCHED_LOAD_SCALE;
  5552. }
  5553. #endif
  5554. #ifdef CONFIG_SCHED_MC
  5555. for_each_cpu_mask(i, *cpu_map) {
  5556. int power;
  5557. struct sched_domain *sd;
  5558. sd = &per_cpu(core_domains, i);
  5559. if (sched_smt_power_savings)
  5560. power = SCHED_LOAD_SCALE * cpus_weight(sd->groups->cpumask);
  5561. else
  5562. power = SCHED_LOAD_SCALE + (cpus_weight(sd->groups->cpumask)-1)
  5563. * SCHED_LOAD_SCALE / 10;
  5564. sd->groups->cpu_power = power;
  5565. }
  5566. #endif
  5567. for_each_cpu_mask(i, *cpu_map) {
  5568. struct sched_domain *sd;
  5569. #ifdef CONFIG_SCHED_MC
  5570. sd = &per_cpu(phys_domains, i);
  5571. if (i != first_cpu(sd->groups->cpumask))
  5572. continue;
  5573. sd->groups->cpu_power = 0;
  5574. if (sched_mc_power_savings || sched_smt_power_savings) {
  5575. int j;
  5576. for_each_cpu_mask(j, sd->groups->cpumask) {
  5577. struct sched_domain *sd1;
  5578. sd1 = &per_cpu(core_domains, j);
  5579. /*
  5580. * for each core we will add once
  5581. * to the group in physical domain
  5582. */
  5583. if (j != first_cpu(sd1->groups->cpumask))
  5584. continue;
  5585. if (sched_smt_power_savings)
  5586. sd->groups->cpu_power += sd1->groups->cpu_power;
  5587. else
  5588. sd->groups->cpu_power += SCHED_LOAD_SCALE;
  5589. }
  5590. } else
  5591. /*
  5592. * This has to be < 2 * SCHED_LOAD_SCALE
  5593. * Lets keep it SCHED_LOAD_SCALE, so that
  5594. * while calculating NUMA group's cpu_power
  5595. * we can simply do
  5596. * numa_group->cpu_power += phys_group->cpu_power;
  5597. *
  5598. * See "only add power once for each physical pkg"
  5599. * comment below
  5600. */
  5601. sd->groups->cpu_power = SCHED_LOAD_SCALE;
  5602. #else
  5603. int power;
  5604. sd = &per_cpu(phys_domains, i);
  5605. if (sched_smt_power_savings)
  5606. power = SCHED_LOAD_SCALE * cpus_weight(sd->groups->cpumask);
  5607. else
  5608. power = SCHED_LOAD_SCALE;
  5609. sd->groups->cpu_power = power;
  5610. #endif
  5611. }
  5612. #ifdef CONFIG_NUMA
  5613. for (i = 0; i < MAX_NUMNODES; i++)
  5614. init_numa_sched_groups_power(sched_group_nodes[i]);
  5615. init_numa_sched_groups_power(sched_group_allnodes);
  5616. #endif
  5617. /* Attach the domains */
  5618. for_each_cpu_mask(i, *cpu_map) {
  5619. struct sched_domain *sd;
  5620. #ifdef CONFIG_SCHED_SMT
  5621. sd = &per_cpu(cpu_domains, i);
  5622. #elif defined(CONFIG_SCHED_MC)
  5623. sd = &per_cpu(core_domains, i);
  5624. #else
  5625. sd = &per_cpu(phys_domains, i);
  5626. #endif
  5627. cpu_attach_domain(sd, i);
  5628. }
  5629. /*
  5630. * Tune cache-hot values:
  5631. */
  5632. calibrate_migration_costs(cpu_map);
  5633. return 0;
  5634. error:
  5635. free_sched_groups(cpu_map);
  5636. return -ENOMEM;
  5637. }
  5638. /*
  5639. * Set up scheduler domains and groups. Callers must hold the hotplug lock.
  5640. */
  5641. static int arch_init_sched_domains(const cpumask_t *cpu_map)
  5642. {
  5643. cpumask_t cpu_default_map;
  5644. int err;
  5645. /*
  5646. * Setup mask for cpus without special case scheduling requirements.
  5647. * For now this just excludes isolated cpus, but could be used to
  5648. * exclude other special cases in the future.
  5649. */
  5650. cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
  5651. err = build_sched_domains(&cpu_default_map);
  5652. return err;
  5653. }
  5654. static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
  5655. {
  5656. free_sched_groups(cpu_map);
  5657. }
  5658. /*
  5659. * Detach sched domains from a group of cpus specified in cpu_map
  5660. * These cpus will now be attached to the NULL domain
  5661. */
  5662. static void detach_destroy_domains(const cpumask_t *cpu_map)
  5663. {
  5664. int i;
  5665. for_each_cpu_mask(i, *cpu_map)
  5666. cpu_attach_domain(NULL, i);
  5667. synchronize_sched();
  5668. arch_destroy_sched_domains(cpu_map);
  5669. }
  5670. /*
  5671. * Partition sched domains as specified by the cpumasks below.
  5672. * This attaches all cpus from the cpumasks to the NULL domain,
  5673. * waits for a RCU quiescent period, recalculates sched
  5674. * domain information and then attaches them back to the
  5675. * correct sched domains
  5676. * Call with hotplug lock held
  5677. */
  5678. int partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
  5679. {
  5680. cpumask_t change_map;
  5681. int err = 0;
  5682. cpus_and(*partition1, *partition1, cpu_online_map);
  5683. cpus_and(*partition2, *partition2, cpu_online_map);
  5684. cpus_or(change_map, *partition1, *partition2);
  5685. /* Detach sched domains from all of the affected cpus */
  5686. detach_destroy_domains(&change_map);
  5687. if (!cpus_empty(*partition1))
  5688. err = build_sched_domains(partition1);
  5689. if (!err && !cpus_empty(*partition2))
  5690. err = build_sched_domains(partition2);
  5691. return err;
  5692. }
  5693. #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
  5694. int arch_reinit_sched_domains(void)
  5695. {
  5696. int err;
  5697. lock_cpu_hotplug();
  5698. detach_destroy_domains(&cpu_online_map);
  5699. err = arch_init_sched_domains(&cpu_online_map);
  5700. unlock_cpu_hotplug();
  5701. return err;
  5702. }
  5703. static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
  5704. {
  5705. int ret;
  5706. if (buf[0] != '0' && buf[0] != '1')
  5707. return -EINVAL;
  5708. if (smt)
  5709. sched_smt_power_savings = (buf[0] == '1');
  5710. else
  5711. sched_mc_power_savings = (buf[0] == '1');
  5712. ret = arch_reinit_sched_domains();
  5713. return ret ? ret : count;
  5714. }
  5715. int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
  5716. {
  5717. int err = 0;
  5718. #ifdef CONFIG_SCHED_SMT
  5719. if (smt_capable())
  5720. err = sysfs_create_file(&cls->kset.kobj,
  5721. &attr_sched_smt_power_savings.attr);
  5722. #endif
  5723. #ifdef CONFIG_SCHED_MC
  5724. if (!err && mc_capable())
  5725. err = sysfs_create_file(&cls->kset.kobj,
  5726. &attr_sched_mc_power_savings.attr);
  5727. #endif
  5728. return err;
  5729. }
  5730. #endif
  5731. #ifdef CONFIG_SCHED_MC
  5732. static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
  5733. {
  5734. return sprintf(page, "%u\n", sched_mc_power_savings);
  5735. }
  5736. static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
  5737. const char *buf, size_t count)
  5738. {
  5739. return sched_power_savings_store(buf, count, 0);
  5740. }
  5741. SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
  5742. sched_mc_power_savings_store);
  5743. #endif
  5744. #ifdef CONFIG_SCHED_SMT
  5745. static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
  5746. {
  5747. return sprintf(page, "%u\n", sched_smt_power_savings);
  5748. }
  5749. static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
  5750. const char *buf, size_t count)
  5751. {
  5752. return sched_power_savings_store(buf, count, 1);
  5753. }
  5754. SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
  5755. sched_smt_power_savings_store);
  5756. #endif
  5757. #ifdef CONFIG_HOTPLUG_CPU
  5758. /*
  5759. * Force a reinitialization of the sched domains hierarchy. The domains
  5760. * and groups cannot be updated in place without racing with the balancing
  5761. * code, so we temporarily attach all running cpus to the NULL domain
  5762. * which will prevent rebalancing while the sched domains are recalculated.
  5763. */
  5764. static int update_sched_domains(struct notifier_block *nfb,
  5765. unsigned long action, void *hcpu)
  5766. {
  5767. switch (action) {
  5768. case CPU_UP_PREPARE:
  5769. case CPU_DOWN_PREPARE:
  5770. detach_destroy_domains(&cpu_online_map);
  5771. return NOTIFY_OK;
  5772. case CPU_UP_CANCELED:
  5773. case CPU_DOWN_FAILED:
  5774. case CPU_ONLINE:
  5775. case CPU_DEAD:
  5776. /*
  5777. * Fall through and re-initialise the domains.
  5778. */
  5779. break;
  5780. default:
  5781. return NOTIFY_DONE;
  5782. }
  5783. /* The hotplug lock is already held by cpu_up/cpu_down */
  5784. arch_init_sched_domains(&cpu_online_map);
  5785. return NOTIFY_OK;
  5786. }
  5787. #endif
  5788. void __init sched_init_smp(void)
  5789. {
  5790. lock_cpu_hotplug();
  5791. arch_init_sched_domains(&cpu_online_map);
  5792. unlock_cpu_hotplug();
  5793. /* XXX: Theoretical race here - CPU may be hotplugged now */
  5794. hotcpu_notifier(update_sched_domains, 0);
  5795. }
  5796. #else
  5797. void __init sched_init_smp(void)
  5798. {
  5799. }
  5800. #endif /* CONFIG_SMP */
  5801. int in_sched_functions(unsigned long addr)
  5802. {
  5803. /* Linker adds these: start and end of __sched functions */
  5804. extern char __sched_text_start[], __sched_text_end[];
  5805. return in_lock_functions(addr) ||
  5806. (addr >= (unsigned long)__sched_text_start
  5807. && addr < (unsigned long)__sched_text_end);
  5808. }
  5809. void __init sched_init(void)
  5810. {
  5811. int i, j, k;
  5812. for_each_possible_cpu(i) {
  5813. struct prio_array *array;
  5814. struct rq *rq;
  5815. rq = cpu_rq(i);
  5816. spin_lock_init(&rq->lock);
  5817. lockdep_set_class(&rq->lock, &rq->rq_lock_key);
  5818. rq->nr_running = 0;
  5819. rq->active = rq->arrays;
  5820. rq->expired = rq->arrays + 1;
  5821. rq->best_expired_prio = MAX_PRIO;
  5822. #ifdef CONFIG_SMP
  5823. rq->sd = NULL;
  5824. for (j = 1; j < 3; j++)
  5825. rq->cpu_load[j] = 0;
  5826. rq->active_balance = 0;
  5827. rq->push_cpu = 0;
  5828. rq->migration_thread = NULL;
  5829. INIT_LIST_HEAD(&rq->migration_queue);
  5830. #endif
  5831. atomic_set(&rq->nr_iowait, 0);
  5832. for (j = 0; j < 2; j++) {
  5833. array = rq->arrays + j;
  5834. for (k = 0; k < MAX_PRIO; k++) {
  5835. INIT_LIST_HEAD(array->queue + k);
  5836. __clear_bit(k, array->bitmap);
  5837. }
  5838. // delimiter for bitsearch
  5839. __set_bit(MAX_PRIO, array->bitmap);
  5840. }
  5841. }
  5842. set_load_weight(&init_task);
  5843. /*
  5844. * The boot idle thread does lazy MMU switching as well:
  5845. */
  5846. atomic_inc(&init_mm.mm_count);
  5847. enter_lazy_tlb(&init_mm, current);
  5848. /*
  5849. * Make us the idle thread. Technically, schedule() should not be
  5850. * called from this thread, however somewhere below it might be,
  5851. * but because we are the idle thread, we just pick up running again
  5852. * when this runqueue becomes "idle".
  5853. */
  5854. init_idle(current, smp_processor_id());
  5855. }
  5856. #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
  5857. void __might_sleep(char *file, int line)
  5858. {
  5859. #ifdef in_atomic
  5860. static unsigned long prev_jiffy; /* ratelimiting */
  5861. if ((in_atomic() || irqs_disabled()) &&
  5862. system_state == SYSTEM_RUNNING && !oops_in_progress) {
  5863. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  5864. return;
  5865. prev_jiffy = jiffies;
  5866. printk(KERN_ERR "BUG: sleeping function called from invalid"
  5867. " context at %s:%d\n", file, line);
  5868. printk("in_atomic():%d, irqs_disabled():%d\n",
  5869. in_atomic(), irqs_disabled());
  5870. dump_stack();
  5871. }
  5872. #endif
  5873. }
  5874. EXPORT_SYMBOL(__might_sleep);
  5875. #endif
  5876. #ifdef CONFIG_MAGIC_SYSRQ
  5877. void normalize_rt_tasks(void)
  5878. {
  5879. struct prio_array *array;
  5880. struct task_struct *p;
  5881. unsigned long flags;
  5882. struct rq *rq;
  5883. read_lock_irq(&tasklist_lock);
  5884. for_each_process(p) {
  5885. if (!rt_task(p))
  5886. continue;
  5887. spin_lock_irqsave(&p->pi_lock, flags);
  5888. rq = __task_rq_lock(p);
  5889. array = p->array;
  5890. if (array)
  5891. deactivate_task(p, task_rq(p));
  5892. __setscheduler(p, SCHED_NORMAL, 0);
  5893. if (array) {
  5894. __activate_task(p, task_rq(p));
  5895. resched_task(rq->curr);
  5896. }
  5897. __task_rq_unlock(rq);
  5898. spin_unlock_irqrestore(&p->pi_lock, flags);
  5899. }
  5900. read_unlock_irq(&tasklist_lock);
  5901. }
  5902. #endif /* CONFIG_MAGIC_SYSRQ */
  5903. #ifdef CONFIG_IA64
  5904. /*
  5905. * These functions are only useful for the IA64 MCA handling.
  5906. *
  5907. * They can only be called when the whole system has been
  5908. * stopped - every CPU needs to be quiescent, and no scheduling
  5909. * activity can take place. Using them for anything else would
  5910. * be a serious bug, and as a result, they aren't even visible
  5911. * under any other configuration.
  5912. */
  5913. /**
  5914. * curr_task - return the current task for a given cpu.
  5915. * @cpu: the processor in question.
  5916. *
  5917. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  5918. */
  5919. struct task_struct *curr_task(int cpu)
  5920. {
  5921. return cpu_curr(cpu);
  5922. }
  5923. /**
  5924. * set_curr_task - set the current task for a given cpu.
  5925. * @cpu: the processor in question.
  5926. * @p: the task pointer to set.
  5927. *
  5928. * Description: This function must only be used when non-maskable interrupts
  5929. * are serviced on a separate stack. It allows the architecture to switch the
  5930. * notion of the current task on a cpu in a non-blocking manner. This function
  5931. * must be called with all CPU's synchronized, and interrupts disabled, the
  5932. * and caller must save the original value of the current task (see
  5933. * curr_task() above) and restore that value before reenabling interrupts and
  5934. * re-starting the system.
  5935. *
  5936. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  5937. */
  5938. void set_curr_task(int cpu, struct task_struct *p)
  5939. {
  5940. cpu_curr(cpu) = p;
  5941. }
  5942. #endif