core.c 213 KB

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