sched.c 177 KB

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