core.c 195 KB

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