core.c 196 KB

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