printk.c 76 KB

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