printk.c 76 KB

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