printk.c 75 KB

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