core.c 208 KB

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