core.c 212 KB

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