printk.c 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279
  1. /*
  2. * linux/kernel/printk.c
  3. *
  4. * Copyright (C) 1991, 1992 Linus Torvalds
  5. *
  6. * Modified to make sys_syslog() more flexible: added commands to
  7. * return the last 4k of kernel messages, regardless of whether
  8. * they've been read or not. Added option to suppress kernel printk's
  9. * to the console. Added hook for sending the console messages
  10. * elsewhere, in preparation for a serial line console (someday).
  11. * Ted Ts'o, 2/11/93.
  12. * Modified for sysctl support, 1/8/97, Chris Horn.
  13. * Fixed SMP synchronization, 08/08/99, Manfred Spraul
  14. * manfred@colorfullife.com
  15. * Rewrote bits to get rid of console_lock
  16. * 01Mar01 Andrew Morton
  17. */
  18. #include <linux/kernel.h>
  19. #include <linux/mm.h>
  20. #include <linux/tty.h>
  21. #include <linux/tty_driver.h>
  22. #include <linux/console.h>
  23. #include <linux/init.h>
  24. #include <linux/jiffies.h>
  25. #include <linux/nmi.h>
  26. #include <linux/module.h>
  27. #include <linux/moduleparam.h>
  28. #include <linux/delay.h>
  29. #include <linux/smp.h>
  30. #include <linux/security.h>
  31. #include <linux/bootmem.h>
  32. #include <linux/memblock.h>
  33. #include <linux/syscalls.h>
  34. #include <linux/crash_core.h>
  35. #include <linux/kdb.h>
  36. #include <linux/ratelimit.h>
  37. #include <linux/kmsg_dump.h>
  38. #include <linux/syslog.h>
  39. #include <linux/cpu.h>
  40. #include <linux/notifier.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 "console_cmdline.h"
  55. #include "braille.h"
  56. #include "internal.h"
  57. int console_printk[4] = {
  58. CONSOLE_LOGLEVEL_DEFAULT, /* console_loglevel */
  59. MESSAGE_LOGLEVEL_DEFAULT, /* default_message_loglevel */
  60. CONSOLE_LOGLEVEL_MIN, /* minimum_console_loglevel */
  61. CONSOLE_LOGLEVEL_DEFAULT, /* default_console_loglevel */
  62. };
  63. atomic_t ignore_console_lock_warning __read_mostly = ATOMIC_INIT(0);
  64. EXPORT_SYMBOL(ignore_console_lock_warning);
  65. /*
  66. * Low level drivers may need that to know if they can schedule in
  67. * their unblank() callback or not. So let's export it.
  68. */
  69. int oops_in_progress;
  70. EXPORT_SYMBOL(oops_in_progress);
  71. /*
  72. * console_sem protects the console_drivers list, and also
  73. * provides serialisation for access to the entire console
  74. * driver system.
  75. */
  76. static DEFINE_SEMAPHORE(console_sem);
  77. struct console *console_drivers;
  78. EXPORT_SYMBOL_GPL(console_drivers);
  79. #ifdef CONFIG_LOCKDEP
  80. static struct lockdep_map console_lock_dep_map = {
  81. .name = "console_lock"
  82. };
  83. #endif
  84. enum devkmsg_log_bits {
  85. __DEVKMSG_LOG_BIT_ON = 0,
  86. __DEVKMSG_LOG_BIT_OFF,
  87. __DEVKMSG_LOG_BIT_LOCK,
  88. };
  89. enum devkmsg_log_masks {
  90. DEVKMSG_LOG_MASK_ON = BIT(__DEVKMSG_LOG_BIT_ON),
  91. DEVKMSG_LOG_MASK_OFF = BIT(__DEVKMSG_LOG_BIT_OFF),
  92. DEVKMSG_LOG_MASK_LOCK = BIT(__DEVKMSG_LOG_BIT_LOCK),
  93. };
  94. /* Keep both the 'on' and 'off' bits clear, i.e. ratelimit by default: */
  95. #define DEVKMSG_LOG_MASK_DEFAULT 0
  96. static unsigned int __read_mostly devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
  97. static int __control_devkmsg(char *str)
  98. {
  99. if (!str)
  100. return -EINVAL;
  101. if (!strncmp(str, "on", 2)) {
  102. devkmsg_log = DEVKMSG_LOG_MASK_ON;
  103. return 2;
  104. } else if (!strncmp(str, "off", 3)) {
  105. devkmsg_log = DEVKMSG_LOG_MASK_OFF;
  106. return 3;
  107. } else if (!strncmp(str, "ratelimit", 9)) {
  108. devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
  109. return 9;
  110. }
  111. return -EINVAL;
  112. }
  113. static int __init control_devkmsg(char *str)
  114. {
  115. if (__control_devkmsg(str) < 0)
  116. return 1;
  117. /*
  118. * Set sysctl string accordingly:
  119. */
  120. if (devkmsg_log == DEVKMSG_LOG_MASK_ON)
  121. strcpy(devkmsg_log_str, "on");
  122. else if (devkmsg_log == DEVKMSG_LOG_MASK_OFF)
  123. strcpy(devkmsg_log_str, "off");
  124. /* else "ratelimit" which is set by default. */
  125. /*
  126. * Sysctl cannot change it anymore. The kernel command line setting of
  127. * this parameter is to force the setting to be permanent throughout the
  128. * runtime of the system. This is a precation measure against userspace
  129. * trying to be a smarta** and attempting to change it up on us.
  130. */
  131. devkmsg_log |= DEVKMSG_LOG_MASK_LOCK;
  132. return 0;
  133. }
  134. __setup("printk.devkmsg=", control_devkmsg);
  135. char devkmsg_log_str[DEVKMSG_STR_MAX_SIZE] = "ratelimit";
  136. int devkmsg_sysctl_set_loglvl(struct ctl_table *table, int write,
  137. void __user *buffer, size_t *lenp, loff_t *ppos)
  138. {
  139. char old_str[DEVKMSG_STR_MAX_SIZE];
  140. unsigned int old;
  141. int err;
  142. if (write) {
  143. if (devkmsg_log & DEVKMSG_LOG_MASK_LOCK)
  144. return -EINVAL;
  145. old = devkmsg_log;
  146. strncpy(old_str, devkmsg_log_str, DEVKMSG_STR_MAX_SIZE);
  147. }
  148. err = proc_dostring(table, write, buffer, lenp, ppos);
  149. if (err)
  150. return err;
  151. if (write) {
  152. err = __control_devkmsg(devkmsg_log_str);
  153. /*
  154. * Do not accept an unknown string OR a known string with
  155. * trailing crap...
  156. */
  157. if (err < 0 || (err + 1 != *lenp)) {
  158. /* ... and restore old setting. */
  159. devkmsg_log = old;
  160. strncpy(devkmsg_log_str, old_str, DEVKMSG_STR_MAX_SIZE);
  161. return -EINVAL;
  162. }
  163. }
  164. return 0;
  165. }
  166. /*
  167. * Number of registered extended console drivers.
  168. *
  169. * If extended consoles are present, in-kernel cont reassembly is disabled
  170. * and each fragment is stored as a separate log entry with proper
  171. * continuation flag so that every emitted message has full metadata. This
  172. * doesn't change the result for regular consoles or /proc/kmsg. For
  173. * /dev/kmsg, as long as the reader concatenates messages according to
  174. * consecutive continuation flags, the end result should be the same too.
  175. */
  176. static int nr_ext_console_drivers;
  177. /*
  178. * Helper macros to handle lockdep when locking/unlocking console_sem. We use
  179. * macros instead of functions so that _RET_IP_ contains useful information.
  180. */
  181. #define down_console_sem() do { \
  182. down(&console_sem);\
  183. mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
  184. } while (0)
  185. static int __down_trylock_console_sem(unsigned long ip)
  186. {
  187. int lock_failed;
  188. unsigned long flags;
  189. /*
  190. * Here and in __up_console_sem() we need to be in safe mode,
  191. * because spindump/WARN/etc from under console ->lock will
  192. * deadlock in printk()->down_trylock_console_sem() otherwise.
  193. */
  194. printk_safe_enter_irqsave(flags);
  195. lock_failed = down_trylock(&console_sem);
  196. printk_safe_exit_irqrestore(flags);
  197. if (lock_failed)
  198. return 1;
  199. mutex_acquire(&console_lock_dep_map, 0, 1, ip);
  200. return 0;
  201. }
  202. #define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
  203. static void __up_console_sem(unsigned long ip)
  204. {
  205. unsigned long flags;
  206. mutex_release(&console_lock_dep_map, 1, ip);
  207. printk_safe_enter_irqsave(flags);
  208. up(&console_sem);
  209. printk_safe_exit_irqrestore(flags);
  210. }
  211. #define up_console_sem() __up_console_sem(_RET_IP_)
  212. /*
  213. * This is used for debugging the mess that is the VT code by
  214. * keeping track if we have the console semaphore held. It's
  215. * definitely not the perfect debug tool (we don't know if _WE_
  216. * hold it and are racing, but it helps tracking those weird code
  217. * paths in the console code where we end up in places I want
  218. * locked without the console sempahore held).
  219. */
  220. static int console_locked, console_suspended;
  221. /*
  222. * If exclusive_console is non-NULL then only this console is to be printed to.
  223. */
  224. static struct console *exclusive_console;
  225. /*
  226. * Array of consoles built from command line options (console=)
  227. */
  228. #define MAX_CMDLINECONSOLES 8
  229. static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
  230. static int preferred_console = -1;
  231. int console_set_on_cmdline;
  232. EXPORT_SYMBOL(console_set_on_cmdline);
  233. /* Flag: console code may call schedule() */
  234. static int console_may_schedule;
  235. enum con_msg_format_flags {
  236. MSG_FORMAT_DEFAULT = 0,
  237. MSG_FORMAT_SYSLOG = (1 << 0),
  238. };
  239. static int console_msg_format = MSG_FORMAT_DEFAULT;
  240. /*
  241. * The printk log buffer consists of a chain of concatenated variable
  242. * length records. Every record starts with a record header, containing
  243. * the overall length of the record.
  244. *
  245. * The heads to the first and last entry in the buffer, as well as the
  246. * sequence numbers of these entries are maintained when messages are
  247. * stored.
  248. *
  249. * If the heads indicate available messages, the length in the header
  250. * tells the start next message. A length == 0 for the next message
  251. * indicates a wrap-around to the beginning of the buffer.
  252. *
  253. * Every record carries the monotonic timestamp in microseconds, as well as
  254. * the standard userspace syslog level and syslog facility. The usual
  255. * kernel messages use LOG_KERN; userspace-injected messages always carry
  256. * a matching syslog facility, by default LOG_USER. The origin of every
  257. * message can be reliably determined that way.
  258. *
  259. * The human readable log message directly follows the message header. The
  260. * length of the message text is stored in the header, the stored message
  261. * is not terminated.
  262. *
  263. * Optionally, a message can carry a dictionary of properties (key/value pairs),
  264. * to provide userspace with a machine-readable message context.
  265. *
  266. * Examples for well-defined, commonly used property names are:
  267. * DEVICE=b12:8 device identifier
  268. * b12:8 block dev_t
  269. * c127:3 char dev_t
  270. * n8 netdev ifindex
  271. * +sound:card0 subsystem:devname
  272. * SUBSYSTEM=pci driver-core subsystem name
  273. *
  274. * Valid characters in property names are [a-zA-Z0-9.-_]. The plain text value
  275. * follows directly after a '=' character. Every property is terminated by
  276. * a '\0' character. The last property is not terminated.
  277. *
  278. * Example of a message structure:
  279. * 0000 ff 8f 00 00 00 00 00 00 monotonic time in nsec
  280. * 0008 34 00 record is 52 bytes long
  281. * 000a 0b 00 text is 11 bytes long
  282. * 000c 1f 00 dictionary is 23 bytes long
  283. * 000e 03 00 LOG_KERN (facility) LOG_ERR (level)
  284. * 0010 69 74 27 73 20 61 20 6c "it's a l"
  285. * 69 6e 65 "ine"
  286. * 001b 44 45 56 49 43 "DEVIC"
  287. * 45 3d 62 38 3a 32 00 44 "E=b8:2\0D"
  288. * 52 49 56 45 52 3d 62 75 "RIVER=bu"
  289. * 67 "g"
  290. * 0032 00 00 00 padding to next message header
  291. *
  292. * The 'struct printk_log' buffer header must never be directly exported to
  293. * userspace, it is a kernel-private implementation detail that might
  294. * need to be changed in the future, when the requirements change.
  295. *
  296. * /dev/kmsg exports the structured data in the following line format:
  297. * "<level>,<sequnum>,<timestamp>,<contflag>[,additional_values, ... ];<message text>\n"
  298. *
  299. * Users of the export format should ignore possible additional values
  300. * separated by ',', and find the message after the ';' character.
  301. *
  302. * The optional key/value pairs are attached as continuation lines starting
  303. * with a space character and terminated by a newline. All possible
  304. * non-prinatable characters are escaped in the "\xff" notation.
  305. */
  306. enum log_flags {
  307. LOG_NOCONS = 1, /* suppress print, do not print to console */
  308. LOG_NEWLINE = 2, /* text ended with a newline */
  309. LOG_PREFIX = 4, /* text started with a prefix */
  310. LOG_CONT = 8, /* text is a fragment of a continuation line */
  311. };
  312. struct printk_log {
  313. u64 ts_nsec; /* timestamp in nanoseconds */
  314. u16 len; /* length of entire record */
  315. u16 text_len; /* length of text buffer */
  316. u16 dict_len; /* length of dictionary buffer */
  317. u8 facility; /* syslog facility */
  318. u8 flags:5; /* internal record flags */
  319. u8 level:3; /* syslog level */
  320. }
  321. #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
  322. __packed __aligned(4)
  323. #endif
  324. ;
  325. /*
  326. * The logbuf_lock protects kmsg buffer, indices, counters. This can be taken
  327. * within the scheduler's rq lock. It must be released before calling
  328. * console_unlock() or anything else that might wake up a process.
  329. */
  330. DEFINE_RAW_SPINLOCK(logbuf_lock);
  331. /*
  332. * Helper macros to lock/unlock logbuf_lock and switch between
  333. * printk-safe/unsafe modes.
  334. */
  335. #define logbuf_lock_irq() \
  336. do { \
  337. printk_safe_enter_irq(); \
  338. raw_spin_lock(&logbuf_lock); \
  339. } while (0)
  340. #define logbuf_unlock_irq() \
  341. do { \
  342. raw_spin_unlock(&logbuf_lock); \
  343. printk_safe_exit_irq(); \
  344. } while (0)
  345. #define logbuf_lock_irqsave(flags) \
  346. do { \
  347. printk_safe_enter_irqsave(flags); \
  348. raw_spin_lock(&logbuf_lock); \
  349. } while (0)
  350. #define logbuf_unlock_irqrestore(flags) \
  351. do { \
  352. raw_spin_unlock(&logbuf_lock); \
  353. printk_safe_exit_irqrestore(flags); \
  354. } while (0)
  355. #ifdef CONFIG_PRINTK
  356. DECLARE_WAIT_QUEUE_HEAD(log_wait);
  357. /* the next printk record to read by syslog(READ) or /proc/kmsg */
  358. static u64 syslog_seq;
  359. static u32 syslog_idx;
  360. static size_t syslog_partial;
  361. /* index and sequence number of the first record stored in the buffer */
  362. static u64 log_first_seq;
  363. static u32 log_first_idx;
  364. /* index and sequence number of the next record to store in the buffer */
  365. static u64 log_next_seq;
  366. static u32 log_next_idx;
  367. /* the next printk record to write to the console */
  368. static u64 console_seq;
  369. static u32 console_idx;
  370. /* the next printk record to read after the last 'clear' command */
  371. static u64 clear_seq;
  372. static u32 clear_idx;
  373. #define PREFIX_MAX 32
  374. #define LOG_LINE_MAX (1024 - PREFIX_MAX)
  375. #define LOG_LEVEL(v) ((v) & 0x07)
  376. #define LOG_FACILITY(v) ((v) >> 3 & 0xff)
  377. /* record buffer */
  378. #define LOG_ALIGN __alignof__(struct printk_log)
  379. #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
  380. static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
  381. static char *log_buf = __log_buf;
  382. static u32 log_buf_len = __LOG_BUF_LEN;
  383. /* Return log buffer address */
  384. char *log_buf_addr_get(void)
  385. {
  386. return log_buf;
  387. }
  388. /* Return log buffer size */
  389. u32 log_buf_len_get(void)
  390. {
  391. return log_buf_len;
  392. }
  393. /* human readable text of the record */
  394. static char *log_text(const struct printk_log *msg)
  395. {
  396. return (char *)msg + sizeof(struct printk_log);
  397. }
  398. /* optional key/value pair dictionary attached to the record */
  399. static char *log_dict(const struct printk_log *msg)
  400. {
  401. return (char *)msg + sizeof(struct printk_log) + msg->text_len;
  402. }
  403. /* get record by index; idx must point to valid msg */
  404. static struct printk_log *log_from_idx(u32 idx)
  405. {
  406. struct printk_log *msg = (struct printk_log *)(log_buf + idx);
  407. /*
  408. * A length == 0 record is the end of buffer marker. Wrap around and
  409. * read the message at the start of the buffer.
  410. */
  411. if (!msg->len)
  412. return (struct printk_log *)log_buf;
  413. return msg;
  414. }
  415. /* get next record; idx must point to valid msg */
  416. static u32 log_next(u32 idx)
  417. {
  418. struct printk_log *msg = (struct printk_log *)(log_buf + idx);
  419. /* length == 0 indicates the end of the buffer; wrap */
  420. /*
  421. * A length == 0 record is the end of buffer marker. Wrap around and
  422. * read the message at the start of the buffer as *this* one, and
  423. * return the one after that.
  424. */
  425. if (!msg->len) {
  426. msg = (struct printk_log *)log_buf;
  427. return msg->len;
  428. }
  429. return idx + msg->len;
  430. }
  431. /*
  432. * Check whether there is enough free space for the given message.
  433. *
  434. * The same values of first_idx and next_idx mean that the buffer
  435. * is either empty or full.
  436. *
  437. * If the buffer is empty, we must respect the position of the indexes.
  438. * They cannot be reset to the beginning of the buffer.
  439. */
  440. static int logbuf_has_space(u32 msg_size, bool empty)
  441. {
  442. u32 free;
  443. if (log_next_idx > log_first_idx || empty)
  444. free = max(log_buf_len - log_next_idx, log_first_idx);
  445. else
  446. free = log_first_idx - log_next_idx;
  447. /*
  448. * We need space also for an empty header that signalizes wrapping
  449. * of the buffer.
  450. */
  451. return free >= msg_size + sizeof(struct printk_log);
  452. }
  453. static int log_make_free_space(u32 msg_size)
  454. {
  455. while (log_first_seq < log_next_seq &&
  456. !logbuf_has_space(msg_size, false)) {
  457. /* drop old messages until we have enough contiguous space */
  458. log_first_idx = log_next(log_first_idx);
  459. log_first_seq++;
  460. }
  461. if (clear_seq < log_first_seq) {
  462. clear_seq = log_first_seq;
  463. clear_idx = log_first_idx;
  464. }
  465. /* sequence numbers are equal, so the log buffer is empty */
  466. if (logbuf_has_space(msg_size, log_first_seq == log_next_seq))
  467. return 0;
  468. return -ENOMEM;
  469. }
  470. /* compute the message size including the padding bytes */
  471. static u32 msg_used_size(u16 text_len, u16 dict_len, u32 *pad_len)
  472. {
  473. u32 size;
  474. size = sizeof(struct printk_log) + text_len + dict_len;
  475. *pad_len = (-size) & (LOG_ALIGN - 1);
  476. size += *pad_len;
  477. return size;
  478. }
  479. /*
  480. * Define how much of the log buffer we could take at maximum. The value
  481. * must be greater than two. Note that only half of the buffer is available
  482. * when the index points to the middle.
  483. */
  484. #define MAX_LOG_TAKE_PART 4
  485. static const char trunc_msg[] = "<truncated>";
  486. static u32 truncate_msg(u16 *text_len, u16 *trunc_msg_len,
  487. u16 *dict_len, u32 *pad_len)
  488. {
  489. /*
  490. * The message should not take the whole buffer. Otherwise, it might
  491. * get removed too soon.
  492. */
  493. u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
  494. if (*text_len > max_text_len)
  495. *text_len = max_text_len;
  496. /* enable the warning message */
  497. *trunc_msg_len = strlen(trunc_msg);
  498. /* disable the "dict" completely */
  499. *dict_len = 0;
  500. /* compute the size again, count also the warning message */
  501. return msg_used_size(*text_len + *trunc_msg_len, 0, pad_len);
  502. }
  503. /* insert record into the buffer, discard old ones, update heads */
  504. static int log_store(int facility, int level,
  505. enum log_flags flags, u64 ts_nsec,
  506. const char *dict, u16 dict_len,
  507. const char *text, u16 text_len)
  508. {
  509. struct printk_log *msg;
  510. u32 size, pad_len;
  511. u16 trunc_msg_len = 0;
  512. /* number of '\0' padding bytes to next message */
  513. size = msg_used_size(text_len, dict_len, &pad_len);
  514. if (log_make_free_space(size)) {
  515. /* truncate the message if it is too long for empty buffer */
  516. size = truncate_msg(&text_len, &trunc_msg_len,
  517. &dict_len, &pad_len);
  518. /* survive when the log buffer is too small for trunc_msg */
  519. if (log_make_free_space(size))
  520. return 0;
  521. }
  522. if (log_next_idx + size + sizeof(struct printk_log) > log_buf_len) {
  523. /*
  524. * This message + an additional empty header does not fit
  525. * at the end of the buffer. Add an empty header with len == 0
  526. * to signify a wrap around.
  527. */
  528. memset(log_buf + log_next_idx, 0, sizeof(struct printk_log));
  529. log_next_idx = 0;
  530. }
  531. /* fill message */
  532. msg = (struct printk_log *)(log_buf + log_next_idx);
  533. memcpy(log_text(msg), text, text_len);
  534. msg->text_len = text_len;
  535. if (trunc_msg_len) {
  536. memcpy(log_text(msg) + text_len, trunc_msg, trunc_msg_len);
  537. msg->text_len += trunc_msg_len;
  538. }
  539. memcpy(log_dict(msg), dict, dict_len);
  540. msg->dict_len = dict_len;
  541. msg->facility = facility;
  542. msg->level = level & 7;
  543. msg->flags = flags & 0x1f;
  544. if (ts_nsec > 0)
  545. msg->ts_nsec = ts_nsec;
  546. else
  547. msg->ts_nsec = local_clock();
  548. memset(log_dict(msg) + dict_len, 0, pad_len);
  549. msg->len = size;
  550. /* insert message */
  551. log_next_idx += msg->len;
  552. log_next_seq++;
  553. return msg->text_len;
  554. }
  555. int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
  556. static int syslog_action_restricted(int type)
  557. {
  558. if (dmesg_restrict)
  559. return 1;
  560. /*
  561. * Unless restricted, we allow "read all" and "get buffer size"
  562. * for everybody.
  563. */
  564. return type != SYSLOG_ACTION_READ_ALL &&
  565. type != SYSLOG_ACTION_SIZE_BUFFER;
  566. }
  567. static int check_syslog_permissions(int type, int source)
  568. {
  569. /*
  570. * If this is from /proc/kmsg and we've already opened it, then we've
  571. * already done the capabilities checks at open time.
  572. */
  573. if (source == SYSLOG_FROM_PROC && type != SYSLOG_ACTION_OPEN)
  574. goto ok;
  575. if (syslog_action_restricted(type)) {
  576. if (capable(CAP_SYSLOG))
  577. goto ok;
  578. /*
  579. * For historical reasons, accept CAP_SYS_ADMIN too, with
  580. * a warning.
  581. */
  582. if (capable(CAP_SYS_ADMIN)) {
  583. pr_warn_once("%s (%d): Attempt to access syslog with "
  584. "CAP_SYS_ADMIN but no CAP_SYSLOG "
  585. "(deprecated).\n",
  586. current->comm, task_pid_nr(current));
  587. goto ok;
  588. }
  589. return -EPERM;
  590. }
  591. ok:
  592. return security_syslog(type);
  593. }
  594. static void append_char(char **pp, char *e, char c)
  595. {
  596. if (*pp < e)
  597. *(*pp)++ = c;
  598. }
  599. static ssize_t msg_print_ext_header(char *buf, size_t size,
  600. struct printk_log *msg, u64 seq)
  601. {
  602. u64 ts_usec = msg->ts_nsec;
  603. do_div(ts_usec, 1000);
  604. return scnprintf(buf, size, "%u,%llu,%llu,%c;",
  605. (msg->facility << 3) | msg->level, seq, ts_usec,
  606. msg->flags & LOG_CONT ? 'c' : '-');
  607. }
  608. static ssize_t msg_print_ext_body(char *buf, size_t size,
  609. char *dict, size_t dict_len,
  610. char *text, size_t text_len)
  611. {
  612. char *p = buf, *e = buf + size;
  613. size_t i;
  614. /* escape non-printable characters */
  615. for (i = 0; i < text_len; i++) {
  616. unsigned char c = text[i];
  617. if (c < ' ' || c >= 127 || c == '\\')
  618. p += scnprintf(p, e - p, "\\x%02x", c);
  619. else
  620. append_char(&p, e, c);
  621. }
  622. append_char(&p, e, '\n');
  623. if (dict_len) {
  624. bool line = true;
  625. for (i = 0; i < dict_len; i++) {
  626. unsigned char c = dict[i];
  627. if (line) {
  628. append_char(&p, e, ' ');
  629. line = false;
  630. }
  631. if (c == '\0') {
  632. append_char(&p, e, '\n');
  633. line = true;
  634. continue;
  635. }
  636. if (c < ' ' || c >= 127 || c == '\\') {
  637. p += scnprintf(p, e - p, "\\x%02x", c);
  638. continue;
  639. }
  640. append_char(&p, e, c);
  641. }
  642. append_char(&p, e, '\n');
  643. }
  644. return p - buf;
  645. }
  646. /* /dev/kmsg - userspace message inject/listen interface */
  647. struct devkmsg_user {
  648. u64 seq;
  649. u32 idx;
  650. struct ratelimit_state rs;
  651. struct mutex lock;
  652. char buf[CONSOLE_EXT_LOG_MAX];
  653. };
  654. static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
  655. {
  656. char *buf, *line;
  657. int level = default_message_loglevel;
  658. int facility = 1; /* LOG_USER */
  659. struct file *file = iocb->ki_filp;
  660. struct devkmsg_user *user = file->private_data;
  661. size_t len = iov_iter_count(from);
  662. ssize_t ret = len;
  663. if (!user || len > LOG_LINE_MAX)
  664. return -EINVAL;
  665. /* Ignore when user logging is disabled. */
  666. if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
  667. return len;
  668. /* Ratelimit when not explicitly enabled. */
  669. if (!(devkmsg_log & DEVKMSG_LOG_MASK_ON)) {
  670. if (!___ratelimit(&user->rs, current->comm))
  671. return ret;
  672. }
  673. buf = kmalloc(len+1, GFP_KERNEL);
  674. if (buf == NULL)
  675. return -ENOMEM;
  676. buf[len] = '\0';
  677. if (!copy_from_iter_full(buf, len, from)) {
  678. kfree(buf);
  679. return -EFAULT;
  680. }
  681. /*
  682. * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
  683. * the decimal value represents 32bit, the lower 3 bit are the log
  684. * level, the rest are the log facility.
  685. *
  686. * If no prefix or no userspace facility is specified, we
  687. * enforce LOG_USER, to be able to reliably distinguish
  688. * kernel-generated messages from userspace-injected ones.
  689. */
  690. line = buf;
  691. if (line[0] == '<') {
  692. char *endp = NULL;
  693. unsigned int u;
  694. u = simple_strtoul(line + 1, &endp, 10);
  695. if (endp && endp[0] == '>') {
  696. level = LOG_LEVEL(u);
  697. if (LOG_FACILITY(u) != 0)
  698. facility = LOG_FACILITY(u);
  699. endp++;
  700. len -= endp - line;
  701. line = endp;
  702. }
  703. }
  704. printk_emit(facility, level, NULL, 0, "%s", line);
  705. kfree(buf);
  706. return ret;
  707. }
  708. static ssize_t devkmsg_read(struct file *file, char __user *buf,
  709. size_t count, loff_t *ppos)
  710. {
  711. struct devkmsg_user *user = file->private_data;
  712. struct printk_log *msg;
  713. size_t len;
  714. ssize_t ret;
  715. if (!user)
  716. return -EBADF;
  717. ret = mutex_lock_interruptible(&user->lock);
  718. if (ret)
  719. return ret;
  720. logbuf_lock_irq();
  721. while (user->seq == log_next_seq) {
  722. if (file->f_flags & O_NONBLOCK) {
  723. ret = -EAGAIN;
  724. logbuf_unlock_irq();
  725. goto out;
  726. }
  727. logbuf_unlock_irq();
  728. ret = wait_event_interruptible(log_wait,
  729. user->seq != log_next_seq);
  730. if (ret)
  731. goto out;
  732. logbuf_lock_irq();
  733. }
  734. if (user->seq < log_first_seq) {
  735. /* our last seen message is gone, return error and reset */
  736. user->idx = log_first_idx;
  737. user->seq = log_first_seq;
  738. ret = -EPIPE;
  739. logbuf_unlock_irq();
  740. goto out;
  741. }
  742. msg = log_from_idx(user->idx);
  743. len = msg_print_ext_header(user->buf, sizeof(user->buf),
  744. msg, user->seq);
  745. len += msg_print_ext_body(user->buf + len, sizeof(user->buf) - len,
  746. log_dict(msg), msg->dict_len,
  747. log_text(msg), msg->text_len);
  748. user->idx = log_next(user->idx);
  749. user->seq++;
  750. logbuf_unlock_irq();
  751. if (len > count) {
  752. ret = -EINVAL;
  753. goto out;
  754. }
  755. if (copy_to_user(buf, user->buf, len)) {
  756. ret = -EFAULT;
  757. goto out;
  758. }
  759. ret = len;
  760. out:
  761. mutex_unlock(&user->lock);
  762. return ret;
  763. }
  764. static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
  765. {
  766. struct devkmsg_user *user = file->private_data;
  767. loff_t ret = 0;
  768. if (!user)
  769. return -EBADF;
  770. if (offset)
  771. return -ESPIPE;
  772. logbuf_lock_irq();
  773. switch (whence) {
  774. case SEEK_SET:
  775. /* the first record */
  776. user->idx = log_first_idx;
  777. user->seq = log_first_seq;
  778. break;
  779. case SEEK_DATA:
  780. /*
  781. * The first record after the last SYSLOG_ACTION_CLEAR,
  782. * like issued by 'dmesg -c'. Reading /dev/kmsg itself
  783. * changes no global state, and does not clear anything.
  784. */
  785. user->idx = clear_idx;
  786. user->seq = clear_seq;
  787. break;
  788. case SEEK_END:
  789. /* after the last record */
  790. user->idx = log_next_idx;
  791. user->seq = log_next_seq;
  792. break;
  793. default:
  794. ret = -EINVAL;
  795. }
  796. logbuf_unlock_irq();
  797. return ret;
  798. }
  799. static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
  800. {
  801. struct devkmsg_user *user = file->private_data;
  802. __poll_t ret = 0;
  803. if (!user)
  804. return EPOLLERR|EPOLLNVAL;
  805. poll_wait(file, &log_wait, wait);
  806. logbuf_lock_irq();
  807. if (user->seq < log_next_seq) {
  808. /* return error when data has vanished underneath us */
  809. if (user->seq < log_first_seq)
  810. ret = EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
  811. else
  812. ret = EPOLLIN|EPOLLRDNORM;
  813. }
  814. logbuf_unlock_irq();
  815. return ret;
  816. }
  817. static int devkmsg_open(struct inode *inode, struct file *file)
  818. {
  819. struct devkmsg_user *user;
  820. int err;
  821. if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
  822. return -EPERM;
  823. /* write-only does not need any file context */
  824. if ((file->f_flags & O_ACCMODE) != O_WRONLY) {
  825. err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
  826. SYSLOG_FROM_READER);
  827. if (err)
  828. return err;
  829. }
  830. user = kmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
  831. if (!user)
  832. return -ENOMEM;
  833. ratelimit_default_init(&user->rs);
  834. ratelimit_set_flags(&user->rs, RATELIMIT_MSG_ON_RELEASE);
  835. mutex_init(&user->lock);
  836. logbuf_lock_irq();
  837. user->idx = log_first_idx;
  838. user->seq = log_first_seq;
  839. logbuf_unlock_irq();
  840. file->private_data = user;
  841. return 0;
  842. }
  843. static int devkmsg_release(struct inode *inode, struct file *file)
  844. {
  845. struct devkmsg_user *user = file->private_data;
  846. if (!user)
  847. return 0;
  848. ratelimit_state_exit(&user->rs);
  849. mutex_destroy(&user->lock);
  850. kfree(user);
  851. return 0;
  852. }
  853. const struct file_operations kmsg_fops = {
  854. .open = devkmsg_open,
  855. .read = devkmsg_read,
  856. .write_iter = devkmsg_write,
  857. .llseek = devkmsg_llseek,
  858. .poll = devkmsg_poll,
  859. .release = devkmsg_release,
  860. };
  861. #ifdef CONFIG_CRASH_CORE
  862. /*
  863. * This appends the listed symbols to /proc/vmcore
  864. *
  865. * /proc/vmcore is used by various utilities, like crash and makedumpfile to
  866. * obtain access to symbols that are otherwise very difficult to locate. These
  867. * symbols are specifically used so that utilities can access and extract the
  868. * dmesg log from a vmcore file after a crash.
  869. */
  870. void log_buf_vmcoreinfo_setup(void)
  871. {
  872. VMCOREINFO_SYMBOL(log_buf);
  873. VMCOREINFO_SYMBOL(log_buf_len);
  874. VMCOREINFO_SYMBOL(log_first_idx);
  875. VMCOREINFO_SYMBOL(clear_idx);
  876. VMCOREINFO_SYMBOL(log_next_idx);
  877. /*
  878. * Export struct printk_log size and field offsets. User space tools can
  879. * parse it and detect any changes to structure down the line.
  880. */
  881. VMCOREINFO_STRUCT_SIZE(printk_log);
  882. VMCOREINFO_OFFSET(printk_log, ts_nsec);
  883. VMCOREINFO_OFFSET(printk_log, len);
  884. VMCOREINFO_OFFSET(printk_log, text_len);
  885. VMCOREINFO_OFFSET(printk_log, dict_len);
  886. }
  887. #endif
  888. /* requested log_buf_len from kernel cmdline */
  889. static unsigned long __initdata new_log_buf_len;
  890. /* we practice scaling the ring buffer by powers of 2 */
  891. static void __init log_buf_len_update(unsigned size)
  892. {
  893. if (size)
  894. size = roundup_pow_of_two(size);
  895. if (size > log_buf_len)
  896. new_log_buf_len = size;
  897. }
  898. /* save requested log_buf_len since it's too early to process it */
  899. static int __init log_buf_len_setup(char *str)
  900. {
  901. unsigned size = memparse(str, &str);
  902. log_buf_len_update(size);
  903. return 0;
  904. }
  905. early_param("log_buf_len", log_buf_len_setup);
  906. #ifdef CONFIG_SMP
  907. #define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
  908. static void __init log_buf_add_cpu(void)
  909. {
  910. unsigned int cpu_extra;
  911. /*
  912. * archs should set up cpu_possible_bits properly with
  913. * set_cpu_possible() after setup_arch() but just in
  914. * case lets ensure this is valid.
  915. */
  916. if (num_possible_cpus() == 1)
  917. return;
  918. cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
  919. /* by default this will only continue through for large > 64 CPUs */
  920. if (cpu_extra <= __LOG_BUF_LEN / 2)
  921. return;
  922. pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
  923. __LOG_CPU_MAX_BUF_LEN);
  924. pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
  925. cpu_extra);
  926. pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
  927. log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
  928. }
  929. #else /* !CONFIG_SMP */
  930. static inline void log_buf_add_cpu(void) {}
  931. #endif /* CONFIG_SMP */
  932. void __init setup_log_buf(int early)
  933. {
  934. unsigned long flags;
  935. char *new_log_buf;
  936. int free;
  937. if (log_buf != __log_buf)
  938. return;
  939. if (!early && !new_log_buf_len)
  940. log_buf_add_cpu();
  941. if (!new_log_buf_len)
  942. return;
  943. if (early) {
  944. new_log_buf =
  945. memblock_virt_alloc(new_log_buf_len, LOG_ALIGN);
  946. } else {
  947. new_log_buf = memblock_virt_alloc_nopanic(new_log_buf_len,
  948. LOG_ALIGN);
  949. }
  950. if (unlikely(!new_log_buf)) {
  951. pr_err("log_buf_len: %ld bytes not available\n",
  952. new_log_buf_len);
  953. return;
  954. }
  955. logbuf_lock_irqsave(flags);
  956. log_buf_len = new_log_buf_len;
  957. log_buf = new_log_buf;
  958. new_log_buf_len = 0;
  959. free = __LOG_BUF_LEN - log_next_idx;
  960. memcpy(log_buf, __log_buf, __LOG_BUF_LEN);
  961. logbuf_unlock_irqrestore(flags);
  962. pr_info("log_buf_len: %d bytes\n", log_buf_len);
  963. pr_info("early log buf free: %d(%d%%)\n",
  964. free, (free * 100) / __LOG_BUF_LEN);
  965. }
  966. static bool __read_mostly ignore_loglevel;
  967. static int __init ignore_loglevel_setup(char *str)
  968. {
  969. ignore_loglevel = true;
  970. pr_info("debug: ignoring loglevel setting.\n");
  971. return 0;
  972. }
  973. early_param("ignore_loglevel", ignore_loglevel_setup);
  974. module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
  975. MODULE_PARM_DESC(ignore_loglevel,
  976. "ignore loglevel setting (prints all kernel messages to the console)");
  977. static bool suppress_message_printing(int level)
  978. {
  979. return (level >= console_loglevel && !ignore_loglevel);
  980. }
  981. #ifdef CONFIG_BOOT_PRINTK_DELAY
  982. static int boot_delay; /* msecs delay after each printk during bootup */
  983. static unsigned long long loops_per_msec; /* based on boot_delay */
  984. static int __init boot_delay_setup(char *str)
  985. {
  986. unsigned long lpj;
  987. lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
  988. loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
  989. get_option(&str, &boot_delay);
  990. if (boot_delay > 10 * 1000)
  991. boot_delay = 0;
  992. pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
  993. "HZ: %d, loops_per_msec: %llu\n",
  994. boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
  995. return 0;
  996. }
  997. early_param("boot_delay", boot_delay_setup);
  998. static void boot_delay_msec(int level)
  999. {
  1000. unsigned long long k;
  1001. unsigned long timeout;
  1002. if ((boot_delay == 0 || system_state >= SYSTEM_RUNNING)
  1003. || suppress_message_printing(level)) {
  1004. return;
  1005. }
  1006. k = (unsigned long long)loops_per_msec * boot_delay;
  1007. timeout = jiffies + msecs_to_jiffies(boot_delay);
  1008. while (k) {
  1009. k--;
  1010. cpu_relax();
  1011. /*
  1012. * use (volatile) jiffies to prevent
  1013. * compiler reduction; loop termination via jiffies
  1014. * is secondary and may or may not happen.
  1015. */
  1016. if (time_after(jiffies, timeout))
  1017. break;
  1018. touch_nmi_watchdog();
  1019. }
  1020. }
  1021. #else
  1022. static inline void boot_delay_msec(int level)
  1023. {
  1024. }
  1025. #endif
  1026. static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
  1027. module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
  1028. static size_t print_time(u64 ts, char *buf)
  1029. {
  1030. unsigned long rem_nsec;
  1031. if (!printk_time)
  1032. return 0;
  1033. rem_nsec = do_div(ts, 1000000000);
  1034. if (!buf)
  1035. return snprintf(NULL, 0, "[%5lu.000000] ", (unsigned long)ts);
  1036. return sprintf(buf, "[%5lu.%06lu] ",
  1037. (unsigned long)ts, rem_nsec / 1000);
  1038. }
  1039. static size_t print_prefix(const struct printk_log *msg, bool syslog, char *buf)
  1040. {
  1041. size_t len = 0;
  1042. unsigned int prefix = (msg->facility << 3) | msg->level;
  1043. if (syslog) {
  1044. if (buf) {
  1045. len += sprintf(buf, "<%u>", prefix);
  1046. } else {
  1047. len += 3;
  1048. if (prefix > 999)
  1049. len += 3;
  1050. else if (prefix > 99)
  1051. len += 2;
  1052. else if (prefix > 9)
  1053. len++;
  1054. }
  1055. }
  1056. len += print_time(msg->ts_nsec, buf ? buf + len : NULL);
  1057. return len;
  1058. }
  1059. static size_t msg_print_text(const struct printk_log *msg, bool syslog, char *buf, size_t size)
  1060. {
  1061. const char *text = log_text(msg);
  1062. size_t text_size = msg->text_len;
  1063. size_t len = 0;
  1064. do {
  1065. const char *next = memchr(text, '\n', text_size);
  1066. size_t text_len;
  1067. if (next) {
  1068. text_len = next - text;
  1069. next++;
  1070. text_size -= next - text;
  1071. } else {
  1072. text_len = text_size;
  1073. }
  1074. if (buf) {
  1075. if (print_prefix(msg, syslog, NULL) +
  1076. text_len + 1 >= size - len)
  1077. break;
  1078. len += print_prefix(msg, syslog, buf + len);
  1079. memcpy(buf + len, text, text_len);
  1080. len += text_len;
  1081. buf[len++] = '\n';
  1082. } else {
  1083. /* SYSLOG_ACTION_* buffer size only calculation */
  1084. len += print_prefix(msg, syslog, NULL);
  1085. len += text_len;
  1086. len++;
  1087. }
  1088. text = next;
  1089. } while (text);
  1090. return len;
  1091. }
  1092. static int syslog_print(char __user *buf, int size)
  1093. {
  1094. char *text;
  1095. struct printk_log *msg;
  1096. int len = 0;
  1097. text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
  1098. if (!text)
  1099. return -ENOMEM;
  1100. while (size > 0) {
  1101. size_t n;
  1102. size_t skip;
  1103. logbuf_lock_irq();
  1104. if (syslog_seq < log_first_seq) {
  1105. /* messages are gone, move to first one */
  1106. syslog_seq = log_first_seq;
  1107. syslog_idx = log_first_idx;
  1108. syslog_partial = 0;
  1109. }
  1110. if (syslog_seq == log_next_seq) {
  1111. logbuf_unlock_irq();
  1112. break;
  1113. }
  1114. skip = syslog_partial;
  1115. msg = log_from_idx(syslog_idx);
  1116. n = msg_print_text(msg, true, text, LOG_LINE_MAX + PREFIX_MAX);
  1117. if (n - syslog_partial <= size) {
  1118. /* message fits into buffer, move forward */
  1119. syslog_idx = log_next(syslog_idx);
  1120. syslog_seq++;
  1121. n -= syslog_partial;
  1122. syslog_partial = 0;
  1123. } else if (!len){
  1124. /* partial read(), remember position */
  1125. n = size;
  1126. syslog_partial += n;
  1127. } else
  1128. n = 0;
  1129. logbuf_unlock_irq();
  1130. if (!n)
  1131. break;
  1132. if (copy_to_user(buf, text + skip, n)) {
  1133. if (!len)
  1134. len = -EFAULT;
  1135. break;
  1136. }
  1137. len += n;
  1138. size -= n;
  1139. buf += n;
  1140. }
  1141. kfree(text);
  1142. return len;
  1143. }
  1144. static int syslog_print_all(char __user *buf, int size, bool clear)
  1145. {
  1146. char *text;
  1147. int len = 0;
  1148. u64 next_seq;
  1149. u64 seq;
  1150. u32 idx;
  1151. text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
  1152. if (!text)
  1153. return -ENOMEM;
  1154. logbuf_lock_irq();
  1155. /*
  1156. * Find first record that fits, including all following records,
  1157. * into the user-provided buffer for this dump.
  1158. */
  1159. seq = clear_seq;
  1160. idx = clear_idx;
  1161. while (seq < log_next_seq) {
  1162. struct printk_log *msg = log_from_idx(idx);
  1163. len += msg_print_text(msg, true, NULL, 0);
  1164. idx = log_next(idx);
  1165. seq++;
  1166. }
  1167. /* move first record forward until length fits into the buffer */
  1168. seq = clear_seq;
  1169. idx = clear_idx;
  1170. while (len > size && seq < log_next_seq) {
  1171. struct printk_log *msg = log_from_idx(idx);
  1172. len -= msg_print_text(msg, true, NULL, 0);
  1173. idx = log_next(idx);
  1174. seq++;
  1175. }
  1176. /* last message fitting into this dump */
  1177. next_seq = log_next_seq;
  1178. len = 0;
  1179. while (len >= 0 && seq < next_seq) {
  1180. struct printk_log *msg = log_from_idx(idx);
  1181. int textlen;
  1182. textlen = msg_print_text(msg, true, text,
  1183. LOG_LINE_MAX + PREFIX_MAX);
  1184. if (textlen < 0) {
  1185. len = textlen;
  1186. break;
  1187. }
  1188. idx = log_next(idx);
  1189. seq++;
  1190. logbuf_unlock_irq();
  1191. if (copy_to_user(buf + len, text, textlen))
  1192. len = -EFAULT;
  1193. else
  1194. len += textlen;
  1195. logbuf_lock_irq();
  1196. if (seq < log_first_seq) {
  1197. /* messages are gone, move to next one */
  1198. seq = log_first_seq;
  1199. idx = log_first_idx;
  1200. }
  1201. }
  1202. if (clear) {
  1203. clear_seq = log_next_seq;
  1204. clear_idx = log_next_idx;
  1205. }
  1206. logbuf_unlock_irq();
  1207. kfree(text);
  1208. return len;
  1209. }
  1210. static void syslog_clear(void)
  1211. {
  1212. logbuf_lock_irq();
  1213. clear_seq = log_next_seq;
  1214. clear_idx = log_next_idx;
  1215. logbuf_unlock_irq();
  1216. }
  1217. int do_syslog(int type, char __user *buf, int len, int source)
  1218. {
  1219. bool clear = false;
  1220. static int saved_console_loglevel = LOGLEVEL_DEFAULT;
  1221. int error;
  1222. error = check_syslog_permissions(type, source);
  1223. if (error)
  1224. return error;
  1225. switch (type) {
  1226. case SYSLOG_ACTION_CLOSE: /* Close log */
  1227. break;
  1228. case SYSLOG_ACTION_OPEN: /* Open log */
  1229. break;
  1230. case SYSLOG_ACTION_READ: /* Read from log */
  1231. if (!buf || len < 0)
  1232. return -EINVAL;
  1233. if (!len)
  1234. return 0;
  1235. if (!access_ok(VERIFY_WRITE, buf, len))
  1236. return -EFAULT;
  1237. error = wait_event_interruptible(log_wait,
  1238. syslog_seq != log_next_seq);
  1239. if (error)
  1240. return error;
  1241. error = syslog_print(buf, len);
  1242. break;
  1243. /* Read/clear last kernel messages */
  1244. case SYSLOG_ACTION_READ_CLEAR:
  1245. clear = true;
  1246. /* FALL THRU */
  1247. /* Read last kernel messages */
  1248. case SYSLOG_ACTION_READ_ALL:
  1249. if (!buf || len < 0)
  1250. return -EINVAL;
  1251. if (!len)
  1252. return 0;
  1253. if (!access_ok(VERIFY_WRITE, buf, len))
  1254. return -EFAULT;
  1255. error = syslog_print_all(buf, len, clear);
  1256. break;
  1257. /* Clear ring buffer */
  1258. case SYSLOG_ACTION_CLEAR:
  1259. syslog_clear();
  1260. break;
  1261. /* Disable logging to console */
  1262. case SYSLOG_ACTION_CONSOLE_OFF:
  1263. if (saved_console_loglevel == LOGLEVEL_DEFAULT)
  1264. saved_console_loglevel = console_loglevel;
  1265. console_loglevel = minimum_console_loglevel;
  1266. break;
  1267. /* Enable logging to console */
  1268. case SYSLOG_ACTION_CONSOLE_ON:
  1269. if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
  1270. console_loglevel = saved_console_loglevel;
  1271. saved_console_loglevel = LOGLEVEL_DEFAULT;
  1272. }
  1273. break;
  1274. /* Set level of messages printed to console */
  1275. case SYSLOG_ACTION_CONSOLE_LEVEL:
  1276. if (len < 1 || len > 8)
  1277. return -EINVAL;
  1278. if (len < minimum_console_loglevel)
  1279. len = minimum_console_loglevel;
  1280. console_loglevel = len;
  1281. /* Implicitly re-enable logging to console */
  1282. saved_console_loglevel = LOGLEVEL_DEFAULT;
  1283. break;
  1284. /* Number of chars in the log buffer */
  1285. case SYSLOG_ACTION_SIZE_UNREAD:
  1286. logbuf_lock_irq();
  1287. if (syslog_seq < log_first_seq) {
  1288. /* messages are gone, move to first one */
  1289. syslog_seq = log_first_seq;
  1290. syslog_idx = log_first_idx;
  1291. syslog_partial = 0;
  1292. }
  1293. if (source == SYSLOG_FROM_PROC) {
  1294. /*
  1295. * Short-cut for poll(/"proc/kmsg") which simply checks
  1296. * for pending data, not the size; return the count of
  1297. * records, not the length.
  1298. */
  1299. error = log_next_seq - syslog_seq;
  1300. } else {
  1301. u64 seq = syslog_seq;
  1302. u32 idx = syslog_idx;
  1303. while (seq < log_next_seq) {
  1304. struct printk_log *msg = log_from_idx(idx);
  1305. error += msg_print_text(msg, true, NULL, 0);
  1306. idx = log_next(idx);
  1307. seq++;
  1308. }
  1309. error -= syslog_partial;
  1310. }
  1311. logbuf_unlock_irq();
  1312. break;
  1313. /* Size of the log buffer */
  1314. case SYSLOG_ACTION_SIZE_BUFFER:
  1315. error = log_buf_len;
  1316. break;
  1317. default:
  1318. error = -EINVAL;
  1319. break;
  1320. }
  1321. return error;
  1322. }
  1323. SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
  1324. {
  1325. return do_syslog(type, buf, len, SYSLOG_FROM_READER);
  1326. }
  1327. /*
  1328. * Special console_lock variants that help to reduce the risk of soft-lockups.
  1329. * They allow to pass console_lock to another printk() call using a busy wait.
  1330. */
  1331. #ifdef CONFIG_LOCKDEP
  1332. static struct lockdep_map console_owner_dep_map = {
  1333. .name = "console_owner"
  1334. };
  1335. #endif
  1336. static DEFINE_RAW_SPINLOCK(console_owner_lock);
  1337. static struct task_struct *console_owner;
  1338. static bool console_waiter;
  1339. /**
  1340. * console_lock_spinning_enable - mark beginning of code where another
  1341. * thread might safely busy wait
  1342. *
  1343. * This basically converts console_lock into a spinlock. This marks
  1344. * the section where the console_lock owner can not sleep, because
  1345. * there may be a waiter spinning (like a spinlock). Also it must be
  1346. * ready to hand over the lock at the end of the section.
  1347. */
  1348. static void console_lock_spinning_enable(void)
  1349. {
  1350. raw_spin_lock(&console_owner_lock);
  1351. console_owner = current;
  1352. raw_spin_unlock(&console_owner_lock);
  1353. /* The waiter may spin on us after setting console_owner */
  1354. spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
  1355. }
  1356. /**
  1357. * console_lock_spinning_disable_and_check - mark end of code where another
  1358. * thread was able to busy wait and check if there is a waiter
  1359. *
  1360. * This is called at the end of the section where spinning is allowed.
  1361. * It has two functions. First, it is a signal that it is no longer
  1362. * safe to start busy waiting for the lock. Second, it checks if
  1363. * there is a busy waiter and passes the lock rights to her.
  1364. *
  1365. * Important: Callers lose the lock if there was a busy waiter.
  1366. * They must not touch items synchronized by console_lock
  1367. * in this case.
  1368. *
  1369. * Return: 1 if the lock rights were passed, 0 otherwise.
  1370. */
  1371. static int console_lock_spinning_disable_and_check(void)
  1372. {
  1373. int waiter;
  1374. raw_spin_lock(&console_owner_lock);
  1375. waiter = READ_ONCE(console_waiter);
  1376. console_owner = NULL;
  1377. raw_spin_unlock(&console_owner_lock);
  1378. if (!waiter) {
  1379. spin_release(&console_owner_dep_map, 1, _THIS_IP_);
  1380. return 0;
  1381. }
  1382. /* The waiter is now free to continue */
  1383. WRITE_ONCE(console_waiter, false);
  1384. spin_release(&console_owner_dep_map, 1, _THIS_IP_);
  1385. /*
  1386. * Hand off console_lock to waiter. The waiter will perform
  1387. * the up(). After this, the waiter is the console_lock owner.
  1388. */
  1389. mutex_release(&console_lock_dep_map, 1, _THIS_IP_);
  1390. return 1;
  1391. }
  1392. /**
  1393. * console_trylock_spinning - try to get console_lock by busy waiting
  1394. *
  1395. * This allows to busy wait for the console_lock when the current
  1396. * owner is running in specially marked sections. It means that
  1397. * the current owner is running and cannot reschedule until it
  1398. * is ready to lose the lock.
  1399. *
  1400. * Return: 1 if we got the lock, 0 othrewise
  1401. */
  1402. static int console_trylock_spinning(void)
  1403. {
  1404. struct task_struct *owner = NULL;
  1405. bool waiter;
  1406. bool spin = false;
  1407. unsigned long flags;
  1408. if (console_trylock())
  1409. return 1;
  1410. printk_safe_enter_irqsave(flags);
  1411. raw_spin_lock(&console_owner_lock);
  1412. owner = READ_ONCE(console_owner);
  1413. waiter = READ_ONCE(console_waiter);
  1414. if (!waiter && owner && owner != current) {
  1415. WRITE_ONCE(console_waiter, true);
  1416. spin = true;
  1417. }
  1418. raw_spin_unlock(&console_owner_lock);
  1419. /*
  1420. * If there is an active printk() writing to the
  1421. * consoles, instead of having it write our data too,
  1422. * see if we can offload that load from the active
  1423. * printer, and do some printing ourselves.
  1424. * Go into a spin only if there isn't already a waiter
  1425. * spinning, and there is an active printer, and
  1426. * that active printer isn't us (recursive printk?).
  1427. */
  1428. if (!spin) {
  1429. printk_safe_exit_irqrestore(flags);
  1430. return 0;
  1431. }
  1432. /* We spin waiting for the owner to release us */
  1433. spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
  1434. /* Owner will clear console_waiter on hand off */
  1435. while (READ_ONCE(console_waiter))
  1436. cpu_relax();
  1437. spin_release(&console_owner_dep_map, 1, _THIS_IP_);
  1438. printk_safe_exit_irqrestore(flags);
  1439. /*
  1440. * The owner passed the console lock to us.
  1441. * Since we did not spin on console lock, annotate
  1442. * this as a trylock. Otherwise lockdep will
  1443. * complain.
  1444. */
  1445. mutex_acquire(&console_lock_dep_map, 0, 1, _THIS_IP_);
  1446. return 1;
  1447. }
  1448. /*
  1449. * Call the console drivers, asking them to write out
  1450. * log_buf[start] to log_buf[end - 1].
  1451. * The console_lock must be held.
  1452. */
  1453. static void call_console_drivers(const char *ext_text, size_t ext_len,
  1454. const char *text, size_t len)
  1455. {
  1456. struct console *con;
  1457. trace_console_rcuidle(text, len);
  1458. if (!console_drivers)
  1459. return;
  1460. for_each_console(con) {
  1461. if (exclusive_console && con != exclusive_console)
  1462. continue;
  1463. if (!(con->flags & CON_ENABLED))
  1464. continue;
  1465. if (!con->write)
  1466. continue;
  1467. if (!cpu_online(smp_processor_id()) &&
  1468. !(con->flags & CON_ANYTIME))
  1469. continue;
  1470. if (con->flags & CON_EXTENDED)
  1471. con->write(con, ext_text, ext_len);
  1472. else
  1473. con->write(con, text, len);
  1474. }
  1475. }
  1476. int printk_delay_msec __read_mostly;
  1477. static inline void printk_delay(void)
  1478. {
  1479. if (unlikely(printk_delay_msec)) {
  1480. int m = printk_delay_msec;
  1481. while (m--) {
  1482. mdelay(1);
  1483. touch_nmi_watchdog();
  1484. }
  1485. }
  1486. }
  1487. /*
  1488. * Continuation lines are buffered, and not committed to the record buffer
  1489. * until the line is complete, or a race forces it. The line fragments
  1490. * though, are printed immediately to the consoles to ensure everything has
  1491. * reached the console in case of a kernel crash.
  1492. */
  1493. static struct cont {
  1494. char buf[LOG_LINE_MAX];
  1495. size_t len; /* length == 0 means unused buffer */
  1496. struct task_struct *owner; /* task of first print*/
  1497. u64 ts_nsec; /* time of first print */
  1498. u8 level; /* log level of first message */
  1499. u8 facility; /* log facility of first message */
  1500. enum log_flags flags; /* prefix, newline flags */
  1501. } cont;
  1502. static void cont_flush(void)
  1503. {
  1504. if (cont.len == 0)
  1505. return;
  1506. log_store(cont.facility, cont.level, cont.flags, cont.ts_nsec,
  1507. NULL, 0, cont.buf, cont.len);
  1508. cont.len = 0;
  1509. }
  1510. static bool cont_add(int facility, int level, enum log_flags flags, const char *text, size_t len)
  1511. {
  1512. /*
  1513. * If ext consoles are present, flush and skip in-kernel
  1514. * continuation. See nr_ext_console_drivers definition. Also, if
  1515. * the line gets too long, split it up in separate records.
  1516. */
  1517. if (nr_ext_console_drivers || cont.len + len > sizeof(cont.buf)) {
  1518. cont_flush();
  1519. return false;
  1520. }
  1521. if (!cont.len) {
  1522. cont.facility = facility;
  1523. cont.level = level;
  1524. cont.owner = current;
  1525. cont.ts_nsec = local_clock();
  1526. cont.flags = flags;
  1527. }
  1528. memcpy(cont.buf + cont.len, text, len);
  1529. cont.len += len;
  1530. // The original flags come from the first line,
  1531. // but later continuations can add a newline.
  1532. if (flags & LOG_NEWLINE) {
  1533. cont.flags |= LOG_NEWLINE;
  1534. cont_flush();
  1535. }
  1536. if (cont.len > (sizeof(cont.buf) * 80) / 100)
  1537. cont_flush();
  1538. return true;
  1539. }
  1540. static size_t log_output(int facility, int level, enum log_flags lflags, const char *dict, size_t dictlen, char *text, size_t text_len)
  1541. {
  1542. /*
  1543. * If an earlier line was buffered, and we're a continuation
  1544. * write from the same process, try to add it to the buffer.
  1545. */
  1546. if (cont.len) {
  1547. if (cont.owner == current && (lflags & LOG_CONT)) {
  1548. if (cont_add(facility, level, lflags, text, text_len))
  1549. return text_len;
  1550. }
  1551. /* Otherwise, make sure it's flushed */
  1552. cont_flush();
  1553. }
  1554. /* Skip empty continuation lines that couldn't be added - they just flush */
  1555. if (!text_len && (lflags & LOG_CONT))
  1556. return 0;
  1557. /* If it doesn't end in a newline, try to buffer the current line */
  1558. if (!(lflags & LOG_NEWLINE)) {
  1559. if (cont_add(facility, level, lflags, text, text_len))
  1560. return text_len;
  1561. }
  1562. /* Store it in the record log */
  1563. return log_store(facility, level, lflags, 0, dict, dictlen, text, text_len);
  1564. }
  1565. /* Must be called under logbuf_lock. */
  1566. int vprintk_store(int facility, int level,
  1567. const char *dict, size_t dictlen,
  1568. const char *fmt, va_list args)
  1569. {
  1570. static char textbuf[LOG_LINE_MAX];
  1571. char *text = textbuf;
  1572. size_t text_len;
  1573. enum log_flags lflags = 0;
  1574. /*
  1575. * The printf needs to come first; we need the syslog
  1576. * prefix which might be passed-in as a parameter.
  1577. */
  1578. text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
  1579. /* mark and strip a trailing newline */
  1580. if (text_len && text[text_len-1] == '\n') {
  1581. text_len--;
  1582. lflags |= LOG_NEWLINE;
  1583. }
  1584. /* strip kernel syslog prefix and extract log level or control flags */
  1585. if (facility == 0) {
  1586. int kern_level;
  1587. while ((kern_level = printk_get_level(text)) != 0) {
  1588. switch (kern_level) {
  1589. case '0' ... '7':
  1590. if (level == LOGLEVEL_DEFAULT)
  1591. level = kern_level - '0';
  1592. /* fallthrough */
  1593. case 'd': /* KERN_DEFAULT */
  1594. lflags |= LOG_PREFIX;
  1595. break;
  1596. case 'c': /* KERN_CONT */
  1597. lflags |= LOG_CONT;
  1598. }
  1599. text_len -= 2;
  1600. text += 2;
  1601. }
  1602. }
  1603. if (level == LOGLEVEL_DEFAULT)
  1604. level = default_message_loglevel;
  1605. if (dict)
  1606. lflags |= LOG_PREFIX|LOG_NEWLINE;
  1607. if (suppress_message_printing(level))
  1608. lflags |= LOG_NOCONS;
  1609. return log_output(facility, level, lflags,
  1610. dict, dictlen, text, text_len);
  1611. }
  1612. asmlinkage int vprintk_emit(int facility, int level,
  1613. const char *dict, size_t dictlen,
  1614. const char *fmt, va_list args)
  1615. {
  1616. int printed_len;
  1617. bool in_sched = false;
  1618. unsigned long flags;
  1619. if (level == LOGLEVEL_SCHED) {
  1620. level = LOGLEVEL_DEFAULT;
  1621. in_sched = true;
  1622. }
  1623. boot_delay_msec(level);
  1624. printk_delay();
  1625. /* This stops the holder of console_sem just where we want him */
  1626. logbuf_lock_irqsave(flags);
  1627. printed_len = vprintk_store(facility, level, dict, dictlen, fmt, args);
  1628. logbuf_unlock_irqrestore(flags);
  1629. /* If called from the scheduler, we can not call up(). */
  1630. if (!in_sched) {
  1631. /*
  1632. * Disable preemption to avoid being preempted while holding
  1633. * console_sem which would prevent anyone from printing to
  1634. * console
  1635. */
  1636. preempt_disable();
  1637. /*
  1638. * Try to acquire and then immediately release the console
  1639. * semaphore. The release will print out buffers and wake up
  1640. * /dev/kmsg and syslog() users.
  1641. */
  1642. if (console_trylock_spinning())
  1643. console_unlock();
  1644. preempt_enable();
  1645. }
  1646. wake_up_klogd();
  1647. return printed_len;
  1648. }
  1649. EXPORT_SYMBOL(vprintk_emit);
  1650. asmlinkage int vprintk(const char *fmt, va_list args)
  1651. {
  1652. return vprintk_func(fmt, args);
  1653. }
  1654. EXPORT_SYMBOL(vprintk);
  1655. asmlinkage int printk_emit(int facility, int level,
  1656. const char *dict, size_t dictlen,
  1657. const char *fmt, ...)
  1658. {
  1659. va_list args;
  1660. int r;
  1661. va_start(args, fmt);
  1662. r = vprintk_emit(facility, level, dict, dictlen, fmt, args);
  1663. va_end(args);
  1664. return r;
  1665. }
  1666. EXPORT_SYMBOL(printk_emit);
  1667. int vprintk_default(const char *fmt, va_list args)
  1668. {
  1669. int r;
  1670. #ifdef CONFIG_KGDB_KDB
  1671. /* Allow to pass printk() to kdb but avoid a recursion. */
  1672. if (unlikely(kdb_trap_printk && kdb_printf_cpu < 0)) {
  1673. r = vkdb_printf(KDB_MSGSRC_PRINTK, fmt, args);
  1674. return r;
  1675. }
  1676. #endif
  1677. r = vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, 0, fmt, args);
  1678. return r;
  1679. }
  1680. EXPORT_SYMBOL_GPL(vprintk_default);
  1681. /**
  1682. * printk - print a kernel message
  1683. * @fmt: format string
  1684. *
  1685. * This is printk(). It can be called from any context. We want it to work.
  1686. *
  1687. * We try to grab the console_lock. If we succeed, it's easy - we log the
  1688. * output and call the console drivers. If we fail to get the semaphore, we
  1689. * place the output into the log buffer and return. The current holder of
  1690. * the console_sem will notice the new output in console_unlock(); and will
  1691. * send it to the consoles before releasing the lock.
  1692. *
  1693. * One effect of this deferred printing is that code which calls printk() and
  1694. * then changes console_loglevel may break. This is because console_loglevel
  1695. * is inspected when the actual printing occurs.
  1696. *
  1697. * See also:
  1698. * printf(3)
  1699. *
  1700. * See the vsnprintf() documentation for format string extensions over C99.
  1701. */
  1702. asmlinkage __visible int printk(const char *fmt, ...)
  1703. {
  1704. va_list args;
  1705. int r;
  1706. va_start(args, fmt);
  1707. r = vprintk_func(fmt, args);
  1708. va_end(args);
  1709. return r;
  1710. }
  1711. EXPORT_SYMBOL(printk);
  1712. #else /* CONFIG_PRINTK */
  1713. #define LOG_LINE_MAX 0
  1714. #define PREFIX_MAX 0
  1715. static u64 syslog_seq;
  1716. static u32 syslog_idx;
  1717. static u64 console_seq;
  1718. static u32 console_idx;
  1719. static u64 log_first_seq;
  1720. static u32 log_first_idx;
  1721. static u64 log_next_seq;
  1722. static char *log_text(const struct printk_log *msg) { return NULL; }
  1723. static char *log_dict(const struct printk_log *msg) { return NULL; }
  1724. static struct printk_log *log_from_idx(u32 idx) { return NULL; }
  1725. static u32 log_next(u32 idx) { return 0; }
  1726. static ssize_t msg_print_ext_header(char *buf, size_t size,
  1727. struct printk_log *msg,
  1728. u64 seq) { return 0; }
  1729. static ssize_t msg_print_ext_body(char *buf, size_t size,
  1730. char *dict, size_t dict_len,
  1731. char *text, size_t text_len) { return 0; }
  1732. static void console_lock_spinning_enable(void) { }
  1733. static int console_lock_spinning_disable_and_check(void) { return 0; }
  1734. static void call_console_drivers(const char *ext_text, size_t ext_len,
  1735. const char *text, size_t len) {}
  1736. static size_t msg_print_text(const struct printk_log *msg,
  1737. bool syslog, char *buf, size_t size) { return 0; }
  1738. #endif /* CONFIG_PRINTK */
  1739. #ifdef CONFIG_EARLY_PRINTK
  1740. struct console *early_console;
  1741. asmlinkage __visible void early_printk(const char *fmt, ...)
  1742. {
  1743. va_list ap;
  1744. char buf[512];
  1745. int n;
  1746. if (!early_console)
  1747. return;
  1748. va_start(ap, fmt);
  1749. n = vscnprintf(buf, sizeof(buf), fmt, ap);
  1750. va_end(ap);
  1751. early_console->write(early_console, buf, n);
  1752. }
  1753. #endif
  1754. static int __add_preferred_console(char *name, int idx, char *options,
  1755. char *brl_options)
  1756. {
  1757. struct console_cmdline *c;
  1758. int i;
  1759. /*
  1760. * See if this tty is not yet registered, and
  1761. * if we have a slot free.
  1762. */
  1763. for (i = 0, c = console_cmdline;
  1764. i < MAX_CMDLINECONSOLES && c->name[0];
  1765. i++, c++) {
  1766. if (strcmp(c->name, name) == 0 && c->index == idx) {
  1767. if (!brl_options)
  1768. preferred_console = i;
  1769. return 0;
  1770. }
  1771. }
  1772. if (i == MAX_CMDLINECONSOLES)
  1773. return -E2BIG;
  1774. if (!brl_options)
  1775. preferred_console = i;
  1776. strlcpy(c->name, name, sizeof(c->name));
  1777. c->options = options;
  1778. braille_set_options(c, brl_options);
  1779. c->index = idx;
  1780. return 0;
  1781. }
  1782. static int __init console_msg_format_setup(char *str)
  1783. {
  1784. if (!strcmp(str, "syslog"))
  1785. console_msg_format = MSG_FORMAT_SYSLOG;
  1786. if (!strcmp(str, "default"))
  1787. console_msg_format = MSG_FORMAT_DEFAULT;
  1788. return 1;
  1789. }
  1790. __setup("console_msg_format=", console_msg_format_setup);
  1791. /*
  1792. * Set up a console. Called via do_early_param() in init/main.c
  1793. * for each "console=" parameter in the boot command line.
  1794. */
  1795. static int __init console_setup(char *str)
  1796. {
  1797. char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
  1798. char *s, *options, *brl_options = NULL;
  1799. int idx;
  1800. if (_braille_console_setup(&str, &brl_options))
  1801. return 1;
  1802. /*
  1803. * Decode str into name, index, options.
  1804. */
  1805. if (str[0] >= '0' && str[0] <= '9') {
  1806. strcpy(buf, "ttyS");
  1807. strncpy(buf + 4, str, sizeof(buf) - 5);
  1808. } else {
  1809. strncpy(buf, str, sizeof(buf) - 1);
  1810. }
  1811. buf[sizeof(buf) - 1] = 0;
  1812. options = strchr(str, ',');
  1813. if (options)
  1814. *(options++) = 0;
  1815. #ifdef __sparc__
  1816. if (!strcmp(str, "ttya"))
  1817. strcpy(buf, "ttyS0");
  1818. if (!strcmp(str, "ttyb"))
  1819. strcpy(buf, "ttyS1");
  1820. #endif
  1821. for (s = buf; *s; s++)
  1822. if (isdigit(*s) || *s == ',')
  1823. break;
  1824. idx = simple_strtoul(s, NULL, 10);
  1825. *s = 0;
  1826. __add_preferred_console(buf, idx, options, brl_options);
  1827. console_set_on_cmdline = 1;
  1828. return 1;
  1829. }
  1830. __setup("console=", console_setup);
  1831. /**
  1832. * add_preferred_console - add a device to the list of preferred consoles.
  1833. * @name: device name
  1834. * @idx: device index
  1835. * @options: options for this console
  1836. *
  1837. * The last preferred console added will be used for kernel messages
  1838. * and stdin/out/err for init. Normally this is used by console_setup
  1839. * above to handle user-supplied console arguments; however it can also
  1840. * be used by arch-specific code either to override the user or more
  1841. * commonly to provide a default console (ie from PROM variables) when
  1842. * the user has not supplied one.
  1843. */
  1844. int add_preferred_console(char *name, int idx, char *options)
  1845. {
  1846. return __add_preferred_console(name, idx, options, NULL);
  1847. }
  1848. bool console_suspend_enabled = true;
  1849. EXPORT_SYMBOL(console_suspend_enabled);
  1850. static int __init console_suspend_disable(char *str)
  1851. {
  1852. console_suspend_enabled = false;
  1853. return 1;
  1854. }
  1855. __setup("no_console_suspend", console_suspend_disable);
  1856. module_param_named(console_suspend, console_suspend_enabled,
  1857. bool, S_IRUGO | S_IWUSR);
  1858. MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
  1859. " and hibernate operations");
  1860. /**
  1861. * suspend_console - suspend the console subsystem
  1862. *
  1863. * This disables printk() while we go into suspend states
  1864. */
  1865. void suspend_console(void)
  1866. {
  1867. if (!console_suspend_enabled)
  1868. return;
  1869. pr_info("Suspending console(s) (use no_console_suspend to debug)\n");
  1870. console_lock();
  1871. console_suspended = 1;
  1872. up_console_sem();
  1873. }
  1874. void resume_console(void)
  1875. {
  1876. if (!console_suspend_enabled)
  1877. return;
  1878. down_console_sem();
  1879. console_suspended = 0;
  1880. console_unlock();
  1881. }
  1882. /**
  1883. * console_cpu_notify - print deferred console messages after CPU hotplug
  1884. * @cpu: unused
  1885. *
  1886. * If printk() is called from a CPU that is not online yet, the messages
  1887. * will be printed on the console only if there are CON_ANYTIME consoles.
  1888. * This function is called when a new CPU comes online (or fails to come
  1889. * up) or goes offline.
  1890. */
  1891. static int console_cpu_notify(unsigned int cpu)
  1892. {
  1893. if (!cpuhp_tasks_frozen) {
  1894. /* If trylock fails, someone else is doing the printing */
  1895. if (console_trylock())
  1896. console_unlock();
  1897. }
  1898. return 0;
  1899. }
  1900. /**
  1901. * console_lock - lock the console system for exclusive use.
  1902. *
  1903. * Acquires a lock which guarantees that the caller has
  1904. * exclusive access to the console system and the console_drivers list.
  1905. *
  1906. * Can sleep, returns nothing.
  1907. */
  1908. void console_lock(void)
  1909. {
  1910. might_sleep();
  1911. down_console_sem();
  1912. if (console_suspended)
  1913. return;
  1914. console_locked = 1;
  1915. console_may_schedule = 1;
  1916. }
  1917. EXPORT_SYMBOL(console_lock);
  1918. /**
  1919. * console_trylock - try to lock the console system for exclusive use.
  1920. *
  1921. * Try to acquire a lock which guarantees that the caller has exclusive
  1922. * access to the console system and the console_drivers list.
  1923. *
  1924. * returns 1 on success, and 0 on failure to acquire the lock.
  1925. */
  1926. int console_trylock(void)
  1927. {
  1928. if (down_trylock_console_sem())
  1929. return 0;
  1930. if (console_suspended) {
  1931. up_console_sem();
  1932. return 0;
  1933. }
  1934. console_locked = 1;
  1935. console_may_schedule = 0;
  1936. return 1;
  1937. }
  1938. EXPORT_SYMBOL(console_trylock);
  1939. int is_console_locked(void)
  1940. {
  1941. return console_locked;
  1942. }
  1943. EXPORT_SYMBOL(is_console_locked);
  1944. /*
  1945. * Check if we have any console that is capable of printing while cpu is
  1946. * booting or shutting down. Requires console_sem.
  1947. */
  1948. static int have_callable_console(void)
  1949. {
  1950. struct console *con;
  1951. for_each_console(con)
  1952. if ((con->flags & CON_ENABLED) &&
  1953. (con->flags & CON_ANYTIME))
  1954. return 1;
  1955. return 0;
  1956. }
  1957. /*
  1958. * Can we actually use the console at this time on this cpu?
  1959. *
  1960. * Console drivers may assume that per-cpu resources have been allocated. So
  1961. * unless they're explicitly marked as being able to cope (CON_ANYTIME) don't
  1962. * call them until this CPU is officially up.
  1963. */
  1964. static inline int can_use_console(void)
  1965. {
  1966. return cpu_online(raw_smp_processor_id()) || have_callable_console();
  1967. }
  1968. /**
  1969. * console_unlock - unlock the console system
  1970. *
  1971. * Releases the console_lock which the caller holds on the console system
  1972. * and the console driver list.
  1973. *
  1974. * While the console_lock was held, console output may have been buffered
  1975. * by printk(). If this is the case, console_unlock(); emits
  1976. * the output prior to releasing the lock.
  1977. *
  1978. * If there is output waiting, we wake /dev/kmsg and syslog() users.
  1979. *
  1980. * console_unlock(); may be called from any context.
  1981. */
  1982. void console_unlock(void)
  1983. {
  1984. static char ext_text[CONSOLE_EXT_LOG_MAX];
  1985. static char text[LOG_LINE_MAX + PREFIX_MAX];
  1986. unsigned long flags;
  1987. bool do_cond_resched, retry;
  1988. if (console_suspended) {
  1989. up_console_sem();
  1990. return;
  1991. }
  1992. /*
  1993. * Console drivers are called with interrupts disabled, so
  1994. * @console_may_schedule should be cleared before; however, we may
  1995. * end up dumping a lot of lines, for example, if called from
  1996. * console registration path, and should invoke cond_resched()
  1997. * between lines if allowable. Not doing so can cause a very long
  1998. * scheduling stall on a slow console leading to RCU stall and
  1999. * softlockup warnings which exacerbate the issue with more
  2000. * messages practically incapacitating the system.
  2001. *
  2002. * console_trylock() is not able to detect the preemptive
  2003. * context reliably. Therefore the value must be stored before
  2004. * and cleared after the the "again" goto label.
  2005. */
  2006. do_cond_resched = console_may_schedule;
  2007. again:
  2008. console_may_schedule = 0;
  2009. /*
  2010. * We released the console_sem lock, so we need to recheck if
  2011. * cpu is online and (if not) is there at least one CON_ANYTIME
  2012. * console.
  2013. */
  2014. if (!can_use_console()) {
  2015. console_locked = 0;
  2016. up_console_sem();
  2017. return;
  2018. }
  2019. for (;;) {
  2020. struct printk_log *msg;
  2021. size_t ext_len = 0;
  2022. size_t len;
  2023. printk_safe_enter_irqsave(flags);
  2024. raw_spin_lock(&logbuf_lock);
  2025. if (console_seq < log_first_seq) {
  2026. len = sprintf(text, "** %u printk messages dropped **\n",
  2027. (unsigned)(log_first_seq - console_seq));
  2028. /* messages are gone, move to first one */
  2029. console_seq = log_first_seq;
  2030. console_idx = log_first_idx;
  2031. } else {
  2032. len = 0;
  2033. }
  2034. skip:
  2035. if (console_seq == log_next_seq)
  2036. break;
  2037. msg = log_from_idx(console_idx);
  2038. if (msg->flags & LOG_NOCONS) {
  2039. /*
  2040. * Skip record if !ignore_loglevel, and
  2041. * record has level above the console loglevel.
  2042. */
  2043. console_idx = log_next(console_idx);
  2044. console_seq++;
  2045. goto skip;
  2046. }
  2047. len += msg_print_text(msg,
  2048. console_msg_format & MSG_FORMAT_SYSLOG,
  2049. text + len,
  2050. sizeof(text) - len);
  2051. if (nr_ext_console_drivers) {
  2052. ext_len = msg_print_ext_header(ext_text,
  2053. sizeof(ext_text),
  2054. msg, console_seq);
  2055. ext_len += msg_print_ext_body(ext_text + ext_len,
  2056. sizeof(ext_text) - ext_len,
  2057. log_dict(msg), msg->dict_len,
  2058. log_text(msg), msg->text_len);
  2059. }
  2060. console_idx = log_next(console_idx);
  2061. console_seq++;
  2062. raw_spin_unlock(&logbuf_lock);
  2063. /*
  2064. * While actively printing out messages, if another printk()
  2065. * were to occur on another CPU, it may wait for this one to
  2066. * finish. This task can not be preempted if there is a
  2067. * waiter waiting to take over.
  2068. */
  2069. console_lock_spinning_enable();
  2070. stop_critical_timings(); /* don't trace print latency */
  2071. call_console_drivers(ext_text, ext_len, text, len);
  2072. start_critical_timings();
  2073. if (console_lock_spinning_disable_and_check()) {
  2074. printk_safe_exit_irqrestore(flags);
  2075. return;
  2076. }
  2077. printk_safe_exit_irqrestore(flags);
  2078. if (do_cond_resched)
  2079. cond_resched();
  2080. }
  2081. console_locked = 0;
  2082. /* Release the exclusive_console once it is used */
  2083. if (unlikely(exclusive_console))
  2084. exclusive_console = NULL;
  2085. raw_spin_unlock(&logbuf_lock);
  2086. up_console_sem();
  2087. /*
  2088. * Someone could have filled up the buffer again, so re-check if there's
  2089. * something to flush. In case we cannot trylock the console_sem again,
  2090. * there's a new owner and the console_unlock() from them will do the
  2091. * flush, no worries.
  2092. */
  2093. raw_spin_lock(&logbuf_lock);
  2094. retry = console_seq != log_next_seq;
  2095. raw_spin_unlock(&logbuf_lock);
  2096. printk_safe_exit_irqrestore(flags);
  2097. if (retry && console_trylock())
  2098. goto again;
  2099. }
  2100. EXPORT_SYMBOL(console_unlock);
  2101. /**
  2102. * console_conditional_schedule - yield the CPU if required
  2103. *
  2104. * If the console code is currently allowed to sleep, and
  2105. * if this CPU should yield the CPU to another task, do
  2106. * so here.
  2107. *
  2108. * Must be called within console_lock();.
  2109. */
  2110. void __sched console_conditional_schedule(void)
  2111. {
  2112. if (console_may_schedule)
  2113. cond_resched();
  2114. }
  2115. EXPORT_SYMBOL(console_conditional_schedule);
  2116. void console_unblank(void)
  2117. {
  2118. struct console *c;
  2119. /*
  2120. * console_unblank can no longer be called in interrupt context unless
  2121. * oops_in_progress is set to 1..
  2122. */
  2123. if (oops_in_progress) {
  2124. if (down_trylock_console_sem() != 0)
  2125. return;
  2126. } else
  2127. console_lock();
  2128. console_locked = 1;
  2129. console_may_schedule = 0;
  2130. for_each_console(c)
  2131. if ((c->flags & CON_ENABLED) && c->unblank)
  2132. c->unblank();
  2133. console_unlock();
  2134. }
  2135. /**
  2136. * console_flush_on_panic - flush console content on panic
  2137. *
  2138. * Immediately output all pending messages no matter what.
  2139. */
  2140. void console_flush_on_panic(void)
  2141. {
  2142. /*
  2143. * If someone else is holding the console lock, trylock will fail
  2144. * and may_schedule may be set. Ignore and proceed to unlock so
  2145. * that messages are flushed out. As this can be called from any
  2146. * context and we don't want to get preempted while flushing,
  2147. * ensure may_schedule is cleared.
  2148. */
  2149. console_trylock();
  2150. console_may_schedule = 0;
  2151. console_unlock();
  2152. }
  2153. /*
  2154. * Return the console tty driver structure and its associated index
  2155. */
  2156. struct tty_driver *console_device(int *index)
  2157. {
  2158. struct console *c;
  2159. struct tty_driver *driver = NULL;
  2160. console_lock();
  2161. for_each_console(c) {
  2162. if (!c->device)
  2163. continue;
  2164. driver = c->device(c, index);
  2165. if (driver)
  2166. break;
  2167. }
  2168. console_unlock();
  2169. return driver;
  2170. }
  2171. /*
  2172. * Prevent further output on the passed console device so that (for example)
  2173. * serial drivers can disable console output before suspending a port, and can
  2174. * re-enable output afterwards.
  2175. */
  2176. void console_stop(struct console *console)
  2177. {
  2178. console_lock();
  2179. console->flags &= ~CON_ENABLED;
  2180. console_unlock();
  2181. }
  2182. EXPORT_SYMBOL(console_stop);
  2183. void console_start(struct console *console)
  2184. {
  2185. console_lock();
  2186. console->flags |= CON_ENABLED;
  2187. console_unlock();
  2188. }
  2189. EXPORT_SYMBOL(console_start);
  2190. static int __read_mostly keep_bootcon;
  2191. static int __init keep_bootcon_setup(char *str)
  2192. {
  2193. keep_bootcon = 1;
  2194. pr_info("debug: skip boot console de-registration.\n");
  2195. return 0;
  2196. }
  2197. early_param("keep_bootcon", keep_bootcon_setup);
  2198. /*
  2199. * The console driver calls this routine during kernel initialization
  2200. * to register the console printing procedure with printk() and to
  2201. * print any messages that were printed by the kernel before the
  2202. * console driver was initialized.
  2203. *
  2204. * This can happen pretty early during the boot process (because of
  2205. * early_printk) - sometimes before setup_arch() completes - be careful
  2206. * of what kernel features are used - they may not be initialised yet.
  2207. *
  2208. * There are two types of consoles - bootconsoles (early_printk) and
  2209. * "real" consoles (everything which is not a bootconsole) which are
  2210. * handled differently.
  2211. * - Any number of bootconsoles can be registered at any time.
  2212. * - As soon as a "real" console is registered, all bootconsoles
  2213. * will be unregistered automatically.
  2214. * - Once a "real" console is registered, any attempt to register a
  2215. * bootconsoles will be rejected
  2216. */
  2217. void register_console(struct console *newcon)
  2218. {
  2219. int i;
  2220. unsigned long flags;
  2221. struct console *bcon = NULL;
  2222. struct console_cmdline *c;
  2223. static bool has_preferred;
  2224. if (console_drivers)
  2225. for_each_console(bcon)
  2226. if (WARN(bcon == newcon,
  2227. "console '%s%d' already registered\n",
  2228. bcon->name, bcon->index))
  2229. return;
  2230. /*
  2231. * before we register a new CON_BOOT console, make sure we don't
  2232. * already have a valid console
  2233. */
  2234. if (console_drivers && newcon->flags & CON_BOOT) {
  2235. /* find the last or real console */
  2236. for_each_console(bcon) {
  2237. if (!(bcon->flags & CON_BOOT)) {
  2238. pr_info("Too late to register bootconsole %s%d\n",
  2239. newcon->name, newcon->index);
  2240. return;
  2241. }
  2242. }
  2243. }
  2244. if (console_drivers && console_drivers->flags & CON_BOOT)
  2245. bcon = console_drivers;
  2246. if (!has_preferred || bcon || !console_drivers)
  2247. has_preferred = preferred_console >= 0;
  2248. /*
  2249. * See if we want to use this console driver. If we
  2250. * didn't select a console we take the first one
  2251. * that registers here.
  2252. */
  2253. if (!has_preferred) {
  2254. if (newcon->index < 0)
  2255. newcon->index = 0;
  2256. if (newcon->setup == NULL ||
  2257. newcon->setup(newcon, NULL) == 0) {
  2258. newcon->flags |= CON_ENABLED;
  2259. if (newcon->device) {
  2260. newcon->flags |= CON_CONSDEV;
  2261. has_preferred = true;
  2262. }
  2263. }
  2264. }
  2265. /*
  2266. * See if this console matches one we selected on
  2267. * the command line.
  2268. */
  2269. for (i = 0, c = console_cmdline;
  2270. i < MAX_CMDLINECONSOLES && c->name[0];
  2271. i++, c++) {
  2272. if (!newcon->match ||
  2273. newcon->match(newcon, c->name, c->index, c->options) != 0) {
  2274. /* default matching */
  2275. BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
  2276. if (strcmp(c->name, newcon->name) != 0)
  2277. continue;
  2278. if (newcon->index >= 0 &&
  2279. newcon->index != c->index)
  2280. continue;
  2281. if (newcon->index < 0)
  2282. newcon->index = c->index;
  2283. if (_braille_register_console(newcon, c))
  2284. return;
  2285. if (newcon->setup &&
  2286. newcon->setup(newcon, c->options) != 0)
  2287. break;
  2288. }
  2289. newcon->flags |= CON_ENABLED;
  2290. if (i == preferred_console) {
  2291. newcon->flags |= CON_CONSDEV;
  2292. has_preferred = true;
  2293. }
  2294. break;
  2295. }
  2296. if (!(newcon->flags & CON_ENABLED))
  2297. return;
  2298. /*
  2299. * If we have a bootconsole, and are switching to a real console,
  2300. * don't print everything out again, since when the boot console, and
  2301. * the real console are the same physical device, it's annoying to
  2302. * see the beginning boot messages twice
  2303. */
  2304. if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
  2305. newcon->flags &= ~CON_PRINTBUFFER;
  2306. /*
  2307. * Put this console in the list - keep the
  2308. * preferred driver at the head of the list.
  2309. */
  2310. console_lock();
  2311. if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
  2312. newcon->next = console_drivers;
  2313. console_drivers = newcon;
  2314. if (newcon->next)
  2315. newcon->next->flags &= ~CON_CONSDEV;
  2316. } else {
  2317. newcon->next = console_drivers->next;
  2318. console_drivers->next = newcon;
  2319. }
  2320. if (newcon->flags & CON_EXTENDED)
  2321. if (!nr_ext_console_drivers++)
  2322. pr_info("printk: continuation disabled due to ext consoles, expect more fragments in /dev/kmsg\n");
  2323. if (newcon->flags & CON_PRINTBUFFER) {
  2324. /*
  2325. * console_unlock(); will print out the buffered messages
  2326. * for us.
  2327. */
  2328. logbuf_lock_irqsave(flags);
  2329. console_seq = syslog_seq;
  2330. console_idx = syslog_idx;
  2331. logbuf_unlock_irqrestore(flags);
  2332. /*
  2333. * We're about to replay the log buffer. Only do this to the
  2334. * just-registered console to avoid excessive message spam to
  2335. * the already-registered consoles.
  2336. */
  2337. exclusive_console = newcon;
  2338. }
  2339. console_unlock();
  2340. console_sysfs_notify();
  2341. /*
  2342. * By unregistering the bootconsoles after we enable the real console
  2343. * we get the "console xxx enabled" message on all the consoles -
  2344. * boot consoles, real consoles, etc - this is to ensure that end
  2345. * users know there might be something in the kernel's log buffer that
  2346. * went to the bootconsole (that they do not see on the real console)
  2347. */
  2348. pr_info("%sconsole [%s%d] enabled\n",
  2349. (newcon->flags & CON_BOOT) ? "boot" : "" ,
  2350. newcon->name, newcon->index);
  2351. if (bcon &&
  2352. ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
  2353. !keep_bootcon) {
  2354. /* We need to iterate through all boot consoles, to make
  2355. * sure we print everything out, before we unregister them.
  2356. */
  2357. for_each_console(bcon)
  2358. if (bcon->flags & CON_BOOT)
  2359. unregister_console(bcon);
  2360. }
  2361. }
  2362. EXPORT_SYMBOL(register_console);
  2363. int unregister_console(struct console *console)
  2364. {
  2365. struct console *a, *b;
  2366. int res;
  2367. pr_info("%sconsole [%s%d] disabled\n",
  2368. (console->flags & CON_BOOT) ? "boot" : "" ,
  2369. console->name, console->index);
  2370. res = _braille_unregister_console(console);
  2371. if (res)
  2372. return res;
  2373. res = 1;
  2374. console_lock();
  2375. if (console_drivers == console) {
  2376. console_drivers=console->next;
  2377. res = 0;
  2378. } else if (console_drivers) {
  2379. for (a=console_drivers->next, b=console_drivers ;
  2380. a; b=a, a=b->next) {
  2381. if (a == console) {
  2382. b->next = a->next;
  2383. res = 0;
  2384. break;
  2385. }
  2386. }
  2387. }
  2388. if (!res && (console->flags & CON_EXTENDED))
  2389. nr_ext_console_drivers--;
  2390. /*
  2391. * If this isn't the last console and it has CON_CONSDEV set, we
  2392. * need to set it on the next preferred console.
  2393. */
  2394. if (console_drivers != NULL && console->flags & CON_CONSDEV)
  2395. console_drivers->flags |= CON_CONSDEV;
  2396. console->flags &= ~CON_ENABLED;
  2397. console_unlock();
  2398. console_sysfs_notify();
  2399. return res;
  2400. }
  2401. EXPORT_SYMBOL(unregister_console);
  2402. /*
  2403. * Initialize the console device. This is called *early*, so
  2404. * we can't necessarily depend on lots of kernel help here.
  2405. * Just do some early initializations, and do the complex setup
  2406. * later.
  2407. */
  2408. void __init console_init(void)
  2409. {
  2410. int ret;
  2411. initcall_t call;
  2412. initcall_entry_t *ce;
  2413. /* Setup the default TTY line discipline. */
  2414. n_tty_init();
  2415. /*
  2416. * set up the console device so that later boot sequences can
  2417. * inform about problems etc..
  2418. */
  2419. ce = __con_initcall_start;
  2420. trace_initcall_level("console");
  2421. while (ce < __con_initcall_end) {
  2422. call = initcall_from_entry(ce);
  2423. trace_initcall_start(call);
  2424. ret = call();
  2425. trace_initcall_finish(call, ret);
  2426. ce++;
  2427. }
  2428. }
  2429. /*
  2430. * Some boot consoles access data that is in the init section and which will
  2431. * be discarded after the initcalls have been run. To make sure that no code
  2432. * will access this data, unregister the boot consoles in a late initcall.
  2433. *
  2434. * If for some reason, such as deferred probe or the driver being a loadable
  2435. * module, the real console hasn't registered yet at this point, there will
  2436. * be a brief interval in which no messages are logged to the console, which
  2437. * makes it difficult to diagnose problems that occur during this time.
  2438. *
  2439. * To mitigate this problem somewhat, only unregister consoles whose memory
  2440. * intersects with the init section. Note that all other boot consoles will
  2441. * get unregistred when the real preferred console is registered.
  2442. */
  2443. static int __init printk_late_init(void)
  2444. {
  2445. struct console *con;
  2446. int ret;
  2447. for_each_console(con) {
  2448. if (!(con->flags & CON_BOOT))
  2449. continue;
  2450. /* Check addresses that might be used for enabled consoles. */
  2451. if (init_section_intersects(con, sizeof(*con)) ||
  2452. init_section_contains(con->write, 0) ||
  2453. init_section_contains(con->read, 0) ||
  2454. init_section_contains(con->device, 0) ||
  2455. init_section_contains(con->unblank, 0) ||
  2456. init_section_contains(con->data, 0)) {
  2457. /*
  2458. * Please, consider moving the reported consoles out
  2459. * of the init section.
  2460. */
  2461. pr_warn("bootconsole [%s%d] uses init memory and must be disabled even before the real one is ready\n",
  2462. con->name, con->index);
  2463. unregister_console(con);
  2464. }
  2465. }
  2466. ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
  2467. console_cpu_notify);
  2468. WARN_ON(ret < 0);
  2469. ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "printk:online",
  2470. console_cpu_notify, NULL);
  2471. WARN_ON(ret < 0);
  2472. return 0;
  2473. }
  2474. late_initcall(printk_late_init);
  2475. #if defined CONFIG_PRINTK
  2476. /*
  2477. * Delayed printk version, for scheduler-internal messages:
  2478. */
  2479. #define PRINTK_PENDING_WAKEUP 0x01
  2480. #define PRINTK_PENDING_OUTPUT 0x02
  2481. static DEFINE_PER_CPU(int, printk_pending);
  2482. static void wake_up_klogd_work_func(struct irq_work *irq_work)
  2483. {
  2484. int pending = __this_cpu_xchg(printk_pending, 0);
  2485. if (pending & PRINTK_PENDING_OUTPUT) {
  2486. /* If trylock fails, someone else is doing the printing */
  2487. if (console_trylock())
  2488. console_unlock();
  2489. }
  2490. if (pending & PRINTK_PENDING_WAKEUP)
  2491. wake_up_interruptible(&log_wait);
  2492. }
  2493. static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
  2494. .func = wake_up_klogd_work_func,
  2495. .flags = IRQ_WORK_LAZY,
  2496. };
  2497. void wake_up_klogd(void)
  2498. {
  2499. preempt_disable();
  2500. if (waitqueue_active(&log_wait)) {
  2501. this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
  2502. irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
  2503. }
  2504. preempt_enable();
  2505. }
  2506. void defer_console_output(void)
  2507. {
  2508. preempt_disable();
  2509. __this_cpu_or(printk_pending, PRINTK_PENDING_OUTPUT);
  2510. irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
  2511. preempt_enable();
  2512. }
  2513. int vprintk_deferred(const char *fmt, va_list args)
  2514. {
  2515. int r;
  2516. r = vprintk_emit(0, LOGLEVEL_SCHED, NULL, 0, fmt, args);
  2517. defer_console_output();
  2518. return r;
  2519. }
  2520. int printk_deferred(const char *fmt, ...)
  2521. {
  2522. va_list args;
  2523. int r;
  2524. va_start(args, fmt);
  2525. r = vprintk_deferred(fmt, args);
  2526. va_end(args);
  2527. return r;
  2528. }
  2529. /*
  2530. * printk rate limiting, lifted from the networking subsystem.
  2531. *
  2532. * This enforces a rate limit: not more than 10 kernel messages
  2533. * every 5s to make a denial-of-service attack impossible.
  2534. */
  2535. DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
  2536. int __printk_ratelimit(const char *func)
  2537. {
  2538. return ___ratelimit(&printk_ratelimit_state, func);
  2539. }
  2540. EXPORT_SYMBOL(__printk_ratelimit);
  2541. /**
  2542. * printk_timed_ratelimit - caller-controlled printk ratelimiting
  2543. * @caller_jiffies: pointer to caller's state
  2544. * @interval_msecs: minimum interval between prints
  2545. *
  2546. * printk_timed_ratelimit() returns true if more than @interval_msecs
  2547. * milliseconds have elapsed since the last time printk_timed_ratelimit()
  2548. * returned true.
  2549. */
  2550. bool printk_timed_ratelimit(unsigned long *caller_jiffies,
  2551. unsigned int interval_msecs)
  2552. {
  2553. unsigned long elapsed = jiffies - *caller_jiffies;
  2554. if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
  2555. return false;
  2556. *caller_jiffies = jiffies;
  2557. return true;
  2558. }
  2559. EXPORT_SYMBOL(printk_timed_ratelimit);
  2560. static DEFINE_SPINLOCK(dump_list_lock);
  2561. static LIST_HEAD(dump_list);
  2562. /**
  2563. * kmsg_dump_register - register a kernel log dumper.
  2564. * @dumper: pointer to the kmsg_dumper structure
  2565. *
  2566. * Adds a kernel log dumper to the system. The dump callback in the
  2567. * structure will be called when the kernel oopses or panics and must be
  2568. * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
  2569. */
  2570. int kmsg_dump_register(struct kmsg_dumper *dumper)
  2571. {
  2572. unsigned long flags;
  2573. int err = -EBUSY;
  2574. /* The dump callback needs to be set */
  2575. if (!dumper->dump)
  2576. return -EINVAL;
  2577. spin_lock_irqsave(&dump_list_lock, flags);
  2578. /* Don't allow registering multiple times */
  2579. if (!dumper->registered) {
  2580. dumper->registered = 1;
  2581. list_add_tail_rcu(&dumper->list, &dump_list);
  2582. err = 0;
  2583. }
  2584. spin_unlock_irqrestore(&dump_list_lock, flags);
  2585. return err;
  2586. }
  2587. EXPORT_SYMBOL_GPL(kmsg_dump_register);
  2588. /**
  2589. * kmsg_dump_unregister - unregister a kmsg dumper.
  2590. * @dumper: pointer to the kmsg_dumper structure
  2591. *
  2592. * Removes a dump device from the system. Returns zero on success and
  2593. * %-EINVAL otherwise.
  2594. */
  2595. int kmsg_dump_unregister(struct kmsg_dumper *dumper)
  2596. {
  2597. unsigned long flags;
  2598. int err = -EINVAL;
  2599. spin_lock_irqsave(&dump_list_lock, flags);
  2600. if (dumper->registered) {
  2601. dumper->registered = 0;
  2602. list_del_rcu(&dumper->list);
  2603. err = 0;
  2604. }
  2605. spin_unlock_irqrestore(&dump_list_lock, flags);
  2606. synchronize_rcu();
  2607. return err;
  2608. }
  2609. EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
  2610. static bool always_kmsg_dump;
  2611. module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
  2612. /**
  2613. * kmsg_dump - dump kernel log to kernel message dumpers.
  2614. * @reason: the reason (oops, panic etc) for dumping
  2615. *
  2616. * Call each of the registered dumper's dump() callback, which can
  2617. * retrieve the kmsg records with kmsg_dump_get_line() or
  2618. * kmsg_dump_get_buffer().
  2619. */
  2620. void kmsg_dump(enum kmsg_dump_reason reason)
  2621. {
  2622. struct kmsg_dumper *dumper;
  2623. unsigned long flags;
  2624. if ((reason > KMSG_DUMP_OOPS) && !always_kmsg_dump)
  2625. return;
  2626. rcu_read_lock();
  2627. list_for_each_entry_rcu(dumper, &dump_list, list) {
  2628. if (dumper->max_reason && reason > dumper->max_reason)
  2629. continue;
  2630. /* initialize iterator with data about the stored records */
  2631. dumper->active = true;
  2632. logbuf_lock_irqsave(flags);
  2633. dumper->cur_seq = clear_seq;
  2634. dumper->cur_idx = clear_idx;
  2635. dumper->next_seq = log_next_seq;
  2636. dumper->next_idx = log_next_idx;
  2637. logbuf_unlock_irqrestore(flags);
  2638. /* invoke dumper which will iterate over records */
  2639. dumper->dump(dumper, reason);
  2640. /* reset iterator */
  2641. dumper->active = false;
  2642. }
  2643. rcu_read_unlock();
  2644. }
  2645. /**
  2646. * kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
  2647. * @dumper: registered kmsg dumper
  2648. * @syslog: include the "<4>" prefixes
  2649. * @line: buffer to copy the line to
  2650. * @size: maximum size of the buffer
  2651. * @len: length of line placed into buffer
  2652. *
  2653. * Start at the beginning of the kmsg buffer, with the oldest kmsg
  2654. * record, and copy one record into the provided buffer.
  2655. *
  2656. * Consecutive calls will return the next available record moving
  2657. * towards the end of the buffer with the youngest messages.
  2658. *
  2659. * A return value of FALSE indicates that there are no more records to
  2660. * read.
  2661. *
  2662. * The function is similar to kmsg_dump_get_line(), but grabs no locks.
  2663. */
  2664. bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
  2665. char *line, size_t size, size_t *len)
  2666. {
  2667. struct printk_log *msg;
  2668. size_t l = 0;
  2669. bool ret = false;
  2670. if (!dumper->active)
  2671. goto out;
  2672. if (dumper->cur_seq < log_first_seq) {
  2673. /* messages are gone, move to first available one */
  2674. dumper->cur_seq = log_first_seq;
  2675. dumper->cur_idx = log_first_idx;
  2676. }
  2677. /* last entry */
  2678. if (dumper->cur_seq >= log_next_seq)
  2679. goto out;
  2680. msg = log_from_idx(dumper->cur_idx);
  2681. l = msg_print_text(msg, syslog, line, size);
  2682. dumper->cur_idx = log_next(dumper->cur_idx);
  2683. dumper->cur_seq++;
  2684. ret = true;
  2685. out:
  2686. if (len)
  2687. *len = l;
  2688. return ret;
  2689. }
  2690. /**
  2691. * kmsg_dump_get_line - retrieve one kmsg log line
  2692. * @dumper: registered kmsg dumper
  2693. * @syslog: include the "<4>" prefixes
  2694. * @line: buffer to copy the line to
  2695. * @size: maximum size of the buffer
  2696. * @len: length of line placed into buffer
  2697. *
  2698. * Start at the beginning of the kmsg buffer, with the oldest kmsg
  2699. * record, and copy one record into the provided buffer.
  2700. *
  2701. * Consecutive calls will return the next available record moving
  2702. * towards the end of the buffer with the youngest messages.
  2703. *
  2704. * A return value of FALSE indicates that there are no more records to
  2705. * read.
  2706. */
  2707. bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
  2708. char *line, size_t size, size_t *len)
  2709. {
  2710. unsigned long flags;
  2711. bool ret;
  2712. logbuf_lock_irqsave(flags);
  2713. ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
  2714. logbuf_unlock_irqrestore(flags);
  2715. return ret;
  2716. }
  2717. EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
  2718. /**
  2719. * kmsg_dump_get_buffer - copy kmsg log lines
  2720. * @dumper: registered kmsg dumper
  2721. * @syslog: include the "<4>" prefixes
  2722. * @buf: buffer to copy the line to
  2723. * @size: maximum size of the buffer
  2724. * @len: length of line placed into buffer
  2725. *
  2726. * Start at the end of the kmsg buffer and fill the provided buffer
  2727. * with as many of the the *youngest* kmsg records that fit into it.
  2728. * If the buffer is large enough, all available kmsg records will be
  2729. * copied with a single call.
  2730. *
  2731. * Consecutive calls will fill the buffer with the next block of
  2732. * available older records, not including the earlier retrieved ones.
  2733. *
  2734. * A return value of FALSE indicates that there are no more records to
  2735. * read.
  2736. */
  2737. bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
  2738. char *buf, size_t size, size_t *len)
  2739. {
  2740. unsigned long flags;
  2741. u64 seq;
  2742. u32 idx;
  2743. u64 next_seq;
  2744. u32 next_idx;
  2745. size_t l = 0;
  2746. bool ret = false;
  2747. if (!dumper->active)
  2748. goto out;
  2749. logbuf_lock_irqsave(flags);
  2750. if (dumper->cur_seq < log_first_seq) {
  2751. /* messages are gone, move to first available one */
  2752. dumper->cur_seq = log_first_seq;
  2753. dumper->cur_idx = log_first_idx;
  2754. }
  2755. /* last entry */
  2756. if (dumper->cur_seq >= dumper->next_seq) {
  2757. logbuf_unlock_irqrestore(flags);
  2758. goto out;
  2759. }
  2760. /* calculate length of entire buffer */
  2761. seq = dumper->cur_seq;
  2762. idx = dumper->cur_idx;
  2763. while (seq < dumper->next_seq) {
  2764. struct printk_log *msg = log_from_idx(idx);
  2765. l += msg_print_text(msg, true, NULL, 0);
  2766. idx = log_next(idx);
  2767. seq++;
  2768. }
  2769. /* move first record forward until length fits into the buffer */
  2770. seq = dumper->cur_seq;
  2771. idx = dumper->cur_idx;
  2772. while (l > size && seq < dumper->next_seq) {
  2773. struct printk_log *msg = log_from_idx(idx);
  2774. l -= msg_print_text(msg, true, NULL, 0);
  2775. idx = log_next(idx);
  2776. seq++;
  2777. }
  2778. /* last message in next interation */
  2779. next_seq = seq;
  2780. next_idx = idx;
  2781. l = 0;
  2782. while (seq < dumper->next_seq) {
  2783. struct printk_log *msg = log_from_idx(idx);
  2784. l += msg_print_text(msg, syslog, buf + l, size - l);
  2785. idx = log_next(idx);
  2786. seq++;
  2787. }
  2788. dumper->next_seq = next_seq;
  2789. dumper->next_idx = next_idx;
  2790. ret = true;
  2791. logbuf_unlock_irqrestore(flags);
  2792. out:
  2793. if (len)
  2794. *len = l;
  2795. return ret;
  2796. }
  2797. EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
  2798. /**
  2799. * kmsg_dump_rewind_nolock - reset the interator (unlocked version)
  2800. * @dumper: registered kmsg dumper
  2801. *
  2802. * Reset the dumper's iterator so that kmsg_dump_get_line() and
  2803. * kmsg_dump_get_buffer() can be called again and used multiple
  2804. * times within the same dumper.dump() callback.
  2805. *
  2806. * The function is similar to kmsg_dump_rewind(), but grabs no locks.
  2807. */
  2808. void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
  2809. {
  2810. dumper->cur_seq = clear_seq;
  2811. dumper->cur_idx = clear_idx;
  2812. dumper->next_seq = log_next_seq;
  2813. dumper->next_idx = log_next_idx;
  2814. }
  2815. /**
  2816. * kmsg_dump_rewind - reset the interator
  2817. * @dumper: registered kmsg dumper
  2818. *
  2819. * Reset the dumper's iterator so that kmsg_dump_get_line() and
  2820. * kmsg_dump_get_buffer() can be called again and used multiple
  2821. * times within the same dumper.dump() callback.
  2822. */
  2823. void kmsg_dump_rewind(struct kmsg_dumper *dumper)
  2824. {
  2825. unsigned long flags;
  2826. logbuf_lock_irqsave(flags);
  2827. kmsg_dump_rewind_nolock(dumper);
  2828. logbuf_unlock_irqrestore(flags);
  2829. }
  2830. EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
  2831. #endif