printk.c 81 KB

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