printk.c 80 KB

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