printk.c 80 KB

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