sched.c 154 KB

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