sched.c 164 KB

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