printk.c 79 KB

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