printk.c 79 KB

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