printk.c 81 KB

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