printk.c 82 KB

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