core.c 217 KB

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