printk.c 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * linux/kernel/printk.c
  4. *
  5. * Copyright (C) 1991, 1992 Linus Torvalds
  6. *
  7. * Modified to make sys_syslog() more flexible: added commands to
  8. * return the last 4k of kernel messages, regardless of whether
  9. * they've been read or not. Added option to suppress kernel printk's
  10. * to the console. Added hook for sending the console messages
  11. * elsewhere, in preparation for a serial line console (someday).
  12. * Ted Ts'o, 2/11/93.
  13. * Modified for sysctl support, 1/8/97, Chris Horn.
  14. * Fixed SMP synchronization, 08/08/99, Manfred Spraul
  15. * manfred@colorfullife.com
  16. * Rewrote bits to get rid of console_lock
  17. * 01Mar01 Andrew Morton
  18. */
  19. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  20. #include <linux/kernel.h>
  21. #include <linux/mm.h>
  22. #include <linux/tty.h>
  23. #include <linux/tty_driver.h>
  24. #include <linux/console.h>
  25. #include <linux/init.h>
  26. #include <linux/jiffies.h>
  27. #include <linux/nmi.h>
  28. #include <linux/module.h>
  29. #include <linux/moduleparam.h>
  30. #include <linux/delay.h>
  31. #include <linux/smp.h>
  32. #include <linux/security.h>
  33. #include <linux/memblock.h>
  34. #include <linux/syscalls.h>
  35. #include <linux/syscore_ops.h>
  36. #include <linux/vmcore_info.h>
  37. #include <linux/ratelimit.h>
  38. #include <linux/kmsg_dump.h>
  39. #include <linux/syslog.h>
  40. #include <linux/cpu.h>
  41. #include <linux/rculist.h>
  42. #include <linux/poll.h>
  43. #include <linux/irq_work.h>
  44. #include <linux/ctype.h>
  45. #include <linux/uio.h>
  46. #include <linux/sched/clock.h>
  47. #include <linux/sched/debug.h>
  48. #include <linux/sched/task_stack.h>
  49. #include <linux/uaccess.h>
  50. #include <asm/sections.h>
  51. #include <trace/events/initcall.h>
  52. #define CREATE_TRACE_POINTS
  53. #include <trace/events/printk.h>
  54. #include "printk_ringbuffer.h"
  55. #include "console_cmdline.h"
  56. #include "braille.h"
  57. #include "internal.h"
  58. int console_printk[4] = {
  59. CONSOLE_LOGLEVEL_DEFAULT, /* console_loglevel */
  60. MESSAGE_LOGLEVEL_DEFAULT, /* default_message_loglevel */
  61. CONSOLE_LOGLEVEL_MIN, /* minimum_console_loglevel */
  62. CONSOLE_LOGLEVEL_DEFAULT, /* default_console_loglevel */
  63. };
  64. EXPORT_SYMBOL_GPL(console_printk);
  65. atomic_t ignore_console_lock_warning __read_mostly = ATOMIC_INIT(0);
  66. EXPORT_SYMBOL(ignore_console_lock_warning);
  67. EXPORT_TRACEPOINT_SYMBOL_GPL(console);
  68. /*
  69. * Low level drivers may need that to know if they can schedule in
  70. * their unblank() callback or not. So let's export it.
  71. */
  72. int oops_in_progress;
  73. EXPORT_SYMBOL(oops_in_progress);
  74. /*
  75. * console_mutex protects console_list updates and console->flags updates.
  76. * The flags are synchronized only for consoles that are registered, i.e.
  77. * accessible via the console list.
  78. */
  79. static DEFINE_MUTEX(console_mutex);
  80. /*
  81. * console_sem protects updates to console->seq
  82. * and also provides serialization for console printing.
  83. */
  84. static DEFINE_SEMAPHORE(console_sem, 1);
  85. HLIST_HEAD(console_list);
  86. EXPORT_SYMBOL_GPL(console_list);
  87. DEFINE_STATIC_SRCU(console_srcu);
  88. /*
  89. * System may need to suppress printk message under certain
  90. * circumstances, like after kernel panic happens.
  91. */
  92. int __read_mostly suppress_printk;
  93. #ifdef CONFIG_LOCKDEP
  94. static struct lockdep_map console_lock_dep_map = {
  95. .name = "console_lock"
  96. };
  97. void lockdep_assert_console_list_lock_held(void)
  98. {
  99. lockdep_assert_held(&console_mutex);
  100. }
  101. EXPORT_SYMBOL(lockdep_assert_console_list_lock_held);
  102. #endif
  103. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  104. bool console_srcu_read_lock_is_held(void)
  105. {
  106. return srcu_read_lock_held(&console_srcu);
  107. }
  108. EXPORT_SYMBOL(console_srcu_read_lock_is_held);
  109. #endif
  110. enum devkmsg_log_bits {
  111. __DEVKMSG_LOG_BIT_ON = 0,
  112. __DEVKMSG_LOG_BIT_OFF,
  113. __DEVKMSG_LOG_BIT_LOCK,
  114. };
  115. enum devkmsg_log_masks {
  116. DEVKMSG_LOG_MASK_ON = BIT(__DEVKMSG_LOG_BIT_ON),
  117. DEVKMSG_LOG_MASK_OFF = BIT(__DEVKMSG_LOG_BIT_OFF),
  118. DEVKMSG_LOG_MASK_LOCK = BIT(__DEVKMSG_LOG_BIT_LOCK),
  119. };
  120. /* Keep both the 'on' and 'off' bits clear, i.e. ratelimit by default: */
  121. #define DEVKMSG_LOG_MASK_DEFAULT 0
  122. static unsigned int __read_mostly devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
  123. static int __control_devkmsg(char *str)
  124. {
  125. size_t len;
  126. if (!str)
  127. return -EINVAL;
  128. len = str_has_prefix(str, "on");
  129. if (len) {
  130. devkmsg_log = DEVKMSG_LOG_MASK_ON;
  131. return len;
  132. }
  133. len = str_has_prefix(str, "off");
  134. if (len) {
  135. devkmsg_log = DEVKMSG_LOG_MASK_OFF;
  136. return len;
  137. }
  138. len = str_has_prefix(str, "ratelimit");
  139. if (len) {
  140. devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
  141. return len;
  142. }
  143. return -EINVAL;
  144. }
  145. static int __init control_devkmsg(char *str)
  146. {
  147. if (__control_devkmsg(str) < 0) {
  148. pr_warn("printk.devkmsg: bad option string '%s'\n", str);
  149. return 1;
  150. }
  151. /*
  152. * Set sysctl string accordingly:
  153. */
  154. if (devkmsg_log == DEVKMSG_LOG_MASK_ON)
  155. strscpy(devkmsg_log_str, "on");
  156. else if (devkmsg_log == DEVKMSG_LOG_MASK_OFF)
  157. strscpy(devkmsg_log_str, "off");
  158. /* else "ratelimit" which is set by default. */
  159. /*
  160. * Sysctl cannot change it anymore. The kernel command line setting of
  161. * this parameter is to force the setting to be permanent throughout the
  162. * runtime of the system. This is a precation measure against userspace
  163. * trying to be a smarta** and attempting to change it up on us.
  164. */
  165. devkmsg_log |= DEVKMSG_LOG_MASK_LOCK;
  166. return 1;
  167. }
  168. __setup("printk.devkmsg=", control_devkmsg);
  169. char devkmsg_log_str[DEVKMSG_STR_MAX_SIZE] = "ratelimit";
  170. #if defined(CONFIG_PRINTK) && defined(CONFIG_SYSCTL)
  171. int devkmsg_sysctl_set_loglvl(const struct ctl_table *table, int write,
  172. void *buffer, size_t *lenp, loff_t *ppos)
  173. {
  174. char old_str[DEVKMSG_STR_MAX_SIZE];
  175. unsigned int old;
  176. int err;
  177. if (write) {
  178. if (devkmsg_log & DEVKMSG_LOG_MASK_LOCK)
  179. return -EINVAL;
  180. old = devkmsg_log;
  181. strscpy(old_str, devkmsg_log_str);
  182. }
  183. err = proc_dostring(table, write, buffer, lenp, ppos);
  184. if (err)
  185. return err;
  186. if (write) {
  187. err = __control_devkmsg(devkmsg_log_str);
  188. /*
  189. * Do not accept an unknown string OR a known string with
  190. * trailing crap...
  191. */
  192. if (err < 0 || (err + 1 != *lenp)) {
  193. /* ... and restore old setting. */
  194. devkmsg_log = old;
  195. strscpy(devkmsg_log_str, old_str);
  196. return -EINVAL;
  197. }
  198. }
  199. return 0;
  200. }
  201. #endif /* CONFIG_PRINTK && CONFIG_SYSCTL */
  202. /**
  203. * console_list_lock - Lock the console list
  204. *
  205. * For console list or console->flags updates
  206. */
  207. void console_list_lock(void)
  208. {
  209. /*
  210. * In unregister_console() and console_force_preferred_locked(),
  211. * synchronize_srcu() is called with the console_list_lock held.
  212. * Therefore it is not allowed that the console_list_lock is taken
  213. * with the srcu_lock held.
  214. *
  215. * Detecting if this context is really in the read-side critical
  216. * section is only possible if the appropriate debug options are
  217. * enabled.
  218. */
  219. WARN_ON_ONCE(debug_lockdep_rcu_enabled() &&
  220. srcu_read_lock_held(&console_srcu));
  221. mutex_lock(&console_mutex);
  222. }
  223. EXPORT_SYMBOL(console_list_lock);
  224. /**
  225. * console_list_unlock - Unlock the console list
  226. *
  227. * Counterpart to console_list_lock()
  228. */
  229. void console_list_unlock(void)
  230. {
  231. mutex_unlock(&console_mutex);
  232. }
  233. EXPORT_SYMBOL(console_list_unlock);
  234. /**
  235. * console_srcu_read_lock - Register a new reader for the
  236. * SRCU-protected console list
  237. *
  238. * Use for_each_console_srcu() to iterate the console list
  239. *
  240. * Context: Any context.
  241. * Return: A cookie to pass to console_srcu_read_unlock().
  242. */
  243. int console_srcu_read_lock(void)
  244. __acquires(&console_srcu)
  245. {
  246. return srcu_read_lock_nmisafe(&console_srcu);
  247. }
  248. EXPORT_SYMBOL(console_srcu_read_lock);
  249. /**
  250. * console_srcu_read_unlock - Unregister an old reader from
  251. * the SRCU-protected console list
  252. * @cookie: cookie returned from console_srcu_read_lock()
  253. *
  254. * Counterpart to console_srcu_read_lock()
  255. */
  256. void console_srcu_read_unlock(int cookie)
  257. __releases(&console_srcu)
  258. {
  259. srcu_read_unlock_nmisafe(&console_srcu, cookie);
  260. }
  261. EXPORT_SYMBOL(console_srcu_read_unlock);
  262. /*
  263. * Helper macros to handle lockdep when locking/unlocking console_sem. We use
  264. * macros instead of functions so that _RET_IP_ contains useful information.
  265. */
  266. #define down_console_sem() do { \
  267. down(&console_sem);\
  268. mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
  269. } while (0)
  270. static int __down_trylock_console_sem(unsigned long ip)
  271. {
  272. int lock_failed;
  273. unsigned long flags;
  274. /*
  275. * Here and in __up_console_sem() we need to be in safe mode,
  276. * because spindump/WARN/etc from under console ->lock will
  277. * deadlock in printk()->down_trylock_console_sem() otherwise.
  278. */
  279. printk_safe_enter_irqsave(flags);
  280. lock_failed = down_trylock(&console_sem);
  281. printk_safe_exit_irqrestore(flags);
  282. if (lock_failed)
  283. return 1;
  284. mutex_acquire(&console_lock_dep_map, 0, 1, ip);
  285. return 0;
  286. }
  287. #define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
  288. static void __up_console_sem(unsigned long ip)
  289. {
  290. unsigned long flags;
  291. mutex_release(&console_lock_dep_map, ip);
  292. printk_safe_enter_irqsave(flags);
  293. up(&console_sem);
  294. printk_safe_exit_irqrestore(flags);
  295. }
  296. #define up_console_sem() __up_console_sem(_RET_IP_)
  297. static bool panic_in_progress(void)
  298. {
  299. return unlikely(atomic_read(&panic_cpu) != PANIC_CPU_INVALID);
  300. }
  301. /* Return true if a panic is in progress on the current CPU. */
  302. bool this_cpu_in_panic(void)
  303. {
  304. /*
  305. * We can use raw_smp_processor_id() here because it is impossible for
  306. * the task to be migrated to the panic_cpu, or away from it. If
  307. * panic_cpu has already been set, and we're not currently executing on
  308. * that CPU, then we never will be.
  309. */
  310. return unlikely(atomic_read(&panic_cpu) == raw_smp_processor_id());
  311. }
  312. /*
  313. * Return true if a panic is in progress on a remote CPU.
  314. *
  315. * On true, the local CPU should immediately release any printing resources
  316. * that may be needed by the panic CPU.
  317. */
  318. bool other_cpu_in_panic(void)
  319. {
  320. return (panic_in_progress() && !this_cpu_in_panic());
  321. }
  322. /*
  323. * This is used for debugging the mess that is the VT code by
  324. * keeping track if we have the console semaphore held. It's
  325. * definitely not the perfect debug tool (we don't know if _WE_
  326. * hold it and are racing, but it helps tracking those weird code
  327. * paths in the console code where we end up in places I want
  328. * locked without the console semaphore held).
  329. */
  330. static int console_locked;
  331. /*
  332. * Array of consoles built from command line options (console=)
  333. */
  334. #define MAX_CMDLINECONSOLES 8
  335. static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
  336. static int preferred_console = -1;
  337. int console_set_on_cmdline;
  338. EXPORT_SYMBOL(console_set_on_cmdline);
  339. /* Flag: console code may call schedule() */
  340. static int console_may_schedule;
  341. enum con_msg_format_flags {
  342. MSG_FORMAT_DEFAULT = 0,
  343. MSG_FORMAT_SYSLOG = (1 << 0),
  344. };
  345. static int console_msg_format = MSG_FORMAT_DEFAULT;
  346. /*
  347. * The printk log buffer consists of a sequenced collection of records, each
  348. * containing variable length message text. Every record also contains its
  349. * own meta-data (@info).
  350. *
  351. * Every record meta-data carries the timestamp in microseconds, as well as
  352. * the standard userspace syslog level and syslog facility. The usual kernel
  353. * messages use LOG_KERN; userspace-injected messages always carry a matching
  354. * syslog facility, by default LOG_USER. The origin of every message can be
  355. * reliably determined that way.
  356. *
  357. * The human readable log message of a record is available in @text, the
  358. * length of the message text in @text_len. The stored message is not
  359. * terminated.
  360. *
  361. * Optionally, a record can carry a dictionary of properties (key/value
  362. * pairs), to provide userspace with a machine-readable message context.
  363. *
  364. * Examples for well-defined, commonly used property names are:
  365. * DEVICE=b12:8 device identifier
  366. * b12:8 block dev_t
  367. * c127:3 char dev_t
  368. * n8 netdev ifindex
  369. * +sound:card0 subsystem:devname
  370. * SUBSYSTEM=pci driver-core subsystem name
  371. *
  372. * Valid characters in property names are [a-zA-Z0-9.-_]. Property names
  373. * and values are terminated by a '\0' character.
  374. *
  375. * Example of record values:
  376. * record.text_buf = "it's a line" (unterminated)
  377. * record.info.seq = 56
  378. * record.info.ts_nsec = 36863
  379. * record.info.text_len = 11
  380. * record.info.facility = 0 (LOG_KERN)
  381. * record.info.flags = 0
  382. * record.info.level = 3 (LOG_ERR)
  383. * record.info.caller_id = 299 (task 299)
  384. * record.info.dev_info.subsystem = "pci" (terminated)
  385. * record.info.dev_info.device = "+pci:0000:00:01.0" (terminated)
  386. *
  387. * The 'struct printk_info' buffer must never be directly exported to
  388. * userspace, it is a kernel-private implementation detail that might
  389. * need to be changed in the future, when the requirements change.
  390. *
  391. * /dev/kmsg exports the structured data in the following line format:
  392. * "<level>,<sequnum>,<timestamp>,<contflag>[,additional_values, ... ];<message text>\n"
  393. *
  394. * Users of the export format should ignore possible additional values
  395. * separated by ',', and find the message after the ';' character.
  396. *
  397. * The optional key/value pairs are attached as continuation lines starting
  398. * with a space character and terminated by a newline. All possible
  399. * non-prinatable characters are escaped in the "\xff" notation.
  400. */
  401. /* syslog_lock protects syslog_* variables and write access to clear_seq. */
  402. static DEFINE_MUTEX(syslog_lock);
  403. /*
  404. * Specifies if a legacy console is registered. If legacy consoles are
  405. * present, it is necessary to perform the console lock/unlock dance
  406. * whenever console flushing should occur.
  407. */
  408. bool have_legacy_console;
  409. /*
  410. * Specifies if an nbcon console is registered. If nbcon consoles are present,
  411. * synchronous printing of legacy consoles will not occur during panic until
  412. * the backtrace has been stored to the ringbuffer.
  413. */
  414. bool have_nbcon_console;
  415. /*
  416. * Specifies if a boot console is registered. If boot consoles are present,
  417. * nbcon consoles cannot print simultaneously and must be synchronized by
  418. * the console lock. This is because boot consoles and nbcon consoles may
  419. * have mapped the same hardware.
  420. */
  421. bool have_boot_console;
  422. /* See printk_legacy_allow_panic_sync() for details. */
  423. bool legacy_allow_panic_sync;
  424. #ifdef CONFIG_PRINTK
  425. DECLARE_WAIT_QUEUE_HEAD(log_wait);
  426. static DECLARE_WAIT_QUEUE_HEAD(legacy_wait);
  427. /* All 3 protected by @syslog_lock. */
  428. /* the next printk record to read by syslog(READ) or /proc/kmsg */
  429. static u64 syslog_seq;
  430. static size_t syslog_partial;
  431. static bool syslog_time;
  432. /* True when _all_ printer threads are available for printing. */
  433. bool printk_kthreads_running;
  434. struct latched_seq {
  435. seqcount_latch_t latch;
  436. u64 val[2];
  437. };
  438. /*
  439. * The next printk record to read after the last 'clear' command. There are
  440. * two copies (updated with seqcount_latch) so that reads can locklessly
  441. * access a valid value. Writers are synchronized by @syslog_lock.
  442. */
  443. static struct latched_seq clear_seq = {
  444. .latch = SEQCNT_LATCH_ZERO(clear_seq.latch),
  445. .val[0] = 0,
  446. .val[1] = 0,
  447. };
  448. #define LOG_LEVEL(v) ((v) & 0x07)
  449. #define LOG_FACILITY(v) ((v) >> 3 & 0xff)
  450. /* record buffer */
  451. #define LOG_ALIGN __alignof__(unsigned long)
  452. #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
  453. #define LOG_BUF_LEN_MAX ((u32)1 << 31)
  454. static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
  455. static char *log_buf = __log_buf;
  456. static u32 log_buf_len = __LOG_BUF_LEN;
  457. /*
  458. * Define the average message size. This only affects the number of
  459. * descriptors that will be available. Underestimating is better than
  460. * overestimating (too many available descriptors is better than not enough).
  461. */
  462. #define PRB_AVGBITS 5 /* 32 character average length */
  463. #if CONFIG_LOG_BUF_SHIFT <= PRB_AVGBITS
  464. #error CONFIG_LOG_BUF_SHIFT value too small.
  465. #endif
  466. _DEFINE_PRINTKRB(printk_rb_static, CONFIG_LOG_BUF_SHIFT - PRB_AVGBITS,
  467. PRB_AVGBITS, &__log_buf[0]);
  468. static struct printk_ringbuffer printk_rb_dynamic;
  469. struct printk_ringbuffer *prb = &printk_rb_static;
  470. /*
  471. * We cannot access per-CPU data (e.g. per-CPU flush irq_work) before
  472. * per_cpu_areas are initialised. This variable is set to true when
  473. * it's safe to access per-CPU data.
  474. */
  475. static bool __printk_percpu_data_ready __ro_after_init;
  476. bool printk_percpu_data_ready(void)
  477. {
  478. return __printk_percpu_data_ready;
  479. }
  480. /* Must be called under syslog_lock. */
  481. static void latched_seq_write(struct latched_seq *ls, u64 val)
  482. {
  483. raw_write_seqcount_latch(&ls->latch);
  484. ls->val[0] = val;
  485. raw_write_seqcount_latch(&ls->latch);
  486. ls->val[1] = val;
  487. }
  488. /* Can be called from any context. */
  489. static u64 latched_seq_read_nolock(struct latched_seq *ls)
  490. {
  491. unsigned int seq;
  492. unsigned int idx;
  493. u64 val;
  494. do {
  495. seq = raw_read_seqcount_latch(&ls->latch);
  496. idx = seq & 0x1;
  497. val = ls->val[idx];
  498. } while (raw_read_seqcount_latch_retry(&ls->latch, seq));
  499. return val;
  500. }
  501. /* Return log buffer address */
  502. char *log_buf_addr_get(void)
  503. {
  504. return log_buf;
  505. }
  506. /* Return log buffer size */
  507. u32 log_buf_len_get(void)
  508. {
  509. return log_buf_len;
  510. }
  511. /*
  512. * Define how much of the log buffer we could take at maximum. The value
  513. * must be greater than two. Note that only half of the buffer is available
  514. * when the index points to the middle.
  515. */
  516. #define MAX_LOG_TAKE_PART 4
  517. static const char trunc_msg[] = "<truncated>";
  518. static void truncate_msg(u16 *text_len, u16 *trunc_msg_len)
  519. {
  520. /*
  521. * The message should not take the whole buffer. Otherwise, it might
  522. * get removed too soon.
  523. */
  524. u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
  525. if (*text_len > max_text_len)
  526. *text_len = max_text_len;
  527. /* enable the warning message (if there is room) */
  528. *trunc_msg_len = strlen(trunc_msg);
  529. if (*text_len >= *trunc_msg_len)
  530. *text_len -= *trunc_msg_len;
  531. else
  532. *trunc_msg_len = 0;
  533. }
  534. int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
  535. static int syslog_action_restricted(int type)
  536. {
  537. if (dmesg_restrict)
  538. return 1;
  539. /*
  540. * Unless restricted, we allow "read all" and "get buffer size"
  541. * for everybody.
  542. */
  543. return type != SYSLOG_ACTION_READ_ALL &&
  544. type != SYSLOG_ACTION_SIZE_BUFFER;
  545. }
  546. static int check_syslog_permissions(int type, int source)
  547. {
  548. /*
  549. * If this is from /proc/kmsg and we've already opened it, then we've
  550. * already done the capabilities checks at open time.
  551. */
  552. if (source == SYSLOG_FROM_PROC && type != SYSLOG_ACTION_OPEN)
  553. goto ok;
  554. if (syslog_action_restricted(type)) {
  555. if (capable(CAP_SYSLOG))
  556. goto ok;
  557. return -EPERM;
  558. }
  559. ok:
  560. return security_syslog(type);
  561. }
  562. static void append_char(char **pp, char *e, char c)
  563. {
  564. if (*pp < e)
  565. *(*pp)++ = c;
  566. }
  567. static ssize_t info_print_ext_header(char *buf, size_t size,
  568. struct printk_info *info)
  569. {
  570. u64 ts_usec = info->ts_nsec;
  571. char caller[20];
  572. #ifdef CONFIG_PRINTK_CALLER
  573. u32 id = info->caller_id;
  574. snprintf(caller, sizeof(caller), ",caller=%c%u",
  575. id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
  576. #else
  577. caller[0] = '\0';
  578. #endif
  579. do_div(ts_usec, 1000);
  580. return scnprintf(buf, size, "%u,%llu,%llu,%c%s;",
  581. (info->facility << 3) | info->level, info->seq,
  582. ts_usec, info->flags & LOG_CONT ? 'c' : '-', caller);
  583. }
  584. static ssize_t msg_add_ext_text(char *buf, size_t size,
  585. const char *text, size_t text_len,
  586. unsigned char endc)
  587. {
  588. char *p = buf, *e = buf + size;
  589. size_t i;
  590. /* escape non-printable characters */
  591. for (i = 0; i < text_len; i++) {
  592. unsigned char c = text[i];
  593. if (c < ' ' || c >= 127 || c == '\\')
  594. p += scnprintf(p, e - p, "\\x%02x", c);
  595. else
  596. append_char(&p, e, c);
  597. }
  598. append_char(&p, e, endc);
  599. return p - buf;
  600. }
  601. static ssize_t msg_add_dict_text(char *buf, size_t size,
  602. const char *key, const char *val)
  603. {
  604. size_t val_len = strlen(val);
  605. ssize_t len;
  606. if (!val_len)
  607. return 0;
  608. len = msg_add_ext_text(buf, size, "", 0, ' '); /* dict prefix */
  609. len += msg_add_ext_text(buf + len, size - len, key, strlen(key), '=');
  610. len += msg_add_ext_text(buf + len, size - len, val, val_len, '\n');
  611. return len;
  612. }
  613. static ssize_t msg_print_ext_body(char *buf, size_t size,
  614. char *text, size_t text_len,
  615. struct dev_printk_info *dev_info)
  616. {
  617. ssize_t len;
  618. len = msg_add_ext_text(buf, size, text, text_len, '\n');
  619. if (!dev_info)
  620. goto out;
  621. len += msg_add_dict_text(buf + len, size - len, "SUBSYSTEM",
  622. dev_info->subsystem);
  623. len += msg_add_dict_text(buf + len, size - len, "DEVICE",
  624. dev_info->device);
  625. out:
  626. return len;
  627. }
  628. /* /dev/kmsg - userspace message inject/listen interface */
  629. struct devkmsg_user {
  630. atomic64_t seq;
  631. struct ratelimit_state rs;
  632. struct mutex lock;
  633. struct printk_buffers pbufs;
  634. };
  635. static __printf(3, 4) __cold
  636. int devkmsg_emit(int facility, int level, const char *fmt, ...)
  637. {
  638. va_list args;
  639. int r;
  640. va_start(args, fmt);
  641. r = vprintk_emit(facility, level, NULL, fmt, args);
  642. va_end(args);
  643. return r;
  644. }
  645. static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
  646. {
  647. char *buf, *line;
  648. int level = default_message_loglevel;
  649. int facility = 1; /* LOG_USER */
  650. struct file *file = iocb->ki_filp;
  651. struct devkmsg_user *user = file->private_data;
  652. size_t len = iov_iter_count(from);
  653. ssize_t ret = len;
  654. if (len > PRINTKRB_RECORD_MAX)
  655. return -EINVAL;
  656. /* Ignore when user logging is disabled. */
  657. if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
  658. return len;
  659. /* Ratelimit when not explicitly enabled. */
  660. if (!(devkmsg_log & DEVKMSG_LOG_MASK_ON)) {
  661. if (!___ratelimit(&user->rs, current->comm))
  662. return ret;
  663. }
  664. buf = kmalloc(len+1, GFP_KERNEL);
  665. if (buf == NULL)
  666. return -ENOMEM;
  667. buf[len] = '\0';
  668. if (!copy_from_iter_full(buf, len, from)) {
  669. kfree(buf);
  670. return -EFAULT;
  671. }
  672. /*
  673. * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
  674. * the decimal value represents 32bit, the lower 3 bit are the log
  675. * level, the rest are the log facility.
  676. *
  677. * If no prefix or no userspace facility is specified, we
  678. * enforce LOG_USER, to be able to reliably distinguish
  679. * kernel-generated messages from userspace-injected ones.
  680. */
  681. line = buf;
  682. if (line[0] == '<') {
  683. char *endp = NULL;
  684. unsigned int u;
  685. u = simple_strtoul(line + 1, &endp, 10);
  686. if (endp && endp[0] == '>') {
  687. level = LOG_LEVEL(u);
  688. if (LOG_FACILITY(u) != 0)
  689. facility = LOG_FACILITY(u);
  690. endp++;
  691. line = endp;
  692. }
  693. }
  694. devkmsg_emit(facility, level, "%s", line);
  695. kfree(buf);
  696. return ret;
  697. }
  698. static ssize_t devkmsg_read(struct file *file, char __user *buf,
  699. size_t count, loff_t *ppos)
  700. {
  701. struct devkmsg_user *user = file->private_data;
  702. char *outbuf = &user->pbufs.outbuf[0];
  703. struct printk_message pmsg = {
  704. .pbufs = &user->pbufs,
  705. };
  706. ssize_t ret;
  707. ret = mutex_lock_interruptible(&user->lock);
  708. if (ret)
  709. return ret;
  710. if (!printk_get_next_message(&pmsg, atomic64_read(&user->seq), true, false)) {
  711. if (file->f_flags & O_NONBLOCK) {
  712. ret = -EAGAIN;
  713. goto out;
  714. }
  715. /*
  716. * Guarantee this task is visible on the waitqueue before
  717. * checking the wake condition.
  718. *
  719. * The full memory barrier within set_current_state() of
  720. * prepare_to_wait_event() pairs with the full memory barrier
  721. * within wq_has_sleeper().
  722. *
  723. * This pairs with __wake_up_klogd:A.
  724. */
  725. ret = wait_event_interruptible(log_wait,
  726. printk_get_next_message(&pmsg, atomic64_read(&user->seq), true,
  727. false)); /* LMM(devkmsg_read:A) */
  728. if (ret)
  729. goto out;
  730. }
  731. if (pmsg.dropped) {
  732. /* our last seen message is gone, return error and reset */
  733. atomic64_set(&user->seq, pmsg.seq);
  734. ret = -EPIPE;
  735. goto out;
  736. }
  737. atomic64_set(&user->seq, pmsg.seq + 1);
  738. if (pmsg.outbuf_len > count) {
  739. ret = -EINVAL;
  740. goto out;
  741. }
  742. if (copy_to_user(buf, outbuf, pmsg.outbuf_len)) {
  743. ret = -EFAULT;
  744. goto out;
  745. }
  746. ret = pmsg.outbuf_len;
  747. out:
  748. mutex_unlock(&user->lock);
  749. return ret;
  750. }
  751. /*
  752. * Be careful when modifying this function!!!
  753. *
  754. * Only few operations are supported because the device works only with the
  755. * entire variable length messages (records). Non-standard values are
  756. * returned in the other cases and has been this way for quite some time.
  757. * User space applications might depend on this behavior.
  758. */
  759. static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
  760. {
  761. struct devkmsg_user *user = file->private_data;
  762. loff_t ret = 0;
  763. if (offset)
  764. return -ESPIPE;
  765. switch (whence) {
  766. case SEEK_SET:
  767. /* the first record */
  768. atomic64_set(&user->seq, prb_first_valid_seq(prb));
  769. break;
  770. case SEEK_DATA:
  771. /*
  772. * The first record after the last SYSLOG_ACTION_CLEAR,
  773. * like issued by 'dmesg -c'. Reading /dev/kmsg itself
  774. * changes no global state, and does not clear anything.
  775. */
  776. atomic64_set(&user->seq, latched_seq_read_nolock(&clear_seq));
  777. break;
  778. case SEEK_END:
  779. /* after the last record */
  780. atomic64_set(&user->seq, prb_next_seq(prb));
  781. break;
  782. default:
  783. ret = -EINVAL;
  784. }
  785. return ret;
  786. }
  787. static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
  788. {
  789. struct devkmsg_user *user = file->private_data;
  790. struct printk_info info;
  791. __poll_t ret = 0;
  792. poll_wait(file, &log_wait, wait);
  793. if (prb_read_valid_info(prb, atomic64_read(&user->seq), &info, NULL)) {
  794. /* return error when data has vanished underneath us */
  795. if (info.seq != atomic64_read(&user->seq))
  796. ret = EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
  797. else
  798. ret = EPOLLIN|EPOLLRDNORM;
  799. }
  800. return ret;
  801. }
  802. static int devkmsg_open(struct inode *inode, struct file *file)
  803. {
  804. struct devkmsg_user *user;
  805. int err;
  806. if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
  807. return -EPERM;
  808. /* write-only does not need any file context */
  809. if ((file->f_flags & O_ACCMODE) != O_WRONLY) {
  810. err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
  811. SYSLOG_FROM_READER);
  812. if (err)
  813. return err;
  814. }
  815. user = kvmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
  816. if (!user)
  817. return -ENOMEM;
  818. ratelimit_default_init(&user->rs);
  819. ratelimit_set_flags(&user->rs, RATELIMIT_MSG_ON_RELEASE);
  820. mutex_init(&user->lock);
  821. atomic64_set(&user->seq, prb_first_valid_seq(prb));
  822. file->private_data = user;
  823. return 0;
  824. }
  825. static int devkmsg_release(struct inode *inode, struct file *file)
  826. {
  827. struct devkmsg_user *user = file->private_data;
  828. ratelimit_state_exit(&user->rs);
  829. mutex_destroy(&user->lock);
  830. kvfree(user);
  831. return 0;
  832. }
  833. const struct file_operations kmsg_fops = {
  834. .open = devkmsg_open,
  835. .read = devkmsg_read,
  836. .write_iter = devkmsg_write,
  837. .llseek = devkmsg_llseek,
  838. .poll = devkmsg_poll,
  839. .release = devkmsg_release,
  840. };
  841. #ifdef CONFIG_VMCORE_INFO
  842. /*
  843. * This appends the listed symbols to /proc/vmcore
  844. *
  845. * /proc/vmcore is used by various utilities, like crash and makedumpfile to
  846. * obtain access to symbols that are otherwise very difficult to locate. These
  847. * symbols are specifically used so that utilities can access and extract the
  848. * dmesg log from a vmcore file after a crash.
  849. */
  850. void log_buf_vmcoreinfo_setup(void)
  851. {
  852. struct dev_printk_info *dev_info = NULL;
  853. VMCOREINFO_SYMBOL(prb);
  854. VMCOREINFO_SYMBOL(printk_rb_static);
  855. VMCOREINFO_SYMBOL(clear_seq);
  856. /*
  857. * Export struct size and field offsets. User space tools can
  858. * parse it and detect any changes to structure down the line.
  859. */
  860. VMCOREINFO_STRUCT_SIZE(printk_ringbuffer);
  861. VMCOREINFO_OFFSET(printk_ringbuffer, desc_ring);
  862. VMCOREINFO_OFFSET(printk_ringbuffer, text_data_ring);
  863. VMCOREINFO_OFFSET(printk_ringbuffer, fail);
  864. VMCOREINFO_STRUCT_SIZE(prb_desc_ring);
  865. VMCOREINFO_OFFSET(prb_desc_ring, count_bits);
  866. VMCOREINFO_OFFSET(prb_desc_ring, descs);
  867. VMCOREINFO_OFFSET(prb_desc_ring, infos);
  868. VMCOREINFO_OFFSET(prb_desc_ring, head_id);
  869. VMCOREINFO_OFFSET(prb_desc_ring, tail_id);
  870. VMCOREINFO_STRUCT_SIZE(prb_desc);
  871. VMCOREINFO_OFFSET(prb_desc, state_var);
  872. VMCOREINFO_OFFSET(prb_desc, text_blk_lpos);
  873. VMCOREINFO_STRUCT_SIZE(prb_data_blk_lpos);
  874. VMCOREINFO_OFFSET(prb_data_blk_lpos, begin);
  875. VMCOREINFO_OFFSET(prb_data_blk_lpos, next);
  876. VMCOREINFO_STRUCT_SIZE(printk_info);
  877. VMCOREINFO_OFFSET(printk_info, seq);
  878. VMCOREINFO_OFFSET(printk_info, ts_nsec);
  879. VMCOREINFO_OFFSET(printk_info, text_len);
  880. VMCOREINFO_OFFSET(printk_info, caller_id);
  881. VMCOREINFO_OFFSET(printk_info, dev_info);
  882. VMCOREINFO_STRUCT_SIZE(dev_printk_info);
  883. VMCOREINFO_OFFSET(dev_printk_info, subsystem);
  884. VMCOREINFO_LENGTH(printk_info_subsystem, sizeof(dev_info->subsystem));
  885. VMCOREINFO_OFFSET(dev_printk_info, device);
  886. VMCOREINFO_LENGTH(printk_info_device, sizeof(dev_info->device));
  887. VMCOREINFO_STRUCT_SIZE(prb_data_ring);
  888. VMCOREINFO_OFFSET(prb_data_ring, size_bits);
  889. VMCOREINFO_OFFSET(prb_data_ring, data);
  890. VMCOREINFO_OFFSET(prb_data_ring, head_lpos);
  891. VMCOREINFO_OFFSET(prb_data_ring, tail_lpos);
  892. VMCOREINFO_SIZE(atomic_long_t);
  893. VMCOREINFO_TYPE_OFFSET(atomic_long_t, counter);
  894. VMCOREINFO_STRUCT_SIZE(latched_seq);
  895. VMCOREINFO_OFFSET(latched_seq, val);
  896. }
  897. #endif
  898. /* requested log_buf_len from kernel cmdline */
  899. static unsigned long __initdata new_log_buf_len;
  900. /* we practice scaling the ring buffer by powers of 2 */
  901. static void __init log_buf_len_update(u64 size)
  902. {
  903. if (size > (u64)LOG_BUF_LEN_MAX) {
  904. size = (u64)LOG_BUF_LEN_MAX;
  905. pr_err("log_buf over 2G is not supported.\n");
  906. }
  907. if (size)
  908. size = roundup_pow_of_two(size);
  909. if (size > log_buf_len)
  910. new_log_buf_len = (unsigned long)size;
  911. }
  912. /* save requested log_buf_len since it's too early to process it */
  913. static int __init log_buf_len_setup(char *str)
  914. {
  915. u64 size;
  916. if (!str)
  917. return -EINVAL;
  918. size = memparse(str, &str);
  919. log_buf_len_update(size);
  920. return 0;
  921. }
  922. early_param("log_buf_len", log_buf_len_setup);
  923. #ifdef CONFIG_SMP
  924. #define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
  925. static void __init log_buf_add_cpu(void)
  926. {
  927. unsigned int cpu_extra;
  928. /*
  929. * archs should set up cpu_possible_bits properly with
  930. * set_cpu_possible() after setup_arch() but just in
  931. * case lets ensure this is valid.
  932. */
  933. if (num_possible_cpus() == 1)
  934. return;
  935. cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
  936. /* by default this will only continue through for large > 64 CPUs */
  937. if (cpu_extra <= __LOG_BUF_LEN / 2)
  938. return;
  939. pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
  940. __LOG_CPU_MAX_BUF_LEN);
  941. pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
  942. cpu_extra);
  943. pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
  944. log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
  945. }
  946. #else /* !CONFIG_SMP */
  947. static inline void log_buf_add_cpu(void) {}
  948. #endif /* CONFIG_SMP */
  949. static void __init set_percpu_data_ready(void)
  950. {
  951. __printk_percpu_data_ready = true;
  952. }
  953. static unsigned int __init add_to_rb(struct printk_ringbuffer *rb,
  954. struct printk_record *r)
  955. {
  956. struct prb_reserved_entry e;
  957. struct printk_record dest_r;
  958. prb_rec_init_wr(&dest_r, r->info->text_len);
  959. if (!prb_reserve(&e, rb, &dest_r))
  960. return 0;
  961. memcpy(&dest_r.text_buf[0], &r->text_buf[0], r->info->text_len);
  962. dest_r.info->text_len = r->info->text_len;
  963. dest_r.info->facility = r->info->facility;
  964. dest_r.info->level = r->info->level;
  965. dest_r.info->flags = r->info->flags;
  966. dest_r.info->ts_nsec = r->info->ts_nsec;
  967. dest_r.info->caller_id = r->info->caller_id;
  968. memcpy(&dest_r.info->dev_info, &r->info->dev_info, sizeof(dest_r.info->dev_info));
  969. prb_final_commit(&e);
  970. return prb_record_text_space(&e);
  971. }
  972. static char setup_text_buf[PRINTKRB_RECORD_MAX] __initdata;
  973. void __init setup_log_buf(int early)
  974. {
  975. struct printk_info *new_infos;
  976. unsigned int new_descs_count;
  977. struct prb_desc *new_descs;
  978. struct printk_info info;
  979. struct printk_record r;
  980. unsigned int text_size;
  981. size_t new_descs_size;
  982. size_t new_infos_size;
  983. unsigned long flags;
  984. char *new_log_buf;
  985. unsigned int free;
  986. u64 seq;
  987. /*
  988. * Some archs call setup_log_buf() multiple times - first is very
  989. * early, e.g. from setup_arch(), and second - when percpu_areas
  990. * are initialised.
  991. */
  992. if (!early)
  993. set_percpu_data_ready();
  994. if (log_buf != __log_buf)
  995. return;
  996. if (!early && !new_log_buf_len)
  997. log_buf_add_cpu();
  998. if (!new_log_buf_len)
  999. return;
  1000. new_descs_count = new_log_buf_len >> PRB_AVGBITS;
  1001. if (new_descs_count == 0) {
  1002. pr_err("new_log_buf_len: %lu too small\n", new_log_buf_len);
  1003. return;
  1004. }
  1005. new_log_buf = memblock_alloc(new_log_buf_len, LOG_ALIGN);
  1006. if (unlikely(!new_log_buf)) {
  1007. pr_err("log_buf_len: %lu text bytes not available\n",
  1008. new_log_buf_len);
  1009. return;
  1010. }
  1011. new_descs_size = new_descs_count * sizeof(struct prb_desc);
  1012. new_descs = memblock_alloc(new_descs_size, LOG_ALIGN);
  1013. if (unlikely(!new_descs)) {
  1014. pr_err("log_buf_len: %zu desc bytes not available\n",
  1015. new_descs_size);
  1016. goto err_free_log_buf;
  1017. }
  1018. new_infos_size = new_descs_count * sizeof(struct printk_info);
  1019. new_infos = memblock_alloc(new_infos_size, LOG_ALIGN);
  1020. if (unlikely(!new_infos)) {
  1021. pr_err("log_buf_len: %zu info bytes not available\n",
  1022. new_infos_size);
  1023. goto err_free_descs;
  1024. }
  1025. prb_rec_init_rd(&r, &info, &setup_text_buf[0], sizeof(setup_text_buf));
  1026. prb_init(&printk_rb_dynamic,
  1027. new_log_buf, ilog2(new_log_buf_len),
  1028. new_descs, ilog2(new_descs_count),
  1029. new_infos);
  1030. local_irq_save(flags);
  1031. log_buf_len = new_log_buf_len;
  1032. log_buf = new_log_buf;
  1033. new_log_buf_len = 0;
  1034. free = __LOG_BUF_LEN;
  1035. prb_for_each_record(0, &printk_rb_static, seq, &r) {
  1036. text_size = add_to_rb(&printk_rb_dynamic, &r);
  1037. if (text_size > free)
  1038. free = 0;
  1039. else
  1040. free -= text_size;
  1041. }
  1042. prb = &printk_rb_dynamic;
  1043. local_irq_restore(flags);
  1044. /*
  1045. * Copy any remaining messages that might have appeared from
  1046. * NMI context after copying but before switching to the
  1047. * dynamic buffer.
  1048. */
  1049. prb_for_each_record(seq, &printk_rb_static, seq, &r) {
  1050. text_size = add_to_rb(&printk_rb_dynamic, &r);
  1051. if (text_size > free)
  1052. free = 0;
  1053. else
  1054. free -= text_size;
  1055. }
  1056. if (seq != prb_next_seq(&printk_rb_static)) {
  1057. pr_err("dropped %llu messages\n",
  1058. prb_next_seq(&printk_rb_static) - seq);
  1059. }
  1060. pr_info("log_buf_len: %u bytes\n", log_buf_len);
  1061. pr_info("early log buf free: %u(%u%%)\n",
  1062. free, (free * 100) / __LOG_BUF_LEN);
  1063. return;
  1064. err_free_descs:
  1065. memblock_free(new_descs, new_descs_size);
  1066. err_free_log_buf:
  1067. memblock_free(new_log_buf, new_log_buf_len);
  1068. }
  1069. static bool __read_mostly ignore_loglevel;
  1070. static int __init ignore_loglevel_setup(char *str)
  1071. {
  1072. ignore_loglevel = true;
  1073. pr_info("debug: ignoring loglevel setting.\n");
  1074. return 0;
  1075. }
  1076. early_param("ignore_loglevel", ignore_loglevel_setup);
  1077. module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
  1078. MODULE_PARM_DESC(ignore_loglevel,
  1079. "ignore loglevel setting (prints all kernel messages to the console)");
  1080. static bool suppress_message_printing(int level)
  1081. {
  1082. return (level >= console_loglevel && !ignore_loglevel);
  1083. }
  1084. #ifdef CONFIG_BOOT_PRINTK_DELAY
  1085. static int boot_delay; /* msecs delay after each printk during bootup */
  1086. static unsigned long long loops_per_msec; /* based on boot_delay */
  1087. static int __init boot_delay_setup(char *str)
  1088. {
  1089. unsigned long lpj;
  1090. lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
  1091. loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
  1092. get_option(&str, &boot_delay);
  1093. if (boot_delay > 10 * 1000)
  1094. boot_delay = 0;
  1095. pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
  1096. "HZ: %d, loops_per_msec: %llu\n",
  1097. boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
  1098. return 0;
  1099. }
  1100. early_param("boot_delay", boot_delay_setup);
  1101. static void boot_delay_msec(int level)
  1102. {
  1103. unsigned long long k;
  1104. unsigned long timeout;
  1105. if ((boot_delay == 0 || system_state >= SYSTEM_RUNNING)
  1106. || suppress_message_printing(level)) {
  1107. return;
  1108. }
  1109. k = (unsigned long long)loops_per_msec * boot_delay;
  1110. timeout = jiffies + msecs_to_jiffies(boot_delay);
  1111. while (k) {
  1112. k--;
  1113. cpu_relax();
  1114. /*
  1115. * use (volatile) jiffies to prevent
  1116. * compiler reduction; loop termination via jiffies
  1117. * is secondary and may or may not happen.
  1118. */
  1119. if (time_after(jiffies, timeout))
  1120. break;
  1121. touch_nmi_watchdog();
  1122. }
  1123. }
  1124. #else
  1125. static inline void boot_delay_msec(int level)
  1126. {
  1127. }
  1128. #endif
  1129. static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
  1130. module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
  1131. static size_t print_syslog(unsigned int level, char *buf)
  1132. {
  1133. return sprintf(buf, "<%u>", level);
  1134. }
  1135. static size_t print_time(u64 ts, char *buf)
  1136. {
  1137. unsigned long rem_nsec = do_div(ts, 1000000000);
  1138. return sprintf(buf, "[%5lu.%06lu]",
  1139. (unsigned long)ts, rem_nsec / 1000);
  1140. }
  1141. #ifdef CONFIG_PRINTK_CALLER
  1142. static size_t print_caller(u32 id, char *buf)
  1143. {
  1144. char caller[12];
  1145. snprintf(caller, sizeof(caller), "%c%u",
  1146. id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
  1147. return sprintf(buf, "[%6s]", caller);
  1148. }
  1149. #else
  1150. #define print_caller(id, buf) 0
  1151. #endif
  1152. static size_t info_print_prefix(const struct printk_info *info, bool syslog,
  1153. bool time, char *buf)
  1154. {
  1155. size_t len = 0;
  1156. if (syslog)
  1157. len = print_syslog((info->facility << 3) | info->level, buf);
  1158. if (time)
  1159. len += print_time(info->ts_nsec, buf + len);
  1160. len += print_caller(info->caller_id, buf + len);
  1161. if (IS_ENABLED(CONFIG_PRINTK_CALLER) || time) {
  1162. buf[len++] = ' ';
  1163. buf[len] = '\0';
  1164. }
  1165. return len;
  1166. }
  1167. /*
  1168. * Prepare the record for printing. The text is shifted within the given
  1169. * buffer to avoid a need for another one. The following operations are
  1170. * done:
  1171. *
  1172. * - Add prefix for each line.
  1173. * - Drop truncated lines that no longer fit into the buffer.
  1174. * - Add the trailing newline that has been removed in vprintk_store().
  1175. * - Add a string terminator.
  1176. *
  1177. * Since the produced string is always terminated, the maximum possible
  1178. * return value is @r->text_buf_size - 1;
  1179. *
  1180. * Return: The length of the updated/prepared text, including the added
  1181. * prefixes and the newline. The terminator is not counted. The dropped
  1182. * line(s) are not counted.
  1183. */
  1184. static size_t record_print_text(struct printk_record *r, bool syslog,
  1185. bool time)
  1186. {
  1187. size_t text_len = r->info->text_len;
  1188. size_t buf_size = r->text_buf_size;
  1189. char *text = r->text_buf;
  1190. char prefix[PRINTK_PREFIX_MAX];
  1191. bool truncated = false;
  1192. size_t prefix_len;
  1193. size_t line_len;
  1194. size_t len = 0;
  1195. char *next;
  1196. /*
  1197. * If the message was truncated because the buffer was not large
  1198. * enough, treat the available text as if it were the full text.
  1199. */
  1200. if (text_len > buf_size)
  1201. text_len = buf_size;
  1202. prefix_len = info_print_prefix(r->info, syslog, time, prefix);
  1203. /*
  1204. * @text_len: bytes of unprocessed text
  1205. * @line_len: bytes of current line _without_ newline
  1206. * @text: pointer to beginning of current line
  1207. * @len: number of bytes prepared in r->text_buf
  1208. */
  1209. for (;;) {
  1210. next = memchr(text, '\n', text_len);
  1211. if (next) {
  1212. line_len = next - text;
  1213. } else {
  1214. /* Drop truncated line(s). */
  1215. if (truncated)
  1216. break;
  1217. line_len = text_len;
  1218. }
  1219. /*
  1220. * Truncate the text if there is not enough space to add the
  1221. * prefix and a trailing newline and a terminator.
  1222. */
  1223. if (len + prefix_len + text_len + 1 + 1 > buf_size) {
  1224. /* Drop even the current line if no space. */
  1225. if (len + prefix_len + line_len + 1 + 1 > buf_size)
  1226. break;
  1227. text_len = buf_size - len - prefix_len - 1 - 1;
  1228. truncated = true;
  1229. }
  1230. memmove(text + prefix_len, text, text_len);
  1231. memcpy(text, prefix, prefix_len);
  1232. /*
  1233. * Increment the prepared length to include the text and
  1234. * prefix that were just moved+copied. Also increment for the
  1235. * newline at the end of this line. If this is the last line,
  1236. * there is no newline, but it will be added immediately below.
  1237. */
  1238. len += prefix_len + line_len + 1;
  1239. if (text_len == line_len) {
  1240. /*
  1241. * This is the last line. Add the trailing newline
  1242. * removed in vprintk_store().
  1243. */
  1244. text[prefix_len + line_len] = '\n';
  1245. break;
  1246. }
  1247. /*
  1248. * Advance beyond the added prefix and the related line with
  1249. * its newline.
  1250. */
  1251. text += prefix_len + line_len + 1;
  1252. /*
  1253. * The remaining text has only decreased by the line with its
  1254. * newline.
  1255. *
  1256. * Note that @text_len can become zero. It happens when @text
  1257. * ended with a newline (either due to truncation or the
  1258. * original string ending with "\n\n"). The loop is correctly
  1259. * repeated and (if not truncated) an empty line with a prefix
  1260. * will be prepared.
  1261. */
  1262. text_len -= line_len + 1;
  1263. }
  1264. /*
  1265. * If a buffer was provided, it will be terminated. Space for the
  1266. * string terminator is guaranteed to be available. The terminator is
  1267. * not counted in the return value.
  1268. */
  1269. if (buf_size > 0)
  1270. r->text_buf[len] = 0;
  1271. return len;
  1272. }
  1273. static size_t get_record_print_text_size(struct printk_info *info,
  1274. unsigned int line_count,
  1275. bool syslog, bool time)
  1276. {
  1277. char prefix[PRINTK_PREFIX_MAX];
  1278. size_t prefix_len;
  1279. prefix_len = info_print_prefix(info, syslog, time, prefix);
  1280. /*
  1281. * Each line will be preceded with a prefix. The intermediate
  1282. * newlines are already within the text, but a final trailing
  1283. * newline will be added.
  1284. */
  1285. return ((prefix_len * line_count) + info->text_len + 1);
  1286. }
  1287. /*
  1288. * Beginning with @start_seq, find the first record where it and all following
  1289. * records up to (but not including) @max_seq fit into @size.
  1290. *
  1291. * @max_seq is simply an upper bound and does not need to exist. If the caller
  1292. * does not require an upper bound, -1 can be used for @max_seq.
  1293. */
  1294. static u64 find_first_fitting_seq(u64 start_seq, u64 max_seq, size_t size,
  1295. bool syslog, bool time)
  1296. {
  1297. struct printk_info info;
  1298. unsigned int line_count;
  1299. size_t len = 0;
  1300. u64 seq;
  1301. /* Determine the size of the records up to @max_seq. */
  1302. prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
  1303. if (info.seq >= max_seq)
  1304. break;
  1305. len += get_record_print_text_size(&info, line_count, syslog, time);
  1306. }
  1307. /*
  1308. * Adjust the upper bound for the next loop to avoid subtracting
  1309. * lengths that were never added.
  1310. */
  1311. if (seq < max_seq)
  1312. max_seq = seq;
  1313. /*
  1314. * Move first record forward until length fits into the buffer. Ignore
  1315. * newest messages that were not counted in the above cycle. Messages
  1316. * might appear and get lost in the meantime. This is a best effort
  1317. * that prevents an infinite loop that could occur with a retry.
  1318. */
  1319. prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
  1320. if (len <= size || info.seq >= max_seq)
  1321. break;
  1322. len -= get_record_print_text_size(&info, line_count, syslog, time);
  1323. }
  1324. return seq;
  1325. }
  1326. /* The caller is responsible for making sure @size is greater than 0. */
  1327. static int syslog_print(char __user *buf, int size)
  1328. {
  1329. struct printk_info info;
  1330. struct printk_record r;
  1331. char *text;
  1332. int len = 0;
  1333. u64 seq;
  1334. text = kmalloc(PRINTK_MESSAGE_MAX, GFP_KERNEL);
  1335. if (!text)
  1336. return -ENOMEM;
  1337. prb_rec_init_rd(&r, &info, text, PRINTK_MESSAGE_MAX);
  1338. mutex_lock(&syslog_lock);
  1339. /*
  1340. * Wait for the @syslog_seq record to be available. @syslog_seq may
  1341. * change while waiting.
  1342. */
  1343. do {
  1344. seq = syslog_seq;
  1345. mutex_unlock(&syslog_lock);
  1346. /*
  1347. * Guarantee this task is visible on the waitqueue before
  1348. * checking the wake condition.
  1349. *
  1350. * The full memory barrier within set_current_state() of
  1351. * prepare_to_wait_event() pairs with the full memory barrier
  1352. * within wq_has_sleeper().
  1353. *
  1354. * This pairs with __wake_up_klogd:A.
  1355. */
  1356. len = wait_event_interruptible(log_wait,
  1357. prb_read_valid(prb, seq, NULL)); /* LMM(syslog_print:A) */
  1358. mutex_lock(&syslog_lock);
  1359. if (len)
  1360. goto out;
  1361. } while (syslog_seq != seq);
  1362. /*
  1363. * Copy records that fit into the buffer. The above cycle makes sure
  1364. * that the first record is always available.
  1365. */
  1366. do {
  1367. size_t n;
  1368. size_t skip;
  1369. int err;
  1370. if (!prb_read_valid(prb, syslog_seq, &r))
  1371. break;
  1372. if (r.info->seq != syslog_seq) {
  1373. /* message is gone, move to next valid one */
  1374. syslog_seq = r.info->seq;
  1375. syslog_partial = 0;
  1376. }
  1377. /*
  1378. * To keep reading/counting partial line consistent,
  1379. * use printk_time value as of the beginning of a line.
  1380. */
  1381. if (!syslog_partial)
  1382. syslog_time = printk_time;
  1383. skip = syslog_partial;
  1384. n = record_print_text(&r, true, syslog_time);
  1385. if (n - syslog_partial <= size) {
  1386. /* message fits into buffer, move forward */
  1387. syslog_seq = r.info->seq + 1;
  1388. n -= syslog_partial;
  1389. syslog_partial = 0;
  1390. } else if (!len){
  1391. /* partial read(), remember position */
  1392. n = size;
  1393. syslog_partial += n;
  1394. } else
  1395. n = 0;
  1396. if (!n)
  1397. break;
  1398. mutex_unlock(&syslog_lock);
  1399. err = copy_to_user(buf, text + skip, n);
  1400. mutex_lock(&syslog_lock);
  1401. if (err) {
  1402. if (!len)
  1403. len = -EFAULT;
  1404. break;
  1405. }
  1406. len += n;
  1407. size -= n;
  1408. buf += n;
  1409. } while (size);
  1410. out:
  1411. mutex_unlock(&syslog_lock);
  1412. kfree(text);
  1413. return len;
  1414. }
  1415. static int syslog_print_all(char __user *buf, int size, bool clear)
  1416. {
  1417. struct printk_info info;
  1418. struct printk_record r;
  1419. char *text;
  1420. int len = 0;
  1421. u64 seq;
  1422. bool time;
  1423. text = kmalloc(PRINTK_MESSAGE_MAX, GFP_KERNEL);
  1424. if (!text)
  1425. return -ENOMEM;
  1426. time = printk_time;
  1427. /*
  1428. * Find first record that fits, including all following records,
  1429. * into the user-provided buffer for this dump.
  1430. */
  1431. seq = find_first_fitting_seq(latched_seq_read_nolock(&clear_seq), -1,
  1432. size, true, time);
  1433. prb_rec_init_rd(&r, &info, text, PRINTK_MESSAGE_MAX);
  1434. prb_for_each_record(seq, prb, seq, &r) {
  1435. int textlen;
  1436. textlen = record_print_text(&r, true, time);
  1437. if (len + textlen > size) {
  1438. seq--;
  1439. break;
  1440. }
  1441. if (copy_to_user(buf + len, text, textlen))
  1442. len = -EFAULT;
  1443. else
  1444. len += textlen;
  1445. if (len < 0)
  1446. break;
  1447. }
  1448. if (clear) {
  1449. mutex_lock(&syslog_lock);
  1450. latched_seq_write(&clear_seq, seq);
  1451. mutex_unlock(&syslog_lock);
  1452. }
  1453. kfree(text);
  1454. return len;
  1455. }
  1456. static void syslog_clear(void)
  1457. {
  1458. mutex_lock(&syslog_lock);
  1459. latched_seq_write(&clear_seq, prb_next_seq(prb));
  1460. mutex_unlock(&syslog_lock);
  1461. }
  1462. int do_syslog(int type, char __user *buf, int len, int source)
  1463. {
  1464. struct printk_info info;
  1465. bool clear = false;
  1466. static int saved_console_loglevel = LOGLEVEL_DEFAULT;
  1467. int error;
  1468. error = check_syslog_permissions(type, source);
  1469. if (error)
  1470. return error;
  1471. switch (type) {
  1472. case SYSLOG_ACTION_CLOSE: /* Close log */
  1473. break;
  1474. case SYSLOG_ACTION_OPEN: /* Open log */
  1475. break;
  1476. case SYSLOG_ACTION_READ: /* Read from log */
  1477. if (!buf || len < 0)
  1478. return -EINVAL;
  1479. if (!len)
  1480. return 0;
  1481. if (!access_ok(buf, len))
  1482. return -EFAULT;
  1483. error = syslog_print(buf, len);
  1484. break;
  1485. /* Read/clear last kernel messages */
  1486. case SYSLOG_ACTION_READ_CLEAR:
  1487. clear = true;
  1488. fallthrough;
  1489. /* Read last kernel messages */
  1490. case SYSLOG_ACTION_READ_ALL:
  1491. if (!buf || len < 0)
  1492. return -EINVAL;
  1493. if (!len)
  1494. return 0;
  1495. if (!access_ok(buf, len))
  1496. return -EFAULT;
  1497. error = syslog_print_all(buf, len, clear);
  1498. break;
  1499. /* Clear ring buffer */
  1500. case SYSLOG_ACTION_CLEAR:
  1501. syslog_clear();
  1502. break;
  1503. /* Disable logging to console */
  1504. case SYSLOG_ACTION_CONSOLE_OFF:
  1505. if (saved_console_loglevel == LOGLEVEL_DEFAULT)
  1506. saved_console_loglevel = console_loglevel;
  1507. console_loglevel = minimum_console_loglevel;
  1508. break;
  1509. /* Enable logging to console */
  1510. case SYSLOG_ACTION_CONSOLE_ON:
  1511. if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
  1512. console_loglevel = saved_console_loglevel;
  1513. saved_console_loglevel = LOGLEVEL_DEFAULT;
  1514. }
  1515. break;
  1516. /* Set level of messages printed to console */
  1517. case SYSLOG_ACTION_CONSOLE_LEVEL:
  1518. if (len < 1 || len > 8)
  1519. return -EINVAL;
  1520. if (len < minimum_console_loglevel)
  1521. len = minimum_console_loglevel;
  1522. console_loglevel = len;
  1523. /* Implicitly re-enable logging to console */
  1524. saved_console_loglevel = LOGLEVEL_DEFAULT;
  1525. break;
  1526. /* Number of chars in the log buffer */
  1527. case SYSLOG_ACTION_SIZE_UNREAD:
  1528. mutex_lock(&syslog_lock);
  1529. if (!prb_read_valid_info(prb, syslog_seq, &info, NULL)) {
  1530. /* No unread messages. */
  1531. mutex_unlock(&syslog_lock);
  1532. return 0;
  1533. }
  1534. if (info.seq != syslog_seq) {
  1535. /* messages are gone, move to first one */
  1536. syslog_seq = info.seq;
  1537. syslog_partial = 0;
  1538. }
  1539. if (source == SYSLOG_FROM_PROC) {
  1540. /*
  1541. * Short-cut for poll(/"proc/kmsg") which simply checks
  1542. * for pending data, not the size; return the count of
  1543. * records, not the length.
  1544. */
  1545. error = prb_next_seq(prb) - syslog_seq;
  1546. } else {
  1547. bool time = syslog_partial ? syslog_time : printk_time;
  1548. unsigned int line_count;
  1549. u64 seq;
  1550. prb_for_each_info(syslog_seq, prb, seq, &info,
  1551. &line_count) {
  1552. error += get_record_print_text_size(&info, line_count,
  1553. true, time);
  1554. time = printk_time;
  1555. }
  1556. error -= syslog_partial;
  1557. }
  1558. mutex_unlock(&syslog_lock);
  1559. break;
  1560. /* Size of the log buffer */
  1561. case SYSLOG_ACTION_SIZE_BUFFER:
  1562. error = log_buf_len;
  1563. break;
  1564. default:
  1565. error = -EINVAL;
  1566. break;
  1567. }
  1568. return error;
  1569. }
  1570. SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
  1571. {
  1572. return do_syslog(type, buf, len, SYSLOG_FROM_READER);
  1573. }
  1574. /*
  1575. * Special console_lock variants that help to reduce the risk of soft-lockups.
  1576. * They allow to pass console_lock to another printk() call using a busy wait.
  1577. */
  1578. #ifdef CONFIG_LOCKDEP
  1579. static struct lockdep_map console_owner_dep_map = {
  1580. .name = "console_owner"
  1581. };
  1582. #endif
  1583. static DEFINE_RAW_SPINLOCK(console_owner_lock);
  1584. static struct task_struct *console_owner;
  1585. static bool console_waiter;
  1586. /**
  1587. * console_lock_spinning_enable - mark beginning of code where another
  1588. * thread might safely busy wait
  1589. *
  1590. * This basically converts console_lock into a spinlock. This marks
  1591. * the section where the console_lock owner can not sleep, because
  1592. * there may be a waiter spinning (like a spinlock). Also it must be
  1593. * ready to hand over the lock at the end of the section.
  1594. */
  1595. void console_lock_spinning_enable(void)
  1596. {
  1597. /*
  1598. * Do not use spinning in panic(). The panic CPU wants to keep the lock.
  1599. * Non-panic CPUs abandon the flush anyway.
  1600. *
  1601. * Just keep the lockdep annotation. The panic-CPU should avoid
  1602. * taking console_owner_lock because it might cause a deadlock.
  1603. * This looks like the easiest way how to prevent false lockdep
  1604. * reports without handling races a lockless way.
  1605. */
  1606. if (panic_in_progress())
  1607. goto lockdep;
  1608. raw_spin_lock(&console_owner_lock);
  1609. console_owner = current;
  1610. raw_spin_unlock(&console_owner_lock);
  1611. lockdep:
  1612. /* The waiter may spin on us after setting console_owner */
  1613. spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
  1614. }
  1615. /**
  1616. * console_lock_spinning_disable_and_check - mark end of code where another
  1617. * thread was able to busy wait and check if there is a waiter
  1618. * @cookie: cookie returned from console_srcu_read_lock()
  1619. *
  1620. * This is called at the end of the section where spinning is allowed.
  1621. * It has two functions. First, it is a signal that it is no longer
  1622. * safe to start busy waiting for the lock. Second, it checks if
  1623. * there is a busy waiter and passes the lock rights to her.
  1624. *
  1625. * Important: Callers lose both the console_lock and the SRCU read lock if
  1626. * there was a busy waiter. They must not touch items synchronized by
  1627. * console_lock or SRCU read lock in this case.
  1628. *
  1629. * Return: 1 if the lock rights were passed, 0 otherwise.
  1630. */
  1631. int console_lock_spinning_disable_and_check(int cookie)
  1632. {
  1633. int waiter;
  1634. /*
  1635. * Ignore spinning waiters during panic() because they might get stopped
  1636. * or blocked at any time,
  1637. *
  1638. * It is safe because nobody is allowed to start spinning during panic
  1639. * in the first place. If there has been a waiter then non panic CPUs
  1640. * might stay spinning. They would get stopped anyway. The panic context
  1641. * will never start spinning and an interrupted spin on panic CPU will
  1642. * never continue.
  1643. */
  1644. if (panic_in_progress()) {
  1645. /* Keep lockdep happy. */
  1646. spin_release(&console_owner_dep_map, _THIS_IP_);
  1647. return 0;
  1648. }
  1649. raw_spin_lock(&console_owner_lock);
  1650. waiter = READ_ONCE(console_waiter);
  1651. console_owner = NULL;
  1652. raw_spin_unlock(&console_owner_lock);
  1653. if (!waiter) {
  1654. spin_release(&console_owner_dep_map, _THIS_IP_);
  1655. return 0;
  1656. }
  1657. /* The waiter is now free to continue */
  1658. WRITE_ONCE(console_waiter, false);
  1659. spin_release(&console_owner_dep_map, _THIS_IP_);
  1660. /*
  1661. * Preserve lockdep lock ordering. Release the SRCU read lock before
  1662. * releasing the console_lock.
  1663. */
  1664. console_srcu_read_unlock(cookie);
  1665. /*
  1666. * Hand off console_lock to waiter. The waiter will perform
  1667. * the up(). After this, the waiter is the console_lock owner.
  1668. */
  1669. mutex_release(&console_lock_dep_map, _THIS_IP_);
  1670. return 1;
  1671. }
  1672. /**
  1673. * console_trylock_spinning - try to get console_lock by busy waiting
  1674. *
  1675. * This allows to busy wait for the console_lock when the current
  1676. * owner is running in specially marked sections. It means that
  1677. * the current owner is running and cannot reschedule until it
  1678. * is ready to lose the lock.
  1679. *
  1680. * Return: 1 if we got the lock, 0 othrewise
  1681. */
  1682. static int console_trylock_spinning(void)
  1683. {
  1684. struct task_struct *owner = NULL;
  1685. bool waiter;
  1686. bool spin = false;
  1687. unsigned long flags;
  1688. if (console_trylock())
  1689. return 1;
  1690. /*
  1691. * It's unsafe to spin once a panic has begun. If we are the
  1692. * panic CPU, we may have already halted the owner of the
  1693. * console_sem. If we are not the panic CPU, then we should
  1694. * avoid taking console_sem, so the panic CPU has a better
  1695. * chance of cleanly acquiring it later.
  1696. */
  1697. if (panic_in_progress())
  1698. return 0;
  1699. printk_safe_enter_irqsave(flags);
  1700. raw_spin_lock(&console_owner_lock);
  1701. owner = READ_ONCE(console_owner);
  1702. waiter = READ_ONCE(console_waiter);
  1703. if (!waiter && owner && owner != current) {
  1704. WRITE_ONCE(console_waiter, true);
  1705. spin = true;
  1706. }
  1707. raw_spin_unlock(&console_owner_lock);
  1708. /*
  1709. * If there is an active printk() writing to the
  1710. * consoles, instead of having it write our data too,
  1711. * see if we can offload that load from the active
  1712. * printer, and do some printing ourselves.
  1713. * Go into a spin only if there isn't already a waiter
  1714. * spinning, and there is an active printer, and
  1715. * that active printer isn't us (recursive printk?).
  1716. */
  1717. if (!spin) {
  1718. printk_safe_exit_irqrestore(flags);
  1719. return 0;
  1720. }
  1721. /* We spin waiting for the owner to release us */
  1722. spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
  1723. /* Owner will clear console_waiter on hand off */
  1724. while (READ_ONCE(console_waiter))
  1725. cpu_relax();
  1726. spin_release(&console_owner_dep_map, _THIS_IP_);
  1727. printk_safe_exit_irqrestore(flags);
  1728. /*
  1729. * The owner passed the console lock to us.
  1730. * Since we did not spin on console lock, annotate
  1731. * this as a trylock. Otherwise lockdep will
  1732. * complain.
  1733. */
  1734. mutex_acquire(&console_lock_dep_map, 0, 1, _THIS_IP_);
  1735. /*
  1736. * Update @console_may_schedule for trylock because the previous
  1737. * owner may have been schedulable.
  1738. */
  1739. console_may_schedule = 0;
  1740. return 1;
  1741. }
  1742. /*
  1743. * Recursion is tracked separately on each CPU. If NMIs are supported, an
  1744. * additional NMI context per CPU is also separately tracked. Until per-CPU
  1745. * is available, a separate "early tracking" is performed.
  1746. */
  1747. static DEFINE_PER_CPU(u8, printk_count);
  1748. static u8 printk_count_early;
  1749. #ifdef CONFIG_HAVE_NMI
  1750. static DEFINE_PER_CPU(u8, printk_count_nmi);
  1751. static u8 printk_count_nmi_early;
  1752. #endif
  1753. /*
  1754. * Recursion is limited to keep the output sane. printk() should not require
  1755. * more than 1 level of recursion (allowing, for example, printk() to trigger
  1756. * a WARN), but a higher value is used in case some printk-internal errors
  1757. * exist, such as the ringbuffer validation checks failing.
  1758. */
  1759. #define PRINTK_MAX_RECURSION 3
  1760. /*
  1761. * Return a pointer to the dedicated counter for the CPU+context of the
  1762. * caller.
  1763. */
  1764. static u8 *__printk_recursion_counter(void)
  1765. {
  1766. #ifdef CONFIG_HAVE_NMI
  1767. if (in_nmi()) {
  1768. if (printk_percpu_data_ready())
  1769. return this_cpu_ptr(&printk_count_nmi);
  1770. return &printk_count_nmi_early;
  1771. }
  1772. #endif
  1773. if (printk_percpu_data_ready())
  1774. return this_cpu_ptr(&printk_count);
  1775. return &printk_count_early;
  1776. }
  1777. /*
  1778. * Enter recursion tracking. Interrupts are disabled to simplify tracking.
  1779. * The caller must check the boolean return value to see if the recursion is
  1780. * allowed. On failure, interrupts are not disabled.
  1781. *
  1782. * @recursion_ptr must be a variable of type (u8 *) and is the same variable
  1783. * that is passed to printk_exit_irqrestore().
  1784. */
  1785. #define printk_enter_irqsave(recursion_ptr, flags) \
  1786. ({ \
  1787. bool success = true; \
  1788. \
  1789. typecheck(u8 *, recursion_ptr); \
  1790. local_irq_save(flags); \
  1791. (recursion_ptr) = __printk_recursion_counter(); \
  1792. if (*(recursion_ptr) > PRINTK_MAX_RECURSION) { \
  1793. local_irq_restore(flags); \
  1794. success = false; \
  1795. } else { \
  1796. (*(recursion_ptr))++; \
  1797. } \
  1798. success; \
  1799. })
  1800. /* Exit recursion tracking, restoring interrupts. */
  1801. #define printk_exit_irqrestore(recursion_ptr, flags) \
  1802. do { \
  1803. typecheck(u8 *, recursion_ptr); \
  1804. (*(recursion_ptr))--; \
  1805. local_irq_restore(flags); \
  1806. } while (0)
  1807. int printk_delay_msec __read_mostly;
  1808. static inline void printk_delay(int level)
  1809. {
  1810. boot_delay_msec(level);
  1811. if (unlikely(printk_delay_msec)) {
  1812. int m = printk_delay_msec;
  1813. while (m--) {
  1814. mdelay(1);
  1815. touch_nmi_watchdog();
  1816. }
  1817. }
  1818. }
  1819. static inline u32 printk_caller_id(void)
  1820. {
  1821. return in_task() ? task_pid_nr(current) :
  1822. 0x80000000 + smp_processor_id();
  1823. }
  1824. /**
  1825. * printk_parse_prefix - Parse level and control flags.
  1826. *
  1827. * @text: The terminated text message.
  1828. * @level: A pointer to the current level value, will be updated.
  1829. * @flags: A pointer to the current printk_info flags, will be updated.
  1830. *
  1831. * @level may be NULL if the caller is not interested in the parsed value.
  1832. * Otherwise the variable pointed to by @level must be set to
  1833. * LOGLEVEL_DEFAULT in order to be updated with the parsed value.
  1834. *
  1835. * @flags may be NULL if the caller is not interested in the parsed value.
  1836. * Otherwise the variable pointed to by @flags will be OR'd with the parsed
  1837. * value.
  1838. *
  1839. * Return: The length of the parsed level and control flags.
  1840. */
  1841. u16 printk_parse_prefix(const char *text, int *level,
  1842. enum printk_info_flags *flags)
  1843. {
  1844. u16 prefix_len = 0;
  1845. int kern_level;
  1846. while (*text) {
  1847. kern_level = printk_get_level(text);
  1848. if (!kern_level)
  1849. break;
  1850. switch (kern_level) {
  1851. case '0' ... '7':
  1852. if (level && *level == LOGLEVEL_DEFAULT)
  1853. *level = kern_level - '0';
  1854. break;
  1855. case 'c': /* KERN_CONT */
  1856. if (flags)
  1857. *flags |= LOG_CONT;
  1858. }
  1859. prefix_len += 2;
  1860. text += 2;
  1861. }
  1862. return prefix_len;
  1863. }
  1864. __printf(5, 0)
  1865. static u16 printk_sprint(char *text, u16 size, int facility,
  1866. enum printk_info_flags *flags, const char *fmt,
  1867. va_list args)
  1868. {
  1869. u16 text_len;
  1870. text_len = vscnprintf(text, size, fmt, args);
  1871. /* Mark and strip a trailing newline. */
  1872. if (text_len && text[text_len - 1] == '\n') {
  1873. text_len--;
  1874. *flags |= LOG_NEWLINE;
  1875. }
  1876. /* Strip log level and control flags. */
  1877. if (facility == 0) {
  1878. u16 prefix_len;
  1879. prefix_len = printk_parse_prefix(text, NULL, NULL);
  1880. if (prefix_len) {
  1881. text_len -= prefix_len;
  1882. memmove(text, text + prefix_len, text_len);
  1883. }
  1884. }
  1885. trace_console(text, text_len);
  1886. return text_len;
  1887. }
  1888. __printf(4, 0)
  1889. int vprintk_store(int facility, int level,
  1890. const struct dev_printk_info *dev_info,
  1891. const char *fmt, va_list args)
  1892. {
  1893. struct prb_reserved_entry e;
  1894. enum printk_info_flags flags = 0;
  1895. struct printk_record r;
  1896. unsigned long irqflags;
  1897. u16 trunc_msg_len = 0;
  1898. char prefix_buf[8];
  1899. u8 *recursion_ptr;
  1900. u16 reserve_size;
  1901. va_list args2;
  1902. u32 caller_id;
  1903. u16 text_len;
  1904. int ret = 0;
  1905. u64 ts_nsec;
  1906. if (!printk_enter_irqsave(recursion_ptr, irqflags))
  1907. return 0;
  1908. /*
  1909. * Since the duration of printk() can vary depending on the message
  1910. * and state of the ringbuffer, grab the timestamp now so that it is
  1911. * close to the call of printk(). This provides a more deterministic
  1912. * timestamp with respect to the caller.
  1913. */
  1914. ts_nsec = local_clock();
  1915. caller_id = printk_caller_id();
  1916. /*
  1917. * The sprintf needs to come first since the syslog prefix might be
  1918. * passed in as a parameter. An extra byte must be reserved so that
  1919. * later the vscnprintf() into the reserved buffer has room for the
  1920. * terminating '\0', which is not counted by vsnprintf().
  1921. */
  1922. va_copy(args2, args);
  1923. reserve_size = vsnprintf(&prefix_buf[0], sizeof(prefix_buf), fmt, args2) + 1;
  1924. va_end(args2);
  1925. if (reserve_size > PRINTKRB_RECORD_MAX)
  1926. reserve_size = PRINTKRB_RECORD_MAX;
  1927. /* Extract log level or control flags. */
  1928. if (facility == 0)
  1929. printk_parse_prefix(&prefix_buf[0], &level, &flags);
  1930. if (level == LOGLEVEL_DEFAULT)
  1931. level = default_message_loglevel;
  1932. if (dev_info)
  1933. flags |= LOG_NEWLINE;
  1934. if (flags & LOG_CONT) {
  1935. prb_rec_init_wr(&r, reserve_size);
  1936. if (prb_reserve_in_last(&e, prb, &r, caller_id, PRINTKRB_RECORD_MAX)) {
  1937. text_len = printk_sprint(&r.text_buf[r.info->text_len], reserve_size,
  1938. facility, &flags, fmt, args);
  1939. r.info->text_len += text_len;
  1940. if (flags & LOG_NEWLINE) {
  1941. r.info->flags |= LOG_NEWLINE;
  1942. prb_final_commit(&e);
  1943. } else {
  1944. prb_commit(&e);
  1945. }
  1946. ret = text_len;
  1947. goto out;
  1948. }
  1949. }
  1950. /*
  1951. * Explicitly initialize the record before every prb_reserve() call.
  1952. * prb_reserve_in_last() and prb_reserve() purposely invalidate the
  1953. * structure when they fail.
  1954. */
  1955. prb_rec_init_wr(&r, reserve_size);
  1956. if (!prb_reserve(&e, prb, &r)) {
  1957. /* truncate the message if it is too long for empty buffer */
  1958. truncate_msg(&reserve_size, &trunc_msg_len);
  1959. prb_rec_init_wr(&r, reserve_size + trunc_msg_len);
  1960. if (!prb_reserve(&e, prb, &r))
  1961. goto out;
  1962. }
  1963. /* fill message */
  1964. text_len = printk_sprint(&r.text_buf[0], reserve_size, facility, &flags, fmt, args);
  1965. if (trunc_msg_len)
  1966. memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
  1967. r.info->text_len = text_len + trunc_msg_len;
  1968. r.info->facility = facility;
  1969. r.info->level = level & 7;
  1970. r.info->flags = flags & 0x1f;
  1971. r.info->ts_nsec = ts_nsec;
  1972. r.info->caller_id = caller_id;
  1973. if (dev_info)
  1974. memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
  1975. /* A message without a trailing newline can be continued. */
  1976. if (!(flags & LOG_NEWLINE))
  1977. prb_commit(&e);
  1978. else
  1979. prb_final_commit(&e);
  1980. ret = text_len + trunc_msg_len;
  1981. out:
  1982. printk_exit_irqrestore(recursion_ptr, irqflags);
  1983. return ret;
  1984. }
  1985. /*
  1986. * This acts as a one-way switch to allow legacy consoles to print from
  1987. * the printk() caller context on a panic CPU. It also attempts to flush
  1988. * the legacy consoles in this context.
  1989. */
  1990. void printk_legacy_allow_panic_sync(void)
  1991. {
  1992. struct console_flush_type ft;
  1993. legacy_allow_panic_sync = true;
  1994. printk_get_console_flush_type(&ft);
  1995. if (ft.legacy_direct) {
  1996. if (console_trylock())
  1997. console_unlock();
  1998. }
  1999. }
  2000. asmlinkage int vprintk_emit(int facility, int level,
  2001. const struct dev_printk_info *dev_info,
  2002. const char *fmt, va_list args)
  2003. {
  2004. struct console_flush_type ft;
  2005. int printed_len;
  2006. /* Suppress unimportant messages after panic happens */
  2007. if (unlikely(suppress_printk))
  2008. return 0;
  2009. /*
  2010. * The messages on the panic CPU are the most important. If
  2011. * non-panic CPUs are generating any messages, they will be
  2012. * silently dropped.
  2013. */
  2014. if (other_cpu_in_panic() && !panic_triggering_all_cpu_backtrace)
  2015. return 0;
  2016. printk_get_console_flush_type(&ft);
  2017. /* If called from the scheduler, we can not call up(). */
  2018. if (level == LOGLEVEL_SCHED) {
  2019. level = LOGLEVEL_DEFAULT;
  2020. ft.legacy_offload |= ft.legacy_direct;
  2021. ft.legacy_direct = false;
  2022. }
  2023. printk_delay(level);
  2024. printed_len = vprintk_store(facility, level, dev_info, fmt, args);
  2025. if (ft.nbcon_atomic)
  2026. nbcon_atomic_flush_pending();
  2027. if (ft.nbcon_offload)
  2028. nbcon_kthreads_wake();
  2029. if (ft.legacy_direct) {
  2030. /*
  2031. * The caller may be holding system-critical or
  2032. * timing-sensitive locks. Disable preemption during
  2033. * printing of all remaining records to all consoles so that
  2034. * this context can return as soon as possible. Hopefully
  2035. * another printk() caller will take over the printing.
  2036. */
  2037. preempt_disable();
  2038. /*
  2039. * Try to acquire and then immediately release the console
  2040. * semaphore. The release will print out buffers. With the
  2041. * spinning variant, this context tries to take over the
  2042. * printing from another printing context.
  2043. */
  2044. if (console_trylock_spinning())
  2045. console_unlock();
  2046. preempt_enable();
  2047. }
  2048. if (ft.legacy_offload)
  2049. defer_console_output();
  2050. else
  2051. wake_up_klogd();
  2052. return printed_len;
  2053. }
  2054. EXPORT_SYMBOL(vprintk_emit);
  2055. int vprintk_default(const char *fmt, va_list args)
  2056. {
  2057. return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
  2058. }
  2059. EXPORT_SYMBOL_GPL(vprintk_default);
  2060. asmlinkage __visible int _printk(const char *fmt, ...)
  2061. {
  2062. va_list args;
  2063. int r;
  2064. va_start(args, fmt);
  2065. r = vprintk(fmt, args);
  2066. va_end(args);
  2067. return r;
  2068. }
  2069. EXPORT_SYMBOL(_printk);
  2070. static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress);
  2071. #else /* CONFIG_PRINTK */
  2072. #define printk_time false
  2073. #define prb_read_valid(rb, seq, r) false
  2074. #define prb_first_valid_seq(rb) 0
  2075. #define prb_next_seq(rb) 0
  2076. static u64 syslog_seq;
  2077. static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress) { return true; }
  2078. #endif /* CONFIG_PRINTK */
  2079. #ifdef CONFIG_EARLY_PRINTK
  2080. struct console *early_console;
  2081. asmlinkage __visible void early_printk(const char *fmt, ...)
  2082. {
  2083. va_list ap;
  2084. char buf[512];
  2085. int n;
  2086. if (!early_console)
  2087. return;
  2088. va_start(ap, fmt);
  2089. n = vscnprintf(buf, sizeof(buf), fmt, ap);
  2090. va_end(ap);
  2091. early_console->write(early_console, buf, n);
  2092. }
  2093. #endif
  2094. static void set_user_specified(struct console_cmdline *c, bool user_specified)
  2095. {
  2096. if (!user_specified)
  2097. return;
  2098. /*
  2099. * @c console was defined by the user on the command line.
  2100. * Do not clear when added twice also by SPCR or the device tree.
  2101. */
  2102. c->user_specified = true;
  2103. /* At least one console defined by the user on the command line. */
  2104. console_set_on_cmdline = 1;
  2105. }
  2106. static int __add_preferred_console(const char *name, const short idx,
  2107. const char *devname, char *options,
  2108. char *brl_options, bool user_specified)
  2109. {
  2110. struct console_cmdline *c;
  2111. int i;
  2112. if (!name && !devname)
  2113. return -EINVAL;
  2114. /*
  2115. * We use a signed short index for struct console for device drivers to
  2116. * indicate a not yet assigned index or port. However, a negative index
  2117. * value is not valid when the console name and index are defined on
  2118. * the command line.
  2119. */
  2120. if (name && idx < 0)
  2121. return -EINVAL;
  2122. /*
  2123. * See if this tty is not yet registered, and
  2124. * if we have a slot free.
  2125. */
  2126. for (i = 0, c = console_cmdline;
  2127. i < MAX_CMDLINECONSOLES && (c->name[0] || c->devname[0]);
  2128. i++, c++) {
  2129. if ((name && strcmp(c->name, name) == 0 && c->index == idx) ||
  2130. (devname && strcmp(c->devname, devname) == 0)) {
  2131. if (!brl_options)
  2132. preferred_console = i;
  2133. set_user_specified(c, user_specified);
  2134. return 0;
  2135. }
  2136. }
  2137. if (i == MAX_CMDLINECONSOLES)
  2138. return -E2BIG;
  2139. if (!brl_options)
  2140. preferred_console = i;
  2141. if (name)
  2142. strscpy(c->name, name);
  2143. if (devname)
  2144. strscpy(c->devname, devname);
  2145. c->options = options;
  2146. set_user_specified(c, user_specified);
  2147. braille_set_options(c, brl_options);
  2148. c->index = idx;
  2149. return 0;
  2150. }
  2151. static int __init console_msg_format_setup(char *str)
  2152. {
  2153. if (!strcmp(str, "syslog"))
  2154. console_msg_format = MSG_FORMAT_SYSLOG;
  2155. if (!strcmp(str, "default"))
  2156. console_msg_format = MSG_FORMAT_DEFAULT;
  2157. return 1;
  2158. }
  2159. __setup("console_msg_format=", console_msg_format_setup);
  2160. /*
  2161. * Set up a console. Called via do_early_param() in init/main.c
  2162. * for each "console=" parameter in the boot command line.
  2163. */
  2164. static int __init console_setup(char *str)
  2165. {
  2166. static_assert(sizeof(console_cmdline[0].devname) >= sizeof(console_cmdline[0].name) + 4);
  2167. char buf[sizeof(console_cmdline[0].devname)];
  2168. char *brl_options = NULL;
  2169. char *ttyname = NULL;
  2170. char *devname = NULL;
  2171. char *options;
  2172. char *s;
  2173. int idx;
  2174. /*
  2175. * console="" or console=null have been suggested as a way to
  2176. * disable console output. Use ttynull that has been created
  2177. * for exactly this purpose.
  2178. */
  2179. if (str[0] == 0 || strcmp(str, "null") == 0) {
  2180. __add_preferred_console("ttynull", 0, NULL, NULL, NULL, true);
  2181. return 1;
  2182. }
  2183. if (_braille_console_setup(&str, &brl_options))
  2184. return 1;
  2185. /* For a DEVNAME:0.0 style console the character device is unknown early */
  2186. if (strchr(str, ':'))
  2187. devname = buf;
  2188. else
  2189. ttyname = buf;
  2190. /*
  2191. * Decode str into name, index, options.
  2192. */
  2193. if (ttyname && isdigit(str[0]))
  2194. scnprintf(buf, sizeof(buf), "ttyS%s", str);
  2195. else
  2196. strscpy(buf, str);
  2197. options = strchr(str, ',');
  2198. if (options)
  2199. *(options++) = 0;
  2200. #ifdef __sparc__
  2201. if (!strcmp(str, "ttya"))
  2202. strscpy(buf, "ttyS0");
  2203. if (!strcmp(str, "ttyb"))
  2204. strscpy(buf, "ttyS1");
  2205. #endif
  2206. for (s = buf; *s; s++)
  2207. if ((ttyname && isdigit(*s)) || *s == ',')
  2208. break;
  2209. /* @idx will get defined when devname matches. */
  2210. if (devname)
  2211. idx = -1;
  2212. else
  2213. idx = simple_strtoul(s, NULL, 10);
  2214. *s = 0;
  2215. __add_preferred_console(ttyname, idx, devname, options, brl_options, true);
  2216. return 1;
  2217. }
  2218. __setup("console=", console_setup);
  2219. /**
  2220. * add_preferred_console - add a device to the list of preferred consoles.
  2221. * @name: device name
  2222. * @idx: device index
  2223. * @options: options for this console
  2224. *
  2225. * The last preferred console added will be used for kernel messages
  2226. * and stdin/out/err for init. Normally this is used by console_setup
  2227. * above to handle user-supplied console arguments; however it can also
  2228. * be used by arch-specific code either to override the user or more
  2229. * commonly to provide a default console (ie from PROM variables) when
  2230. * the user has not supplied one.
  2231. */
  2232. int add_preferred_console(const char *name, const short idx, char *options)
  2233. {
  2234. return __add_preferred_console(name, idx, NULL, options, NULL, false);
  2235. }
  2236. /**
  2237. * match_devname_and_update_preferred_console - Update a preferred console
  2238. * when matching devname is found.
  2239. * @devname: DEVNAME:0.0 style device name
  2240. * @name: Name of the corresponding console driver, e.g. "ttyS"
  2241. * @idx: Console index, e.g. port number.
  2242. *
  2243. * The function checks whether a device with the given @devname is
  2244. * preferred via the console=DEVNAME:0.0 command line option.
  2245. * It fills the missing console driver name and console index
  2246. * so that a later register_console() call could find (match)
  2247. * and enable this device.
  2248. *
  2249. * It might be used when a driver subsystem initializes particular
  2250. * devices with already known DEVNAME:0.0 style names. And it
  2251. * could predict which console driver name and index this device
  2252. * would later get associated with.
  2253. *
  2254. * Return: 0 on success, negative error code on failure.
  2255. */
  2256. int match_devname_and_update_preferred_console(const char *devname,
  2257. const char *name,
  2258. const short idx)
  2259. {
  2260. struct console_cmdline *c = console_cmdline;
  2261. int i;
  2262. if (!devname || !strlen(devname) || !name || !strlen(name) || idx < 0)
  2263. return -EINVAL;
  2264. for (i = 0; i < MAX_CMDLINECONSOLES && (c->name[0] || c->devname[0]);
  2265. i++, c++) {
  2266. if (!strcmp(devname, c->devname)) {
  2267. pr_info("associate the preferred console \"%s\" with \"%s%d\"\n",
  2268. devname, name, idx);
  2269. strscpy(c->name, name);
  2270. c->index = idx;
  2271. return 0;
  2272. }
  2273. }
  2274. return -ENOENT;
  2275. }
  2276. EXPORT_SYMBOL_GPL(match_devname_and_update_preferred_console);
  2277. bool console_suspend_enabled = true;
  2278. EXPORT_SYMBOL(console_suspend_enabled);
  2279. static int __init console_suspend_disable(char *str)
  2280. {
  2281. console_suspend_enabled = false;
  2282. return 1;
  2283. }
  2284. __setup("no_console_suspend", console_suspend_disable);
  2285. module_param_named(console_suspend, console_suspend_enabled,
  2286. bool, S_IRUGO | S_IWUSR);
  2287. MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
  2288. " and hibernate operations");
  2289. static bool printk_console_no_auto_verbose;
  2290. void console_verbose(void)
  2291. {
  2292. if (console_loglevel && !printk_console_no_auto_verbose)
  2293. console_loglevel = CONSOLE_LOGLEVEL_MOTORMOUTH;
  2294. }
  2295. EXPORT_SYMBOL_GPL(console_verbose);
  2296. module_param_named(console_no_auto_verbose, printk_console_no_auto_verbose, bool, 0644);
  2297. MODULE_PARM_DESC(console_no_auto_verbose, "Disable console loglevel raise to highest on oops/panic/etc");
  2298. /**
  2299. * suspend_console - suspend the console subsystem
  2300. *
  2301. * This disables printk() while we go into suspend states
  2302. */
  2303. void suspend_console(void)
  2304. {
  2305. struct console *con;
  2306. if (!console_suspend_enabled)
  2307. return;
  2308. pr_info("Suspending console(s) (use no_console_suspend to debug)\n");
  2309. pr_flush(1000, true);
  2310. console_list_lock();
  2311. for_each_console(con)
  2312. console_srcu_write_flags(con, con->flags | CON_SUSPENDED);
  2313. console_list_unlock();
  2314. /*
  2315. * Ensure that all SRCU list walks have completed. All printing
  2316. * contexts must be able to see that they are suspended so that it
  2317. * is guaranteed that all printing has stopped when this function
  2318. * completes.
  2319. */
  2320. synchronize_srcu(&console_srcu);
  2321. }
  2322. void resume_console(void)
  2323. {
  2324. struct console_flush_type ft;
  2325. struct console *con;
  2326. if (!console_suspend_enabled)
  2327. return;
  2328. console_list_lock();
  2329. for_each_console(con)
  2330. console_srcu_write_flags(con, con->flags & ~CON_SUSPENDED);
  2331. console_list_unlock();
  2332. /*
  2333. * Ensure that all SRCU list walks have completed. All printing
  2334. * contexts must be able to see they are no longer suspended so
  2335. * that they are guaranteed to wake up and resume printing.
  2336. */
  2337. synchronize_srcu(&console_srcu);
  2338. printk_get_console_flush_type(&ft);
  2339. if (ft.nbcon_offload)
  2340. nbcon_kthreads_wake();
  2341. if (ft.legacy_offload)
  2342. defer_console_output();
  2343. pr_flush(1000, true);
  2344. }
  2345. /**
  2346. * console_cpu_notify - print deferred console messages after CPU hotplug
  2347. * @cpu: unused
  2348. *
  2349. * If printk() is called from a CPU that is not online yet, the messages
  2350. * will be printed on the console only if there are CON_ANYTIME consoles.
  2351. * This function is called when a new CPU comes online (or fails to come
  2352. * up) or goes offline.
  2353. */
  2354. static int console_cpu_notify(unsigned int cpu)
  2355. {
  2356. struct console_flush_type ft;
  2357. if (!cpuhp_tasks_frozen) {
  2358. printk_get_console_flush_type(&ft);
  2359. if (ft.nbcon_atomic)
  2360. nbcon_atomic_flush_pending();
  2361. if (ft.legacy_direct) {
  2362. if (console_trylock())
  2363. console_unlock();
  2364. }
  2365. }
  2366. return 0;
  2367. }
  2368. /**
  2369. * console_lock - block the console subsystem from printing
  2370. *
  2371. * Acquires a lock which guarantees that no consoles will
  2372. * be in or enter their write() callback.
  2373. *
  2374. * Can sleep, returns nothing.
  2375. */
  2376. void console_lock(void)
  2377. {
  2378. might_sleep();
  2379. /* On panic, the console_lock must be left to the panic cpu. */
  2380. while (other_cpu_in_panic())
  2381. msleep(1000);
  2382. down_console_sem();
  2383. console_locked = 1;
  2384. console_may_schedule = 1;
  2385. }
  2386. EXPORT_SYMBOL(console_lock);
  2387. /**
  2388. * console_trylock - try to block the console subsystem from printing
  2389. *
  2390. * Try to acquire a lock which guarantees that no consoles will
  2391. * be in or enter their write() callback.
  2392. *
  2393. * returns 1 on success, and 0 on failure to acquire the lock.
  2394. */
  2395. int console_trylock(void)
  2396. {
  2397. /* On panic, the console_lock must be left to the panic cpu. */
  2398. if (other_cpu_in_panic())
  2399. return 0;
  2400. if (down_trylock_console_sem())
  2401. return 0;
  2402. console_locked = 1;
  2403. console_may_schedule = 0;
  2404. return 1;
  2405. }
  2406. EXPORT_SYMBOL(console_trylock);
  2407. int is_console_locked(void)
  2408. {
  2409. return console_locked;
  2410. }
  2411. EXPORT_SYMBOL(is_console_locked);
  2412. static void __console_unlock(void)
  2413. {
  2414. console_locked = 0;
  2415. up_console_sem();
  2416. }
  2417. #ifdef CONFIG_PRINTK
  2418. /*
  2419. * Prepend the message in @pmsg->pbufs->outbuf. This is achieved by shifting
  2420. * the existing message over and inserting the scratchbuf message.
  2421. *
  2422. * @pmsg is the original printk message.
  2423. * @fmt is the printf format of the message which will prepend the existing one.
  2424. *
  2425. * If there is not enough space in @pmsg->pbufs->outbuf, the existing
  2426. * message text will be sufficiently truncated.
  2427. *
  2428. * If @pmsg->pbufs->outbuf is modified, @pmsg->outbuf_len is updated.
  2429. */
  2430. __printf(2, 3)
  2431. static void console_prepend_message(struct printk_message *pmsg, const char *fmt, ...)
  2432. {
  2433. struct printk_buffers *pbufs = pmsg->pbufs;
  2434. const size_t scratchbuf_sz = sizeof(pbufs->scratchbuf);
  2435. const size_t outbuf_sz = sizeof(pbufs->outbuf);
  2436. char *scratchbuf = &pbufs->scratchbuf[0];
  2437. char *outbuf = &pbufs->outbuf[0];
  2438. va_list args;
  2439. size_t len;
  2440. va_start(args, fmt);
  2441. len = vscnprintf(scratchbuf, scratchbuf_sz, fmt, args);
  2442. va_end(args);
  2443. /*
  2444. * Make sure outbuf is sufficiently large before prepending.
  2445. * Keep at least the prefix when the message must be truncated.
  2446. * It is a rather theoretical problem when someone tries to
  2447. * use a minimalist buffer.
  2448. */
  2449. if (WARN_ON_ONCE(len + PRINTK_PREFIX_MAX >= outbuf_sz))
  2450. return;
  2451. if (pmsg->outbuf_len + len >= outbuf_sz) {
  2452. /* Truncate the message, but keep it terminated. */
  2453. pmsg->outbuf_len = outbuf_sz - (len + 1);
  2454. outbuf[pmsg->outbuf_len] = 0;
  2455. }
  2456. memmove(outbuf + len, outbuf, pmsg->outbuf_len + 1);
  2457. memcpy(outbuf, scratchbuf, len);
  2458. pmsg->outbuf_len += len;
  2459. }
  2460. /*
  2461. * Prepend the message in @pmsg->pbufs->outbuf with a "dropped message".
  2462. * @pmsg->outbuf_len is updated appropriately.
  2463. *
  2464. * @pmsg is the printk message to prepend.
  2465. *
  2466. * @dropped is the dropped count to report in the dropped message.
  2467. */
  2468. void console_prepend_dropped(struct printk_message *pmsg, unsigned long dropped)
  2469. {
  2470. console_prepend_message(pmsg, "** %lu printk messages dropped **\n", dropped);
  2471. }
  2472. /*
  2473. * Prepend the message in @pmsg->pbufs->outbuf with a "replay message".
  2474. * @pmsg->outbuf_len is updated appropriately.
  2475. *
  2476. * @pmsg is the printk message to prepend.
  2477. */
  2478. void console_prepend_replay(struct printk_message *pmsg)
  2479. {
  2480. console_prepend_message(pmsg, "** replaying previous printk message **\n");
  2481. }
  2482. /*
  2483. * Read and format the specified record (or a later record if the specified
  2484. * record is not available).
  2485. *
  2486. * @pmsg will contain the formatted result. @pmsg->pbufs must point to a
  2487. * struct printk_buffers.
  2488. *
  2489. * @seq is the record to read and format. If it is not available, the next
  2490. * valid record is read.
  2491. *
  2492. * @is_extended specifies if the message should be formatted for extended
  2493. * console output.
  2494. *
  2495. * @may_supress specifies if records may be skipped based on loglevel.
  2496. *
  2497. * Returns false if no record is available. Otherwise true and all fields
  2498. * of @pmsg are valid. (See the documentation of struct printk_message
  2499. * for information about the @pmsg fields.)
  2500. */
  2501. bool printk_get_next_message(struct printk_message *pmsg, u64 seq,
  2502. bool is_extended, bool may_suppress)
  2503. {
  2504. struct printk_buffers *pbufs = pmsg->pbufs;
  2505. const size_t scratchbuf_sz = sizeof(pbufs->scratchbuf);
  2506. const size_t outbuf_sz = sizeof(pbufs->outbuf);
  2507. char *scratchbuf = &pbufs->scratchbuf[0];
  2508. char *outbuf = &pbufs->outbuf[0];
  2509. struct printk_info info;
  2510. struct printk_record r;
  2511. size_t len = 0;
  2512. /*
  2513. * Formatting extended messages requires a separate buffer, so use the
  2514. * scratch buffer to read in the ringbuffer text.
  2515. *
  2516. * Formatting normal messages is done in-place, so read the ringbuffer
  2517. * text directly into the output buffer.
  2518. */
  2519. if (is_extended)
  2520. prb_rec_init_rd(&r, &info, scratchbuf, scratchbuf_sz);
  2521. else
  2522. prb_rec_init_rd(&r, &info, outbuf, outbuf_sz);
  2523. if (!prb_read_valid(prb, seq, &r))
  2524. return false;
  2525. pmsg->seq = r.info->seq;
  2526. pmsg->dropped = r.info->seq - seq;
  2527. /* Skip record that has level above the console loglevel. */
  2528. if (may_suppress && suppress_message_printing(r.info->level))
  2529. goto out;
  2530. if (is_extended) {
  2531. len = info_print_ext_header(outbuf, outbuf_sz, r.info);
  2532. len += msg_print_ext_body(outbuf + len, outbuf_sz - len,
  2533. &r.text_buf[0], r.info->text_len, &r.info->dev_info);
  2534. } else {
  2535. len = record_print_text(&r, console_msg_format & MSG_FORMAT_SYSLOG, printk_time);
  2536. }
  2537. out:
  2538. pmsg->outbuf_len = len;
  2539. return true;
  2540. }
  2541. /*
  2542. * Legacy console printing from printk() caller context does not respect
  2543. * raw_spinlock/spinlock nesting. For !PREEMPT_RT the lockdep warning is a
  2544. * false positive. For PREEMPT_RT the false positive condition does not
  2545. * occur.
  2546. *
  2547. * This map is used to temporarily establish LD_WAIT_SLEEP context for the
  2548. * console write() callback when legacy printing to avoid false positive
  2549. * lockdep complaints, thus allowing lockdep to continue to function for
  2550. * real issues.
  2551. */
  2552. #ifdef CONFIG_PREEMPT_RT
  2553. static inline void printk_legacy_allow_spinlock_enter(void) { }
  2554. static inline void printk_legacy_allow_spinlock_exit(void) { }
  2555. #else
  2556. static DEFINE_WAIT_OVERRIDE_MAP(printk_legacy_map, LD_WAIT_SLEEP);
  2557. static inline void printk_legacy_allow_spinlock_enter(void)
  2558. {
  2559. lock_map_acquire_try(&printk_legacy_map);
  2560. }
  2561. static inline void printk_legacy_allow_spinlock_exit(void)
  2562. {
  2563. lock_map_release(&printk_legacy_map);
  2564. }
  2565. #endif /* CONFIG_PREEMPT_RT */
  2566. /*
  2567. * Used as the printk buffers for non-panic, serialized console printing.
  2568. * This is for legacy (!CON_NBCON) as well as all boot (CON_BOOT) consoles.
  2569. * Its usage requires the console_lock held.
  2570. */
  2571. struct printk_buffers printk_shared_pbufs;
  2572. /*
  2573. * Print one record for the given console. The record printed is whatever
  2574. * record is the next available record for the given console.
  2575. *
  2576. * @handover will be set to true if a printk waiter has taken over the
  2577. * console_lock, in which case the caller is no longer holding both the
  2578. * console_lock and the SRCU read lock. Otherwise it is set to false.
  2579. *
  2580. * @cookie is the cookie from the SRCU read lock.
  2581. *
  2582. * Returns false if the given console has no next record to print, otherwise
  2583. * true.
  2584. *
  2585. * Requires the console_lock and the SRCU read lock.
  2586. */
  2587. static bool console_emit_next_record(struct console *con, bool *handover, int cookie)
  2588. {
  2589. bool is_extended = console_srcu_read_flags(con) & CON_EXTENDED;
  2590. char *outbuf = &printk_shared_pbufs.outbuf[0];
  2591. struct printk_message pmsg = {
  2592. .pbufs = &printk_shared_pbufs,
  2593. };
  2594. unsigned long flags;
  2595. *handover = false;
  2596. if (!printk_get_next_message(&pmsg, con->seq, is_extended, true))
  2597. return false;
  2598. con->dropped += pmsg.dropped;
  2599. /* Skip messages of formatted length 0. */
  2600. if (pmsg.outbuf_len == 0) {
  2601. con->seq = pmsg.seq + 1;
  2602. goto skip;
  2603. }
  2604. if (con->dropped && !is_extended) {
  2605. console_prepend_dropped(&pmsg, con->dropped);
  2606. con->dropped = 0;
  2607. }
  2608. /* Write everything out to the hardware. */
  2609. if (force_legacy_kthread() && !panic_in_progress()) {
  2610. /*
  2611. * With forced threading this function is in a task context
  2612. * (either legacy kthread or get_init_console_seq()). There
  2613. * is no need for concern about printk reentrance, handovers,
  2614. * or lockdep complaints.
  2615. */
  2616. con->write(con, outbuf, pmsg.outbuf_len);
  2617. con->seq = pmsg.seq + 1;
  2618. } else {
  2619. /*
  2620. * While actively printing out messages, if another printk()
  2621. * were to occur on another CPU, it may wait for this one to
  2622. * finish. This task can not be preempted if there is a
  2623. * waiter waiting to take over.
  2624. *
  2625. * Interrupts are disabled because the hand over to a waiter
  2626. * must not be interrupted until the hand over is completed
  2627. * (@console_waiter is cleared).
  2628. */
  2629. printk_safe_enter_irqsave(flags);
  2630. console_lock_spinning_enable();
  2631. /* Do not trace print latency. */
  2632. stop_critical_timings();
  2633. printk_legacy_allow_spinlock_enter();
  2634. con->write(con, outbuf, pmsg.outbuf_len);
  2635. printk_legacy_allow_spinlock_exit();
  2636. start_critical_timings();
  2637. con->seq = pmsg.seq + 1;
  2638. *handover = console_lock_spinning_disable_and_check(cookie);
  2639. printk_safe_exit_irqrestore(flags);
  2640. }
  2641. skip:
  2642. return true;
  2643. }
  2644. #else
  2645. static bool console_emit_next_record(struct console *con, bool *handover, int cookie)
  2646. {
  2647. *handover = false;
  2648. return false;
  2649. }
  2650. static inline void printk_kthreads_check_locked(void) { }
  2651. #endif /* CONFIG_PRINTK */
  2652. /*
  2653. * Print out all remaining records to all consoles.
  2654. *
  2655. * @do_cond_resched is set by the caller. It can be true only in schedulable
  2656. * context.
  2657. *
  2658. * @next_seq is set to the sequence number after the last available record.
  2659. * The value is valid only when this function returns true. It means that all
  2660. * usable consoles are completely flushed.
  2661. *
  2662. * @handover will be set to true if a printk waiter has taken over the
  2663. * console_lock, in which case the caller is no longer holding the
  2664. * console_lock. Otherwise it is set to false.
  2665. *
  2666. * Returns true when there was at least one usable console and all messages
  2667. * were flushed to all usable consoles. A returned false informs the caller
  2668. * that everything was not flushed (either there were no usable consoles or
  2669. * another context has taken over printing or it is a panic situation and this
  2670. * is not the panic CPU). Regardless the reason, the caller should assume it
  2671. * is not useful to immediately try again.
  2672. *
  2673. * Requires the console_lock.
  2674. */
  2675. static bool console_flush_all(bool do_cond_resched, u64 *next_seq, bool *handover)
  2676. {
  2677. struct console_flush_type ft;
  2678. bool any_usable = false;
  2679. struct console *con;
  2680. bool any_progress;
  2681. int cookie;
  2682. *next_seq = 0;
  2683. *handover = false;
  2684. do {
  2685. any_progress = false;
  2686. printk_get_console_flush_type(&ft);
  2687. cookie = console_srcu_read_lock();
  2688. for_each_console_srcu(con) {
  2689. short flags = console_srcu_read_flags(con);
  2690. u64 printk_seq;
  2691. bool progress;
  2692. /*
  2693. * console_flush_all() is only responsible for nbcon
  2694. * consoles when the nbcon consoles cannot print via
  2695. * their atomic or threaded flushing.
  2696. */
  2697. if ((flags & CON_NBCON) && (ft.nbcon_atomic || ft.nbcon_offload))
  2698. continue;
  2699. if (!console_is_usable(con, flags, !do_cond_resched))
  2700. continue;
  2701. any_usable = true;
  2702. if (flags & CON_NBCON) {
  2703. progress = nbcon_legacy_emit_next_record(con, handover, cookie,
  2704. !do_cond_resched);
  2705. printk_seq = nbcon_seq_read(con);
  2706. } else {
  2707. progress = console_emit_next_record(con, handover, cookie);
  2708. printk_seq = con->seq;
  2709. }
  2710. /*
  2711. * If a handover has occurred, the SRCU read lock
  2712. * is already released.
  2713. */
  2714. if (*handover)
  2715. return false;
  2716. /* Track the next of the highest seq flushed. */
  2717. if (printk_seq > *next_seq)
  2718. *next_seq = printk_seq;
  2719. if (!progress)
  2720. continue;
  2721. any_progress = true;
  2722. /* Allow panic_cpu to take over the consoles safely. */
  2723. if (other_cpu_in_panic())
  2724. goto abandon;
  2725. if (do_cond_resched)
  2726. cond_resched();
  2727. }
  2728. console_srcu_read_unlock(cookie);
  2729. } while (any_progress);
  2730. return any_usable;
  2731. abandon:
  2732. console_srcu_read_unlock(cookie);
  2733. return false;
  2734. }
  2735. static void __console_flush_and_unlock(void)
  2736. {
  2737. bool do_cond_resched;
  2738. bool handover;
  2739. bool flushed;
  2740. u64 next_seq;
  2741. /*
  2742. * Console drivers are called with interrupts disabled, so
  2743. * @console_may_schedule should be cleared before; however, we may
  2744. * end up dumping a lot of lines, for example, if called from
  2745. * console registration path, and should invoke cond_resched()
  2746. * between lines if allowable. Not doing so can cause a very long
  2747. * scheduling stall on a slow console leading to RCU stall and
  2748. * softlockup warnings which exacerbate the issue with more
  2749. * messages practically incapacitating the system. Therefore, create
  2750. * a local to use for the printing loop.
  2751. */
  2752. do_cond_resched = console_may_schedule;
  2753. do {
  2754. console_may_schedule = 0;
  2755. flushed = console_flush_all(do_cond_resched, &next_seq, &handover);
  2756. if (!handover)
  2757. __console_unlock();
  2758. /*
  2759. * Abort if there was a failure to flush all messages to all
  2760. * usable consoles. Either it is not possible to flush (in
  2761. * which case it would be an infinite loop of retrying) or
  2762. * another context has taken over printing.
  2763. */
  2764. if (!flushed)
  2765. break;
  2766. /*
  2767. * Some context may have added new records after
  2768. * console_flush_all() but before unlocking the console.
  2769. * Re-check if there is a new record to flush. If the trylock
  2770. * fails, another context is already handling the printing.
  2771. */
  2772. } while (prb_read_valid(prb, next_seq, NULL) && console_trylock());
  2773. }
  2774. /**
  2775. * console_unlock - unblock the legacy console subsystem from printing
  2776. *
  2777. * Releases the console_lock which the caller holds to block printing of
  2778. * the legacy console subsystem.
  2779. *
  2780. * While the console_lock was held, console output may have been buffered
  2781. * by printk(). If this is the case, console_unlock() emits the output on
  2782. * legacy consoles prior to releasing the lock.
  2783. *
  2784. * console_unlock(); may be called from any context.
  2785. */
  2786. void console_unlock(void)
  2787. {
  2788. struct console_flush_type ft;
  2789. printk_get_console_flush_type(&ft);
  2790. if (ft.legacy_direct)
  2791. __console_flush_and_unlock();
  2792. else
  2793. __console_unlock();
  2794. }
  2795. EXPORT_SYMBOL(console_unlock);
  2796. /**
  2797. * console_conditional_schedule - yield the CPU if required
  2798. *
  2799. * If the console code is currently allowed to sleep, and
  2800. * if this CPU should yield the CPU to another task, do
  2801. * so here.
  2802. *
  2803. * Must be called within console_lock();.
  2804. */
  2805. void __sched console_conditional_schedule(void)
  2806. {
  2807. if (console_may_schedule)
  2808. cond_resched();
  2809. }
  2810. EXPORT_SYMBOL(console_conditional_schedule);
  2811. void console_unblank(void)
  2812. {
  2813. bool found_unblank = false;
  2814. struct console *c;
  2815. int cookie;
  2816. /*
  2817. * First check if there are any consoles implementing the unblank()
  2818. * callback. If not, there is no reason to continue and take the
  2819. * console lock, which in particular can be dangerous if
  2820. * @oops_in_progress is set.
  2821. */
  2822. cookie = console_srcu_read_lock();
  2823. for_each_console_srcu(c) {
  2824. short flags = console_srcu_read_flags(c);
  2825. if (flags & CON_SUSPENDED)
  2826. continue;
  2827. if ((flags & CON_ENABLED) && c->unblank) {
  2828. found_unblank = true;
  2829. break;
  2830. }
  2831. }
  2832. console_srcu_read_unlock(cookie);
  2833. if (!found_unblank)
  2834. return;
  2835. /*
  2836. * Stop console printing because the unblank() callback may
  2837. * assume the console is not within its write() callback.
  2838. *
  2839. * If @oops_in_progress is set, this may be an atomic context.
  2840. * In that case, attempt a trylock as best-effort.
  2841. */
  2842. if (oops_in_progress) {
  2843. /* Semaphores are not NMI-safe. */
  2844. if (in_nmi())
  2845. return;
  2846. /*
  2847. * Attempting to trylock the console lock can deadlock
  2848. * if another CPU was stopped while modifying the
  2849. * semaphore. "Hope and pray" that this is not the
  2850. * current situation.
  2851. */
  2852. if (down_trylock_console_sem() != 0)
  2853. return;
  2854. } else
  2855. console_lock();
  2856. console_locked = 1;
  2857. console_may_schedule = 0;
  2858. cookie = console_srcu_read_lock();
  2859. for_each_console_srcu(c) {
  2860. short flags = console_srcu_read_flags(c);
  2861. if (flags & CON_SUSPENDED)
  2862. continue;
  2863. if ((flags & CON_ENABLED) && c->unblank)
  2864. c->unblank();
  2865. }
  2866. console_srcu_read_unlock(cookie);
  2867. console_unlock();
  2868. if (!oops_in_progress)
  2869. pr_flush(1000, true);
  2870. }
  2871. /*
  2872. * Rewind all consoles to the oldest available record.
  2873. *
  2874. * IMPORTANT: The function is safe only when called under
  2875. * console_lock(). It is not enforced because
  2876. * it is used as a best effort in panic().
  2877. */
  2878. static void __console_rewind_all(void)
  2879. {
  2880. struct console *c;
  2881. short flags;
  2882. int cookie;
  2883. u64 seq;
  2884. seq = prb_first_valid_seq(prb);
  2885. cookie = console_srcu_read_lock();
  2886. for_each_console_srcu(c) {
  2887. flags = console_srcu_read_flags(c);
  2888. if (flags & CON_NBCON) {
  2889. nbcon_seq_force(c, seq);
  2890. } else {
  2891. /*
  2892. * This assignment is safe only when called under
  2893. * console_lock(). On panic, legacy consoles are
  2894. * only best effort.
  2895. */
  2896. c->seq = seq;
  2897. }
  2898. }
  2899. console_srcu_read_unlock(cookie);
  2900. }
  2901. /**
  2902. * console_flush_on_panic - flush console content on panic
  2903. * @mode: flush all messages in buffer or just the pending ones
  2904. *
  2905. * Immediately output all pending messages no matter what.
  2906. */
  2907. void console_flush_on_panic(enum con_flush_mode mode)
  2908. {
  2909. struct console_flush_type ft;
  2910. bool handover;
  2911. u64 next_seq;
  2912. /*
  2913. * Ignore the console lock and flush out the messages. Attempting a
  2914. * trylock would not be useful because:
  2915. *
  2916. * - if it is contended, it must be ignored anyway
  2917. * - console_lock() and console_trylock() block and fail
  2918. * respectively in panic for non-panic CPUs
  2919. * - semaphores are not NMI-safe
  2920. */
  2921. /*
  2922. * If another context is holding the console lock,
  2923. * @console_may_schedule might be set. Clear it so that
  2924. * this context does not call cond_resched() while flushing.
  2925. */
  2926. console_may_schedule = 0;
  2927. if (mode == CONSOLE_REPLAY_ALL)
  2928. __console_rewind_all();
  2929. printk_get_console_flush_type(&ft);
  2930. if (ft.nbcon_atomic)
  2931. nbcon_atomic_flush_pending();
  2932. /* Flush legacy consoles once allowed, even when dangerous. */
  2933. if (legacy_allow_panic_sync)
  2934. console_flush_all(false, &next_seq, &handover);
  2935. }
  2936. /*
  2937. * Return the console tty driver structure and its associated index
  2938. */
  2939. struct tty_driver *console_device(int *index)
  2940. {
  2941. struct console *c;
  2942. struct tty_driver *driver = NULL;
  2943. int cookie;
  2944. /*
  2945. * Take console_lock to serialize device() callback with
  2946. * other console operations. For example, fg_console is
  2947. * modified under console_lock when switching vt.
  2948. */
  2949. console_lock();
  2950. cookie = console_srcu_read_lock();
  2951. for_each_console_srcu(c) {
  2952. if (!c->device)
  2953. continue;
  2954. driver = c->device(c, index);
  2955. if (driver)
  2956. break;
  2957. }
  2958. console_srcu_read_unlock(cookie);
  2959. console_unlock();
  2960. return driver;
  2961. }
  2962. /*
  2963. * Prevent further output on the passed console device so that (for example)
  2964. * serial drivers can disable console output before suspending a port, and can
  2965. * re-enable output afterwards.
  2966. */
  2967. void console_stop(struct console *console)
  2968. {
  2969. __pr_flush(console, 1000, true);
  2970. console_list_lock();
  2971. console_srcu_write_flags(console, console->flags & ~CON_ENABLED);
  2972. console_list_unlock();
  2973. /*
  2974. * Ensure that all SRCU list walks have completed. All contexts must
  2975. * be able to see that this console is disabled so that (for example)
  2976. * the caller can suspend the port without risk of another context
  2977. * using the port.
  2978. */
  2979. synchronize_srcu(&console_srcu);
  2980. }
  2981. EXPORT_SYMBOL(console_stop);
  2982. void console_start(struct console *console)
  2983. {
  2984. struct console_flush_type ft;
  2985. bool is_nbcon;
  2986. console_list_lock();
  2987. console_srcu_write_flags(console, console->flags | CON_ENABLED);
  2988. is_nbcon = console->flags & CON_NBCON;
  2989. console_list_unlock();
  2990. /*
  2991. * Ensure that all SRCU list walks have completed. The related
  2992. * printing context must be able to see it is enabled so that
  2993. * it is guaranteed to wake up and resume printing.
  2994. */
  2995. synchronize_srcu(&console_srcu);
  2996. printk_get_console_flush_type(&ft);
  2997. if (is_nbcon && ft.nbcon_offload)
  2998. nbcon_kthread_wake(console);
  2999. else if (ft.legacy_offload)
  3000. defer_console_output();
  3001. __pr_flush(console, 1000, true);
  3002. }
  3003. EXPORT_SYMBOL(console_start);
  3004. #ifdef CONFIG_PRINTK
  3005. static int unregister_console_locked(struct console *console);
  3006. /* True when system boot is far enough to create printer threads. */
  3007. static bool printk_kthreads_ready __ro_after_init;
  3008. static struct task_struct *printk_legacy_kthread;
  3009. static bool legacy_kthread_should_wakeup(void)
  3010. {
  3011. struct console_flush_type ft;
  3012. struct console *con;
  3013. bool ret = false;
  3014. int cookie;
  3015. if (kthread_should_stop())
  3016. return true;
  3017. printk_get_console_flush_type(&ft);
  3018. cookie = console_srcu_read_lock();
  3019. for_each_console_srcu(con) {
  3020. short flags = console_srcu_read_flags(con);
  3021. u64 printk_seq;
  3022. /*
  3023. * The legacy printer thread is only responsible for nbcon
  3024. * consoles when the nbcon consoles cannot print via their
  3025. * atomic or threaded flushing.
  3026. */
  3027. if ((flags & CON_NBCON) && (ft.nbcon_atomic || ft.nbcon_offload))
  3028. continue;
  3029. if (!console_is_usable(con, flags, false))
  3030. continue;
  3031. if (flags & CON_NBCON) {
  3032. printk_seq = nbcon_seq_read(con);
  3033. } else {
  3034. /*
  3035. * It is safe to read @seq because only this
  3036. * thread context updates @seq.
  3037. */
  3038. printk_seq = con->seq;
  3039. }
  3040. if (prb_read_valid(prb, printk_seq, NULL)) {
  3041. ret = true;
  3042. break;
  3043. }
  3044. }
  3045. console_srcu_read_unlock(cookie);
  3046. return ret;
  3047. }
  3048. static int legacy_kthread_func(void *unused)
  3049. {
  3050. for (;;) {
  3051. wait_event_interruptible(legacy_wait, legacy_kthread_should_wakeup());
  3052. if (kthread_should_stop())
  3053. break;
  3054. console_lock();
  3055. __console_flush_and_unlock();
  3056. }
  3057. return 0;
  3058. }
  3059. static bool legacy_kthread_create(void)
  3060. {
  3061. struct task_struct *kt;
  3062. lockdep_assert_console_list_lock_held();
  3063. kt = kthread_run(legacy_kthread_func, NULL, "pr/legacy");
  3064. if (WARN_ON(IS_ERR(kt))) {
  3065. pr_err("failed to start legacy printing thread\n");
  3066. return false;
  3067. }
  3068. printk_legacy_kthread = kt;
  3069. /*
  3070. * It is important that console printing threads are scheduled
  3071. * shortly after a printk call and with generous runtime budgets.
  3072. */
  3073. sched_set_normal(printk_legacy_kthread, -20);
  3074. return true;
  3075. }
  3076. /**
  3077. * printk_kthreads_shutdown - shutdown all threaded printers
  3078. *
  3079. * On system shutdown all threaded printers are stopped. This allows printk
  3080. * to transition back to atomic printing, thus providing a robust mechanism
  3081. * for the final shutdown/reboot messages to be output.
  3082. */
  3083. static void printk_kthreads_shutdown(void)
  3084. {
  3085. struct console *con;
  3086. console_list_lock();
  3087. if (printk_kthreads_running) {
  3088. printk_kthreads_running = false;
  3089. for_each_console(con) {
  3090. if (con->flags & CON_NBCON)
  3091. nbcon_kthread_stop(con);
  3092. }
  3093. /*
  3094. * The threads may have been stopped while printing a
  3095. * backlog. Flush any records left over.
  3096. */
  3097. nbcon_atomic_flush_pending();
  3098. }
  3099. console_list_unlock();
  3100. }
  3101. static struct syscore_ops printk_syscore_ops = {
  3102. .shutdown = printk_kthreads_shutdown,
  3103. };
  3104. /*
  3105. * If appropriate, start nbcon kthreads and set @printk_kthreads_running.
  3106. * If any kthreads fail to start, those consoles are unregistered.
  3107. *
  3108. * Must be called under console_list_lock().
  3109. */
  3110. static void printk_kthreads_check_locked(void)
  3111. {
  3112. struct hlist_node *tmp;
  3113. struct console *con;
  3114. lockdep_assert_console_list_lock_held();
  3115. if (!printk_kthreads_ready)
  3116. return;
  3117. if (have_legacy_console || have_boot_console) {
  3118. if (!printk_legacy_kthread &&
  3119. force_legacy_kthread() &&
  3120. !legacy_kthread_create()) {
  3121. /*
  3122. * All legacy consoles must be unregistered. If there
  3123. * are any nbcon consoles, they will set up their own
  3124. * kthread.
  3125. */
  3126. hlist_for_each_entry_safe(con, tmp, &console_list, node) {
  3127. if (con->flags & CON_NBCON)
  3128. continue;
  3129. unregister_console_locked(con);
  3130. }
  3131. }
  3132. } else if (printk_legacy_kthread) {
  3133. kthread_stop(printk_legacy_kthread);
  3134. printk_legacy_kthread = NULL;
  3135. }
  3136. /*
  3137. * Printer threads cannot be started as long as any boot console is
  3138. * registered because there is no way to synchronize the hardware
  3139. * registers between boot console code and regular console code.
  3140. * It can only be known that there will be no new boot consoles when
  3141. * an nbcon console is registered.
  3142. */
  3143. if (have_boot_console || !have_nbcon_console) {
  3144. /* Clear flag in case all nbcon consoles unregistered. */
  3145. printk_kthreads_running = false;
  3146. return;
  3147. }
  3148. if (printk_kthreads_running)
  3149. return;
  3150. hlist_for_each_entry_safe(con, tmp, &console_list, node) {
  3151. if (!(con->flags & CON_NBCON))
  3152. continue;
  3153. if (!nbcon_kthread_create(con))
  3154. unregister_console_locked(con);
  3155. }
  3156. printk_kthreads_running = true;
  3157. }
  3158. static int __init printk_set_kthreads_ready(void)
  3159. {
  3160. register_syscore_ops(&printk_syscore_ops);
  3161. console_list_lock();
  3162. printk_kthreads_ready = true;
  3163. printk_kthreads_check_locked();
  3164. console_list_unlock();
  3165. return 0;
  3166. }
  3167. early_initcall(printk_set_kthreads_ready);
  3168. #endif /* CONFIG_PRINTK */
  3169. static int __read_mostly keep_bootcon;
  3170. static int __init keep_bootcon_setup(char *str)
  3171. {
  3172. keep_bootcon = 1;
  3173. pr_info("debug: skip boot console de-registration.\n");
  3174. return 0;
  3175. }
  3176. early_param("keep_bootcon", keep_bootcon_setup);
  3177. static int console_call_setup(struct console *newcon, char *options)
  3178. {
  3179. int err;
  3180. if (!newcon->setup)
  3181. return 0;
  3182. /* Synchronize with possible boot console. */
  3183. console_lock();
  3184. err = newcon->setup(newcon, options);
  3185. console_unlock();
  3186. return err;
  3187. }
  3188. /*
  3189. * This is called by register_console() to try to match
  3190. * the newly registered console with any of the ones selected
  3191. * by either the command line or add_preferred_console() and
  3192. * setup/enable it.
  3193. *
  3194. * Care need to be taken with consoles that are statically
  3195. * enabled such as netconsole
  3196. */
  3197. static int try_enable_preferred_console(struct console *newcon,
  3198. bool user_specified)
  3199. {
  3200. struct console_cmdline *c;
  3201. int i, err;
  3202. for (i = 0, c = console_cmdline;
  3203. i < MAX_CMDLINECONSOLES && (c->name[0] || c->devname[0]);
  3204. i++, c++) {
  3205. /* Console not yet initialized? */
  3206. if (!c->name[0])
  3207. continue;
  3208. if (c->user_specified != user_specified)
  3209. continue;
  3210. if (!newcon->match ||
  3211. newcon->match(newcon, c->name, c->index, c->options) != 0) {
  3212. /* default matching */
  3213. BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
  3214. if (strcmp(c->name, newcon->name) != 0)
  3215. continue;
  3216. if (newcon->index >= 0 &&
  3217. newcon->index != c->index)
  3218. continue;
  3219. if (newcon->index < 0)
  3220. newcon->index = c->index;
  3221. if (_braille_register_console(newcon, c))
  3222. return 0;
  3223. err = console_call_setup(newcon, c->options);
  3224. if (err)
  3225. return err;
  3226. }
  3227. newcon->flags |= CON_ENABLED;
  3228. if (i == preferred_console)
  3229. newcon->flags |= CON_CONSDEV;
  3230. return 0;
  3231. }
  3232. /*
  3233. * Some consoles, such as pstore and netconsole, can be enabled even
  3234. * without matching. Accept the pre-enabled consoles only when match()
  3235. * and setup() had a chance to be called.
  3236. */
  3237. if (newcon->flags & CON_ENABLED && c->user_specified == user_specified)
  3238. return 0;
  3239. return -ENOENT;
  3240. }
  3241. /* Try to enable the console unconditionally */
  3242. static void try_enable_default_console(struct console *newcon)
  3243. {
  3244. if (newcon->index < 0)
  3245. newcon->index = 0;
  3246. if (console_call_setup(newcon, NULL) != 0)
  3247. return;
  3248. newcon->flags |= CON_ENABLED;
  3249. if (newcon->device)
  3250. newcon->flags |= CON_CONSDEV;
  3251. }
  3252. /* Return the starting sequence number for a newly registered console. */
  3253. static u64 get_init_console_seq(struct console *newcon, bool bootcon_registered)
  3254. {
  3255. struct console *con;
  3256. bool handover;
  3257. u64 init_seq;
  3258. if (newcon->flags & (CON_PRINTBUFFER | CON_BOOT)) {
  3259. /* Get a consistent copy of @syslog_seq. */
  3260. mutex_lock(&syslog_lock);
  3261. init_seq = syslog_seq;
  3262. mutex_unlock(&syslog_lock);
  3263. } else {
  3264. /* Begin with next message added to ringbuffer. */
  3265. init_seq = prb_next_seq(prb);
  3266. /*
  3267. * If any enabled boot consoles are due to be unregistered
  3268. * shortly, some may not be caught up and may be the same
  3269. * device as @newcon. Since it is not known which boot console
  3270. * is the same device, flush all consoles and, if necessary,
  3271. * start with the message of the enabled boot console that is
  3272. * the furthest behind.
  3273. */
  3274. if (bootcon_registered && !keep_bootcon) {
  3275. /*
  3276. * Hold the console_lock to stop console printing and
  3277. * guarantee safe access to console->seq.
  3278. */
  3279. console_lock();
  3280. /*
  3281. * Flush all consoles and set the console to start at
  3282. * the next unprinted sequence number.
  3283. */
  3284. if (!console_flush_all(true, &init_seq, &handover)) {
  3285. /*
  3286. * Flushing failed. Just choose the lowest
  3287. * sequence of the enabled boot consoles.
  3288. */
  3289. /*
  3290. * If there was a handover, this context no
  3291. * longer holds the console_lock.
  3292. */
  3293. if (handover)
  3294. console_lock();
  3295. init_seq = prb_next_seq(prb);
  3296. for_each_console(con) {
  3297. u64 seq;
  3298. if (!(con->flags & CON_BOOT) ||
  3299. !(con->flags & CON_ENABLED)) {
  3300. continue;
  3301. }
  3302. if (con->flags & CON_NBCON)
  3303. seq = nbcon_seq_read(con);
  3304. else
  3305. seq = con->seq;
  3306. if (seq < init_seq)
  3307. init_seq = seq;
  3308. }
  3309. }
  3310. console_unlock();
  3311. }
  3312. }
  3313. return init_seq;
  3314. }
  3315. #define console_first() \
  3316. hlist_entry(console_list.first, struct console, node)
  3317. static int unregister_console_locked(struct console *console);
  3318. /*
  3319. * The console driver calls this routine during kernel initialization
  3320. * to register the console printing procedure with printk() and to
  3321. * print any messages that were printed by the kernel before the
  3322. * console driver was initialized.
  3323. *
  3324. * This can happen pretty early during the boot process (because of
  3325. * early_printk) - sometimes before setup_arch() completes - be careful
  3326. * of what kernel features are used - they may not be initialised yet.
  3327. *
  3328. * There are two types of consoles - bootconsoles (early_printk) and
  3329. * "real" consoles (everything which is not a bootconsole) which are
  3330. * handled differently.
  3331. * - Any number of bootconsoles can be registered at any time.
  3332. * - As soon as a "real" console is registered, all bootconsoles
  3333. * will be unregistered automatically.
  3334. * - Once a "real" console is registered, any attempt to register a
  3335. * bootconsoles will be rejected
  3336. */
  3337. void register_console(struct console *newcon)
  3338. {
  3339. bool use_device_lock = (newcon->flags & CON_NBCON) && newcon->write_atomic;
  3340. bool bootcon_registered = false;
  3341. bool realcon_registered = false;
  3342. struct console *con;
  3343. unsigned long flags;
  3344. u64 init_seq;
  3345. int err;
  3346. console_list_lock();
  3347. for_each_console(con) {
  3348. if (WARN(con == newcon, "console '%s%d' already registered\n",
  3349. con->name, con->index)) {
  3350. goto unlock;
  3351. }
  3352. if (con->flags & CON_BOOT)
  3353. bootcon_registered = true;
  3354. else
  3355. realcon_registered = true;
  3356. }
  3357. /* Do not register boot consoles when there already is a real one. */
  3358. if ((newcon->flags & CON_BOOT) && realcon_registered) {
  3359. pr_info("Too late to register bootconsole %s%d\n",
  3360. newcon->name, newcon->index);
  3361. goto unlock;
  3362. }
  3363. if (newcon->flags & CON_NBCON) {
  3364. /*
  3365. * Ensure the nbcon console buffers can be allocated
  3366. * before modifying any global data.
  3367. */
  3368. if (!nbcon_alloc(newcon))
  3369. goto unlock;
  3370. }
  3371. /*
  3372. * See if we want to enable this console driver by default.
  3373. *
  3374. * Nope when a console is preferred by the command line, device
  3375. * tree, or SPCR.
  3376. *
  3377. * The first real console with tty binding (driver) wins. More
  3378. * consoles might get enabled before the right one is found.
  3379. *
  3380. * Note that a console with tty binding will have CON_CONSDEV
  3381. * flag set and will be first in the list.
  3382. */
  3383. if (preferred_console < 0) {
  3384. if (hlist_empty(&console_list) || !console_first()->device ||
  3385. console_first()->flags & CON_BOOT) {
  3386. try_enable_default_console(newcon);
  3387. }
  3388. }
  3389. /* See if this console matches one we selected on the command line */
  3390. err = try_enable_preferred_console(newcon, true);
  3391. /* If not, try to match against the platform default(s) */
  3392. if (err == -ENOENT)
  3393. err = try_enable_preferred_console(newcon, false);
  3394. /* printk() messages are not printed to the Braille console. */
  3395. if (err || newcon->flags & CON_BRL) {
  3396. if (newcon->flags & CON_NBCON)
  3397. nbcon_free(newcon);
  3398. goto unlock;
  3399. }
  3400. /*
  3401. * If we have a bootconsole, and are switching to a real console,
  3402. * don't print everything out again, since when the boot console, and
  3403. * the real console are the same physical device, it's annoying to
  3404. * see the beginning boot messages twice
  3405. */
  3406. if (bootcon_registered &&
  3407. ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV)) {
  3408. newcon->flags &= ~CON_PRINTBUFFER;
  3409. }
  3410. newcon->dropped = 0;
  3411. init_seq = get_init_console_seq(newcon, bootcon_registered);
  3412. if (newcon->flags & CON_NBCON) {
  3413. have_nbcon_console = true;
  3414. nbcon_seq_force(newcon, init_seq);
  3415. } else {
  3416. have_legacy_console = true;
  3417. newcon->seq = init_seq;
  3418. }
  3419. if (newcon->flags & CON_BOOT)
  3420. have_boot_console = true;
  3421. /*
  3422. * If another context is actively using the hardware of this new
  3423. * console, it will not be aware of the nbcon synchronization. This
  3424. * is a risk that two contexts could access the hardware
  3425. * simultaneously if this new console is used for atomic printing
  3426. * and the other context is still using the hardware.
  3427. *
  3428. * Use the driver synchronization to ensure that the hardware is not
  3429. * in use while this new console transitions to being registered.
  3430. */
  3431. if (use_device_lock)
  3432. newcon->device_lock(newcon, &flags);
  3433. /*
  3434. * Put this console in the list - keep the
  3435. * preferred driver at the head of the list.
  3436. */
  3437. if (hlist_empty(&console_list)) {
  3438. /* Ensure CON_CONSDEV is always set for the head. */
  3439. newcon->flags |= CON_CONSDEV;
  3440. hlist_add_head_rcu(&newcon->node, &console_list);
  3441. } else if (newcon->flags & CON_CONSDEV) {
  3442. /* Only the new head can have CON_CONSDEV set. */
  3443. console_srcu_write_flags(console_first(), console_first()->flags & ~CON_CONSDEV);
  3444. hlist_add_head_rcu(&newcon->node, &console_list);
  3445. } else {
  3446. hlist_add_behind_rcu(&newcon->node, console_list.first);
  3447. }
  3448. /*
  3449. * No need to synchronize SRCU here! The caller does not rely
  3450. * on all contexts being able to see the new console before
  3451. * register_console() completes.
  3452. */
  3453. /* This new console is now registered. */
  3454. if (use_device_lock)
  3455. newcon->device_unlock(newcon, flags);
  3456. console_sysfs_notify();
  3457. /*
  3458. * By unregistering the bootconsoles after we enable the real console
  3459. * we get the "console xxx enabled" message on all the consoles -
  3460. * boot consoles, real consoles, etc - this is to ensure that end
  3461. * users know there might be something in the kernel's log buffer that
  3462. * went to the bootconsole (that they do not see on the real console)
  3463. */
  3464. con_printk(KERN_INFO, newcon, "enabled\n");
  3465. if (bootcon_registered &&
  3466. ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
  3467. !keep_bootcon) {
  3468. struct hlist_node *tmp;
  3469. hlist_for_each_entry_safe(con, tmp, &console_list, node) {
  3470. if (con->flags & CON_BOOT)
  3471. unregister_console_locked(con);
  3472. }
  3473. }
  3474. /* Changed console list, may require printer threads to start/stop. */
  3475. printk_kthreads_check_locked();
  3476. unlock:
  3477. console_list_unlock();
  3478. }
  3479. EXPORT_SYMBOL(register_console);
  3480. /* Must be called under console_list_lock(). */
  3481. static int unregister_console_locked(struct console *console)
  3482. {
  3483. bool use_device_lock = (console->flags & CON_NBCON) && console->write_atomic;
  3484. bool found_legacy_con = false;
  3485. bool found_nbcon_con = false;
  3486. bool found_boot_con = false;
  3487. unsigned long flags;
  3488. struct console *c;
  3489. int res;
  3490. lockdep_assert_console_list_lock_held();
  3491. con_printk(KERN_INFO, console, "disabled\n");
  3492. res = _braille_unregister_console(console);
  3493. if (res < 0)
  3494. return res;
  3495. if (res > 0)
  3496. return 0;
  3497. if (!console_is_registered_locked(console))
  3498. res = -ENODEV;
  3499. else if (console_is_usable(console, console->flags, true))
  3500. __pr_flush(console, 1000, true);
  3501. /* Disable it unconditionally */
  3502. console_srcu_write_flags(console, console->flags & ~CON_ENABLED);
  3503. if (res < 0)
  3504. return res;
  3505. /*
  3506. * Use the driver synchronization to ensure that the hardware is not
  3507. * in use while this console transitions to being unregistered.
  3508. */
  3509. if (use_device_lock)
  3510. console->device_lock(console, &flags);
  3511. hlist_del_init_rcu(&console->node);
  3512. if (use_device_lock)
  3513. console->device_unlock(console, flags);
  3514. /*
  3515. * <HISTORICAL>
  3516. * If this isn't the last console and it has CON_CONSDEV set, we
  3517. * need to set it on the next preferred console.
  3518. * </HISTORICAL>
  3519. *
  3520. * The above makes no sense as there is no guarantee that the next
  3521. * console has any device attached. Oh well....
  3522. */
  3523. if (!hlist_empty(&console_list) && console->flags & CON_CONSDEV)
  3524. console_srcu_write_flags(console_first(), console_first()->flags | CON_CONSDEV);
  3525. /*
  3526. * Ensure that all SRCU list walks have completed. All contexts
  3527. * must not be able to see this console in the list so that any
  3528. * exit/cleanup routines can be performed safely.
  3529. */
  3530. synchronize_srcu(&console_srcu);
  3531. if (console->flags & CON_NBCON)
  3532. nbcon_free(console);
  3533. console_sysfs_notify();
  3534. if (console->exit)
  3535. res = console->exit(console);
  3536. /*
  3537. * With this console gone, the global flags tracking registered
  3538. * console types may have changed. Update them.
  3539. */
  3540. for_each_console(c) {
  3541. if (c->flags & CON_BOOT)
  3542. found_boot_con = true;
  3543. if (c->flags & CON_NBCON)
  3544. found_nbcon_con = true;
  3545. else
  3546. found_legacy_con = true;
  3547. }
  3548. if (!found_boot_con)
  3549. have_boot_console = found_boot_con;
  3550. if (!found_legacy_con)
  3551. have_legacy_console = found_legacy_con;
  3552. if (!found_nbcon_con)
  3553. have_nbcon_console = found_nbcon_con;
  3554. /* Changed console list, may require printer threads to start/stop. */
  3555. printk_kthreads_check_locked();
  3556. return res;
  3557. }
  3558. int unregister_console(struct console *console)
  3559. {
  3560. int res;
  3561. console_list_lock();
  3562. res = unregister_console_locked(console);
  3563. console_list_unlock();
  3564. return res;
  3565. }
  3566. EXPORT_SYMBOL(unregister_console);
  3567. /**
  3568. * console_force_preferred_locked - force a registered console preferred
  3569. * @con: The registered console to force preferred.
  3570. *
  3571. * Must be called under console_list_lock().
  3572. */
  3573. void console_force_preferred_locked(struct console *con)
  3574. {
  3575. struct console *cur_pref_con;
  3576. if (!console_is_registered_locked(con))
  3577. return;
  3578. cur_pref_con = console_first();
  3579. /* Already preferred? */
  3580. if (cur_pref_con == con)
  3581. return;
  3582. /*
  3583. * Delete, but do not re-initialize the entry. This allows the console
  3584. * to continue to appear registered (via any hlist_unhashed_lockless()
  3585. * checks), even though it was briefly removed from the console list.
  3586. */
  3587. hlist_del_rcu(&con->node);
  3588. /*
  3589. * Ensure that all SRCU list walks have completed so that the console
  3590. * can be added to the beginning of the console list and its forward
  3591. * list pointer can be re-initialized.
  3592. */
  3593. synchronize_srcu(&console_srcu);
  3594. con->flags |= CON_CONSDEV;
  3595. WARN_ON(!con->device);
  3596. /* Only the new head can have CON_CONSDEV set. */
  3597. console_srcu_write_flags(cur_pref_con, cur_pref_con->flags & ~CON_CONSDEV);
  3598. hlist_add_head_rcu(&con->node, &console_list);
  3599. }
  3600. EXPORT_SYMBOL(console_force_preferred_locked);
  3601. /*
  3602. * Initialize the console device. This is called *early*, so
  3603. * we can't necessarily depend on lots of kernel help here.
  3604. * Just do some early initializations, and do the complex setup
  3605. * later.
  3606. */
  3607. void __init console_init(void)
  3608. {
  3609. int ret;
  3610. initcall_t call;
  3611. initcall_entry_t *ce;
  3612. /* Setup the default TTY line discipline. */
  3613. n_tty_init();
  3614. /*
  3615. * set up the console device so that later boot sequences can
  3616. * inform about problems etc..
  3617. */
  3618. ce = __con_initcall_start;
  3619. trace_initcall_level("console");
  3620. while (ce < __con_initcall_end) {
  3621. call = initcall_from_entry(ce);
  3622. trace_initcall_start(call);
  3623. ret = call();
  3624. trace_initcall_finish(call, ret);
  3625. ce++;
  3626. }
  3627. }
  3628. /*
  3629. * Some boot consoles access data that is in the init section and which will
  3630. * be discarded after the initcalls have been run. To make sure that no code
  3631. * will access this data, unregister the boot consoles in a late initcall.
  3632. *
  3633. * If for some reason, such as deferred probe or the driver being a loadable
  3634. * module, the real console hasn't registered yet at this point, there will
  3635. * be a brief interval in which no messages are logged to the console, which
  3636. * makes it difficult to diagnose problems that occur during this time.
  3637. *
  3638. * To mitigate this problem somewhat, only unregister consoles whose memory
  3639. * intersects with the init section. Note that all other boot consoles will
  3640. * get unregistered when the real preferred console is registered.
  3641. */
  3642. static int __init printk_late_init(void)
  3643. {
  3644. struct hlist_node *tmp;
  3645. struct console *con;
  3646. int ret;
  3647. console_list_lock();
  3648. hlist_for_each_entry_safe(con, tmp, &console_list, node) {
  3649. if (!(con->flags & CON_BOOT))
  3650. continue;
  3651. /* Check addresses that might be used for enabled consoles. */
  3652. if (init_section_intersects(con, sizeof(*con)) ||
  3653. init_section_contains(con->write, 0) ||
  3654. init_section_contains(con->read, 0) ||
  3655. init_section_contains(con->device, 0) ||
  3656. init_section_contains(con->unblank, 0) ||
  3657. init_section_contains(con->data, 0)) {
  3658. /*
  3659. * Please, consider moving the reported consoles out
  3660. * of the init section.
  3661. */
  3662. pr_warn("bootconsole [%s%d] uses init memory and must be disabled even before the real one is ready\n",
  3663. con->name, con->index);
  3664. unregister_console_locked(con);
  3665. }
  3666. }
  3667. console_list_unlock();
  3668. ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
  3669. console_cpu_notify);
  3670. WARN_ON(ret < 0);
  3671. ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "printk:online",
  3672. console_cpu_notify, NULL);
  3673. WARN_ON(ret < 0);
  3674. printk_sysctl_init();
  3675. return 0;
  3676. }
  3677. late_initcall(printk_late_init);
  3678. #if defined CONFIG_PRINTK
  3679. /* If @con is specified, only wait for that console. Otherwise wait for all. */
  3680. static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress)
  3681. {
  3682. unsigned long timeout_jiffies = msecs_to_jiffies(timeout_ms);
  3683. unsigned long remaining_jiffies = timeout_jiffies;
  3684. struct console_flush_type ft;
  3685. struct console *c;
  3686. u64 last_diff = 0;
  3687. u64 printk_seq;
  3688. short flags;
  3689. int cookie;
  3690. u64 diff;
  3691. u64 seq;
  3692. /* Sorry, pr_flush() will not work this early. */
  3693. if (system_state < SYSTEM_SCHEDULING)
  3694. return false;
  3695. might_sleep();
  3696. seq = prb_next_reserve_seq(prb);
  3697. /* Flush the consoles so that records up to @seq are printed. */
  3698. printk_get_console_flush_type(&ft);
  3699. if (ft.nbcon_atomic)
  3700. nbcon_atomic_flush_pending();
  3701. if (ft.legacy_direct) {
  3702. console_lock();
  3703. console_unlock();
  3704. }
  3705. for (;;) {
  3706. unsigned long begin_jiffies;
  3707. unsigned long slept_jiffies;
  3708. diff = 0;
  3709. /*
  3710. * Hold the console_lock to guarantee safe access to
  3711. * console->seq. Releasing console_lock flushes more
  3712. * records in case @seq is still not printed on all
  3713. * usable consoles.
  3714. *
  3715. * Holding the console_lock is not necessary if there
  3716. * are no legacy or boot consoles. However, such a
  3717. * console could register at any time. Always hold the
  3718. * console_lock as a precaution rather than
  3719. * synchronizing against register_console().
  3720. */
  3721. console_lock();
  3722. cookie = console_srcu_read_lock();
  3723. for_each_console_srcu(c) {
  3724. if (con && con != c)
  3725. continue;
  3726. flags = console_srcu_read_flags(c);
  3727. /*
  3728. * If consoles are not usable, it cannot be expected
  3729. * that they make forward progress, so only increment
  3730. * @diff for usable consoles.
  3731. */
  3732. if (!console_is_usable(c, flags, true) &&
  3733. !console_is_usable(c, flags, false)) {
  3734. continue;
  3735. }
  3736. if (flags & CON_NBCON) {
  3737. printk_seq = nbcon_seq_read(c);
  3738. } else {
  3739. printk_seq = c->seq;
  3740. }
  3741. if (printk_seq < seq)
  3742. diff += seq - printk_seq;
  3743. }
  3744. console_srcu_read_unlock(cookie);
  3745. if (diff != last_diff && reset_on_progress)
  3746. remaining_jiffies = timeout_jiffies;
  3747. console_unlock();
  3748. /* Note: @diff is 0 if there are no usable consoles. */
  3749. if (diff == 0 || remaining_jiffies == 0)
  3750. break;
  3751. /* msleep(1) might sleep much longer. Check time by jiffies. */
  3752. begin_jiffies = jiffies;
  3753. msleep(1);
  3754. slept_jiffies = jiffies - begin_jiffies;
  3755. remaining_jiffies -= min(slept_jiffies, remaining_jiffies);
  3756. last_diff = diff;
  3757. }
  3758. return (diff == 0);
  3759. }
  3760. /**
  3761. * pr_flush() - Wait for printing threads to catch up.
  3762. *
  3763. * @timeout_ms: The maximum time (in ms) to wait.
  3764. * @reset_on_progress: Reset the timeout if forward progress is seen.
  3765. *
  3766. * A value of 0 for @timeout_ms means no waiting will occur. A value of -1
  3767. * represents infinite waiting.
  3768. *
  3769. * If @reset_on_progress is true, the timeout will be reset whenever any
  3770. * printer has been seen to make some forward progress.
  3771. *
  3772. * Context: Process context. May sleep while acquiring console lock.
  3773. * Return: true if all usable printers are caught up.
  3774. */
  3775. bool pr_flush(int timeout_ms, bool reset_on_progress)
  3776. {
  3777. return __pr_flush(NULL, timeout_ms, reset_on_progress);
  3778. }
  3779. /*
  3780. * Delayed printk version, for scheduler-internal messages:
  3781. */
  3782. #define PRINTK_PENDING_WAKEUP 0x01
  3783. #define PRINTK_PENDING_OUTPUT 0x02
  3784. static DEFINE_PER_CPU(int, printk_pending);
  3785. static void wake_up_klogd_work_func(struct irq_work *irq_work)
  3786. {
  3787. int pending = this_cpu_xchg(printk_pending, 0);
  3788. if (pending & PRINTK_PENDING_OUTPUT) {
  3789. if (force_legacy_kthread()) {
  3790. if (printk_legacy_kthread)
  3791. wake_up_interruptible(&legacy_wait);
  3792. } else {
  3793. if (console_trylock())
  3794. console_unlock();
  3795. }
  3796. }
  3797. if (pending & PRINTK_PENDING_WAKEUP)
  3798. wake_up_interruptible(&log_wait);
  3799. }
  3800. static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) =
  3801. IRQ_WORK_INIT_LAZY(wake_up_klogd_work_func);
  3802. static void __wake_up_klogd(int val)
  3803. {
  3804. if (!printk_percpu_data_ready())
  3805. return;
  3806. preempt_disable();
  3807. /*
  3808. * Guarantee any new records can be seen by tasks preparing to wait
  3809. * before this context checks if the wait queue is empty.
  3810. *
  3811. * The full memory barrier within wq_has_sleeper() pairs with the full
  3812. * memory barrier within set_current_state() of
  3813. * prepare_to_wait_event(), which is called after ___wait_event() adds
  3814. * the waiter but before it has checked the wait condition.
  3815. *
  3816. * This pairs with devkmsg_read:A and syslog_print:A.
  3817. */
  3818. if (wq_has_sleeper(&log_wait) || /* LMM(__wake_up_klogd:A) */
  3819. (val & PRINTK_PENDING_OUTPUT)) {
  3820. this_cpu_or(printk_pending, val);
  3821. irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
  3822. }
  3823. preempt_enable();
  3824. }
  3825. /**
  3826. * wake_up_klogd - Wake kernel logging daemon
  3827. *
  3828. * Use this function when new records have been added to the ringbuffer
  3829. * and the console printing of those records has already occurred or is
  3830. * known to be handled by some other context. This function will only
  3831. * wake the logging daemon.
  3832. *
  3833. * Context: Any context.
  3834. */
  3835. void wake_up_klogd(void)
  3836. {
  3837. __wake_up_klogd(PRINTK_PENDING_WAKEUP);
  3838. }
  3839. /**
  3840. * defer_console_output - Wake kernel logging daemon and trigger
  3841. * console printing in a deferred context
  3842. *
  3843. * Use this function when new records have been added to the ringbuffer,
  3844. * this context is responsible for console printing those records, but
  3845. * the current context is not allowed to perform the console printing.
  3846. * Trigger an irq_work context to perform the console printing. This
  3847. * function also wakes the logging daemon.
  3848. *
  3849. * Context: Any context.
  3850. */
  3851. void defer_console_output(void)
  3852. {
  3853. /*
  3854. * New messages may have been added directly to the ringbuffer
  3855. * using vprintk_store(), so wake any waiters as well.
  3856. */
  3857. __wake_up_klogd(PRINTK_PENDING_WAKEUP | PRINTK_PENDING_OUTPUT);
  3858. }
  3859. void printk_trigger_flush(void)
  3860. {
  3861. defer_console_output();
  3862. }
  3863. int vprintk_deferred(const char *fmt, va_list args)
  3864. {
  3865. return vprintk_emit(0, LOGLEVEL_SCHED, NULL, fmt, args);
  3866. }
  3867. int _printk_deferred(const char *fmt, ...)
  3868. {
  3869. va_list args;
  3870. int r;
  3871. va_start(args, fmt);
  3872. r = vprintk_deferred(fmt, args);
  3873. va_end(args);
  3874. return r;
  3875. }
  3876. /*
  3877. * printk rate limiting, lifted from the networking subsystem.
  3878. *
  3879. * This enforces a rate limit: not more than 10 kernel messages
  3880. * every 5s to make a denial-of-service attack impossible.
  3881. */
  3882. DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
  3883. int __printk_ratelimit(const char *func)
  3884. {
  3885. return ___ratelimit(&printk_ratelimit_state, func);
  3886. }
  3887. EXPORT_SYMBOL(__printk_ratelimit);
  3888. /**
  3889. * printk_timed_ratelimit - caller-controlled printk ratelimiting
  3890. * @caller_jiffies: pointer to caller's state
  3891. * @interval_msecs: minimum interval between prints
  3892. *
  3893. * printk_timed_ratelimit() returns true if more than @interval_msecs
  3894. * milliseconds have elapsed since the last time printk_timed_ratelimit()
  3895. * returned true.
  3896. */
  3897. bool printk_timed_ratelimit(unsigned long *caller_jiffies,
  3898. unsigned int interval_msecs)
  3899. {
  3900. unsigned long elapsed = jiffies - *caller_jiffies;
  3901. if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
  3902. return false;
  3903. *caller_jiffies = jiffies;
  3904. return true;
  3905. }
  3906. EXPORT_SYMBOL(printk_timed_ratelimit);
  3907. static DEFINE_SPINLOCK(dump_list_lock);
  3908. static LIST_HEAD(dump_list);
  3909. /**
  3910. * kmsg_dump_register - register a kernel log dumper.
  3911. * @dumper: pointer to the kmsg_dumper structure
  3912. *
  3913. * Adds a kernel log dumper to the system. The dump callback in the
  3914. * structure will be called when the kernel oopses or panics and must be
  3915. * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
  3916. */
  3917. int kmsg_dump_register(struct kmsg_dumper *dumper)
  3918. {
  3919. unsigned long flags;
  3920. int err = -EBUSY;
  3921. /* The dump callback needs to be set */
  3922. if (!dumper->dump)
  3923. return -EINVAL;
  3924. spin_lock_irqsave(&dump_list_lock, flags);
  3925. /* Don't allow registering multiple times */
  3926. if (!dumper->registered) {
  3927. dumper->registered = 1;
  3928. list_add_tail_rcu(&dumper->list, &dump_list);
  3929. err = 0;
  3930. }
  3931. spin_unlock_irqrestore(&dump_list_lock, flags);
  3932. return err;
  3933. }
  3934. EXPORT_SYMBOL_GPL(kmsg_dump_register);
  3935. /**
  3936. * kmsg_dump_unregister - unregister a kmsg dumper.
  3937. * @dumper: pointer to the kmsg_dumper structure
  3938. *
  3939. * Removes a dump device from the system. Returns zero on success and
  3940. * %-EINVAL otherwise.
  3941. */
  3942. int kmsg_dump_unregister(struct kmsg_dumper *dumper)
  3943. {
  3944. unsigned long flags;
  3945. int err = -EINVAL;
  3946. spin_lock_irqsave(&dump_list_lock, flags);
  3947. if (dumper->registered) {
  3948. dumper->registered = 0;
  3949. list_del_rcu(&dumper->list);
  3950. err = 0;
  3951. }
  3952. spin_unlock_irqrestore(&dump_list_lock, flags);
  3953. synchronize_rcu();
  3954. return err;
  3955. }
  3956. EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
  3957. static bool always_kmsg_dump;
  3958. module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
  3959. const char *kmsg_dump_reason_str(enum kmsg_dump_reason reason)
  3960. {
  3961. switch (reason) {
  3962. case KMSG_DUMP_PANIC:
  3963. return "Panic";
  3964. case KMSG_DUMP_OOPS:
  3965. return "Oops";
  3966. case KMSG_DUMP_EMERG:
  3967. return "Emergency";
  3968. case KMSG_DUMP_SHUTDOWN:
  3969. return "Shutdown";
  3970. default:
  3971. return "Unknown";
  3972. }
  3973. }
  3974. EXPORT_SYMBOL_GPL(kmsg_dump_reason_str);
  3975. /**
  3976. * kmsg_dump_desc - dump kernel log to kernel message dumpers.
  3977. * @reason: the reason (oops, panic etc) for dumping
  3978. * @desc: a short string to describe what caused the panic or oops. Can be NULL
  3979. * if no additional description is available.
  3980. *
  3981. * Call each of the registered dumper's dump() callback, which can
  3982. * retrieve the kmsg records with kmsg_dump_get_line() or
  3983. * kmsg_dump_get_buffer().
  3984. */
  3985. void kmsg_dump_desc(enum kmsg_dump_reason reason, const char *desc)
  3986. {
  3987. struct kmsg_dumper *dumper;
  3988. struct kmsg_dump_detail detail = {
  3989. .reason = reason,
  3990. .description = desc};
  3991. rcu_read_lock();
  3992. list_for_each_entry_rcu(dumper, &dump_list, list) {
  3993. enum kmsg_dump_reason max_reason = dumper->max_reason;
  3994. /*
  3995. * If client has not provided a specific max_reason, default
  3996. * to KMSG_DUMP_OOPS, unless always_kmsg_dump was set.
  3997. */
  3998. if (max_reason == KMSG_DUMP_UNDEF) {
  3999. max_reason = always_kmsg_dump ? KMSG_DUMP_MAX :
  4000. KMSG_DUMP_OOPS;
  4001. }
  4002. if (reason > max_reason)
  4003. continue;
  4004. /* invoke dumper which will iterate over records */
  4005. dumper->dump(dumper, &detail);
  4006. }
  4007. rcu_read_unlock();
  4008. }
  4009. /**
  4010. * kmsg_dump_get_line - retrieve one kmsg log line
  4011. * @iter: kmsg dump iterator
  4012. * @syslog: include the "<4>" prefixes
  4013. * @line: buffer to copy the line to
  4014. * @size: maximum size of the buffer
  4015. * @len: length of line placed into buffer
  4016. *
  4017. * Start at the beginning of the kmsg buffer, with the oldest kmsg
  4018. * record, and copy one record into the provided buffer.
  4019. *
  4020. * Consecutive calls will return the next available record moving
  4021. * towards the end of the buffer with the youngest messages.
  4022. *
  4023. * A return value of FALSE indicates that there are no more records to
  4024. * read.
  4025. */
  4026. bool kmsg_dump_get_line(struct kmsg_dump_iter *iter, bool syslog,
  4027. char *line, size_t size, size_t *len)
  4028. {
  4029. u64 min_seq = latched_seq_read_nolock(&clear_seq);
  4030. struct printk_info info;
  4031. unsigned int line_count;
  4032. struct printk_record r;
  4033. size_t l = 0;
  4034. bool ret = false;
  4035. if (iter->cur_seq < min_seq)
  4036. iter->cur_seq = min_seq;
  4037. prb_rec_init_rd(&r, &info, line, size);
  4038. /* Read text or count text lines? */
  4039. if (line) {
  4040. if (!prb_read_valid(prb, iter->cur_seq, &r))
  4041. goto out;
  4042. l = record_print_text(&r, syslog, printk_time);
  4043. } else {
  4044. if (!prb_read_valid_info(prb, iter->cur_seq,
  4045. &info, &line_count)) {
  4046. goto out;
  4047. }
  4048. l = get_record_print_text_size(&info, line_count, syslog,
  4049. printk_time);
  4050. }
  4051. iter->cur_seq = r.info->seq + 1;
  4052. ret = true;
  4053. out:
  4054. if (len)
  4055. *len = l;
  4056. return ret;
  4057. }
  4058. EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
  4059. /**
  4060. * kmsg_dump_get_buffer - copy kmsg log lines
  4061. * @iter: kmsg dump iterator
  4062. * @syslog: include the "<4>" prefixes
  4063. * @buf: buffer to copy the line to
  4064. * @size: maximum size of the buffer
  4065. * @len_out: length of line placed into buffer
  4066. *
  4067. * Start at the end of the kmsg buffer and fill the provided buffer
  4068. * with as many of the *youngest* kmsg records that fit into it.
  4069. * If the buffer is large enough, all available kmsg records will be
  4070. * copied with a single call.
  4071. *
  4072. * Consecutive calls will fill the buffer with the next block of
  4073. * available older records, not including the earlier retrieved ones.
  4074. *
  4075. * A return value of FALSE indicates that there are no more records to
  4076. * read.
  4077. */
  4078. bool kmsg_dump_get_buffer(struct kmsg_dump_iter *iter, bool syslog,
  4079. char *buf, size_t size, size_t *len_out)
  4080. {
  4081. u64 min_seq = latched_seq_read_nolock(&clear_seq);
  4082. struct printk_info info;
  4083. struct printk_record r;
  4084. u64 seq;
  4085. u64 next_seq;
  4086. size_t len = 0;
  4087. bool ret = false;
  4088. bool time = printk_time;
  4089. if (!buf || !size)
  4090. goto out;
  4091. if (iter->cur_seq < min_seq)
  4092. iter->cur_seq = min_seq;
  4093. if (prb_read_valid_info(prb, iter->cur_seq, &info, NULL)) {
  4094. if (info.seq != iter->cur_seq) {
  4095. /* messages are gone, move to first available one */
  4096. iter->cur_seq = info.seq;
  4097. }
  4098. }
  4099. /* last entry */
  4100. if (iter->cur_seq >= iter->next_seq)
  4101. goto out;
  4102. /*
  4103. * Find first record that fits, including all following records,
  4104. * into the user-provided buffer for this dump. Pass in size-1
  4105. * because this function (by way of record_print_text()) will
  4106. * not write more than size-1 bytes of text into @buf.
  4107. */
  4108. seq = find_first_fitting_seq(iter->cur_seq, iter->next_seq,
  4109. size - 1, syslog, time);
  4110. /*
  4111. * Next kmsg_dump_get_buffer() invocation will dump block of
  4112. * older records stored right before this one.
  4113. */
  4114. next_seq = seq;
  4115. prb_rec_init_rd(&r, &info, buf, size);
  4116. prb_for_each_record(seq, prb, seq, &r) {
  4117. if (r.info->seq >= iter->next_seq)
  4118. break;
  4119. len += record_print_text(&r, syslog, time);
  4120. /* Adjust record to store to remaining buffer space. */
  4121. prb_rec_init_rd(&r, &info, buf + len, size - len);
  4122. }
  4123. iter->next_seq = next_seq;
  4124. ret = true;
  4125. out:
  4126. if (len_out)
  4127. *len_out = len;
  4128. return ret;
  4129. }
  4130. EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
  4131. /**
  4132. * kmsg_dump_rewind - reset the iterator
  4133. * @iter: kmsg dump iterator
  4134. *
  4135. * Reset the dumper's iterator so that kmsg_dump_get_line() and
  4136. * kmsg_dump_get_buffer() can be called again and used multiple
  4137. * times within the same dumper.dump() callback.
  4138. */
  4139. void kmsg_dump_rewind(struct kmsg_dump_iter *iter)
  4140. {
  4141. iter->cur_seq = latched_seq_read_nolock(&clear_seq);
  4142. iter->next_seq = prb_next_seq(prb);
  4143. }
  4144. EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
  4145. /**
  4146. * console_try_replay_all - try to replay kernel log on consoles
  4147. *
  4148. * Try to obtain lock on console subsystem and replay all
  4149. * available records in printk buffer on the consoles.
  4150. * Does nothing if lock is not obtained.
  4151. *
  4152. * Context: Any, except for NMI.
  4153. */
  4154. void console_try_replay_all(void)
  4155. {
  4156. struct console_flush_type ft;
  4157. printk_get_console_flush_type(&ft);
  4158. if (console_trylock()) {
  4159. __console_rewind_all();
  4160. if (ft.nbcon_atomic)
  4161. nbcon_atomic_flush_pending();
  4162. if (ft.nbcon_offload)
  4163. nbcon_kthreads_wake();
  4164. if (ft.legacy_offload)
  4165. defer_console_output();
  4166. /* Consoles are flushed as part of console_unlock(). */
  4167. console_unlock();
  4168. }
  4169. }
  4170. #endif
  4171. #ifdef CONFIG_SMP
  4172. static atomic_t printk_cpu_sync_owner = ATOMIC_INIT(-1);
  4173. static atomic_t printk_cpu_sync_nested = ATOMIC_INIT(0);
  4174. bool is_printk_cpu_sync_owner(void)
  4175. {
  4176. return (atomic_read(&printk_cpu_sync_owner) == raw_smp_processor_id());
  4177. }
  4178. /**
  4179. * __printk_cpu_sync_wait() - Busy wait until the printk cpu-reentrant
  4180. * spinning lock is not owned by any CPU.
  4181. *
  4182. * Context: Any context.
  4183. */
  4184. void __printk_cpu_sync_wait(void)
  4185. {
  4186. do {
  4187. cpu_relax();
  4188. } while (atomic_read(&printk_cpu_sync_owner) != -1);
  4189. }
  4190. EXPORT_SYMBOL(__printk_cpu_sync_wait);
  4191. /**
  4192. * __printk_cpu_sync_try_get() - Try to acquire the printk cpu-reentrant
  4193. * spinning lock.
  4194. *
  4195. * If no processor has the lock, the calling processor takes the lock and
  4196. * becomes the owner. If the calling processor is already the owner of the
  4197. * lock, this function succeeds immediately.
  4198. *
  4199. * Context: Any context. Expects interrupts to be disabled.
  4200. * Return: 1 on success, otherwise 0.
  4201. */
  4202. int __printk_cpu_sync_try_get(void)
  4203. {
  4204. int cpu;
  4205. int old;
  4206. cpu = smp_processor_id();
  4207. /*
  4208. * Guarantee loads and stores from this CPU when it is the lock owner
  4209. * are _not_ visible to the previous lock owner. This pairs with
  4210. * __printk_cpu_sync_put:B.
  4211. *
  4212. * Memory barrier involvement:
  4213. *
  4214. * If __printk_cpu_sync_try_get:A reads from __printk_cpu_sync_put:B,
  4215. * then __printk_cpu_sync_put:A can never read from
  4216. * __printk_cpu_sync_try_get:B.
  4217. *
  4218. * Relies on:
  4219. *
  4220. * RELEASE from __printk_cpu_sync_put:A to __printk_cpu_sync_put:B
  4221. * of the previous CPU
  4222. * matching
  4223. * ACQUIRE from __printk_cpu_sync_try_get:A to
  4224. * __printk_cpu_sync_try_get:B of this CPU
  4225. */
  4226. old = atomic_cmpxchg_acquire(&printk_cpu_sync_owner, -1,
  4227. cpu); /* LMM(__printk_cpu_sync_try_get:A) */
  4228. if (old == -1) {
  4229. /*
  4230. * This CPU is now the owner and begins loading/storing
  4231. * data: LMM(__printk_cpu_sync_try_get:B)
  4232. */
  4233. return 1;
  4234. } else if (old == cpu) {
  4235. /* This CPU is already the owner. */
  4236. atomic_inc(&printk_cpu_sync_nested);
  4237. return 1;
  4238. }
  4239. return 0;
  4240. }
  4241. EXPORT_SYMBOL(__printk_cpu_sync_try_get);
  4242. /**
  4243. * __printk_cpu_sync_put() - Release the printk cpu-reentrant spinning lock.
  4244. *
  4245. * The calling processor must be the owner of the lock.
  4246. *
  4247. * Context: Any context. Expects interrupts to be disabled.
  4248. */
  4249. void __printk_cpu_sync_put(void)
  4250. {
  4251. if (atomic_read(&printk_cpu_sync_nested)) {
  4252. atomic_dec(&printk_cpu_sync_nested);
  4253. return;
  4254. }
  4255. /*
  4256. * This CPU is finished loading/storing data:
  4257. * LMM(__printk_cpu_sync_put:A)
  4258. */
  4259. /*
  4260. * Guarantee loads and stores from this CPU when it was the
  4261. * lock owner are visible to the next lock owner. This pairs
  4262. * with __printk_cpu_sync_try_get:A.
  4263. *
  4264. * Memory barrier involvement:
  4265. *
  4266. * If __printk_cpu_sync_try_get:A reads from __printk_cpu_sync_put:B,
  4267. * then __printk_cpu_sync_try_get:B reads from __printk_cpu_sync_put:A.
  4268. *
  4269. * Relies on:
  4270. *
  4271. * RELEASE from __printk_cpu_sync_put:A to __printk_cpu_sync_put:B
  4272. * of this CPU
  4273. * matching
  4274. * ACQUIRE from __printk_cpu_sync_try_get:A to
  4275. * __printk_cpu_sync_try_get:B of the next CPU
  4276. */
  4277. atomic_set_release(&printk_cpu_sync_owner,
  4278. -1); /* LMM(__printk_cpu_sync_put:B) */
  4279. }
  4280. EXPORT_SYMBOL(__printk_cpu_sync_put);
  4281. #endif /* CONFIG_SMP */