printk.c 79 KB

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