core.c 214 KB

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