printk.c 77 KB

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