core.c 211 KB

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