1 // SPDX-License-Identifier: GPL-2.0-only
3 * Persistent Storage - platform driver interface parts.
5 * Copyright (C) 2007-2008 Google, Inc.
6 * Copyright (C) 2010 Intel Corporation <tony.luck@intel.com>
9 #define pr_fmt(fmt) "pstore: " fmt
11 #include <linux/atomic.h>
12 #include <linux/types.h>
13 #include <linux/errno.h>
14 #include <linux/init.h>
15 #include <linux/kmsg_dump.h>
16 #include <linux/console.h>
17 #include <linux/module.h>
18 #include <linux/pstore.h>
19 #if IS_ENABLED(CONFIG_PSTORE_LZO_COMPRESS)
20 #include <linux/lzo.h>
22 #if IS_ENABLED(CONFIG_PSTORE_LZ4_COMPRESS) || IS_ENABLED(CONFIG_PSTORE_LZ4HC_COMPRESS)
23 #include <linux/lz4.h>
25 #if IS_ENABLED(CONFIG_PSTORE_ZSTD_COMPRESS)
26 #include <linux/zstd.h>
28 #include <linux/crypto.h>
29 #include <linux/string.h>
30 #include <linux/timer.h>
31 #include <linux/slab.h>
32 #include <linux/uaccess.h>
33 #include <linux/jiffies.h>
34 #include <linux/workqueue.h>
39 * We defer making "oops" entries appear in pstore - see
40 * whether the system is actually still running well enough
41 * to let someone see the entry
43 static int pstore_update_ms = -1;
44 module_param_named(update_ms, pstore_update_ms, int, 0600);
45 MODULE_PARM_DESC(update_ms, "milliseconds before pstore updates its content "
46 "(default is -1, which means runtime updates are disabled; "
47 "enabling this option may not be safe; it may lead to further "
48 "corruption on Oopses)");
50 /* Names should be in the same order as the enum pstore_type_id */
51 static const char * const pstore_type_names[] = {
63 static int pstore_new_entry;
65 static void pstore_timefunc(struct timer_list *);
66 static DEFINE_TIMER(pstore_timer, pstore_timefunc);
68 static void pstore_dowork(struct work_struct *);
69 static DECLARE_WORK(pstore_work, pstore_dowork);
72 * psinfo_lock protects "psinfo" during calls to
73 * pstore_register(), pstore_unregister(), and
74 * the filesystem mount/unmount routines.
76 static DEFINE_MUTEX(psinfo_lock);
77 struct pstore_info *psinfo;
80 module_param(backend, charp, 0444);
81 MODULE_PARM_DESC(backend, "specific backend to use");
83 static char *compress =
84 #ifdef CONFIG_PSTORE_COMPRESS_DEFAULT
85 CONFIG_PSTORE_COMPRESS_DEFAULT;
89 module_param(compress, charp, 0444);
90 MODULE_PARM_DESC(compress, "compression to use");
92 /* How much of the kernel log to snapshot */
93 unsigned long kmsg_bytes = CONFIG_PSTORE_DEFAULT_KMSG_BYTES;
94 module_param(kmsg_bytes, ulong, 0444);
95 MODULE_PARM_DESC(kmsg_bytes, "amount of kernel log to snapshot (in bytes)");
97 /* Compression parameters */
98 static struct crypto_comp *tfm;
100 struct pstore_zbackend {
101 int (*zbufsize)(size_t size);
105 static char *big_oops_buf;
106 static size_t big_oops_buf_sz;
108 void pstore_set_kmsg_bytes(int bytes)
113 /* Tag each group of saved records with a sequence number */
114 static int oopscount;
116 const char *pstore_type_to_name(enum pstore_type_id type)
118 BUILD_BUG_ON(ARRAY_SIZE(pstore_type_names) != PSTORE_TYPE_MAX);
120 if (WARN_ON_ONCE(type >= PSTORE_TYPE_MAX))
123 return pstore_type_names[type];
125 EXPORT_SYMBOL_GPL(pstore_type_to_name);
127 enum pstore_type_id pstore_name_to_type(const char *name)
131 for (i = 0; i < PSTORE_TYPE_MAX; i++) {
132 if (!strcmp(pstore_type_names[i], name))
136 return PSTORE_TYPE_MAX;
138 EXPORT_SYMBOL_GPL(pstore_name_to_type);
140 static void pstore_timer_kick(void)
142 if (pstore_update_ms < 0)
145 mod_timer(&pstore_timer, jiffies + msecs_to_jiffies(pstore_update_ms));
148 static bool pstore_cannot_block_path(enum kmsg_dump_reason reason)
151 * In case of NMI path, pstore shouldn't be blocked
152 * regardless of reason.
158 /* In panic case, other cpus are stopped by smp_send_stop(). */
159 case KMSG_DUMP_PANIC:
161 * Emergency restart shouldn't be blocked by spinning on
162 * pstore_info::buf_lock.
164 case KMSG_DUMP_EMERG:
171 #if IS_ENABLED(CONFIG_PSTORE_DEFLATE_COMPRESS)
172 static int zbufsize_deflate(size_t size)
177 /* buffer range for efivars */
187 /* buffer range for nvram, erst */
196 return (size * 100) / cmpr;
200 #if IS_ENABLED(CONFIG_PSTORE_LZO_COMPRESS)
201 static int zbufsize_lzo(size_t size)
203 return lzo1x_worst_compress(size);
207 #if IS_ENABLED(CONFIG_PSTORE_LZ4_COMPRESS) || IS_ENABLED(CONFIG_PSTORE_LZ4HC_COMPRESS)
208 static int zbufsize_lz4(size_t size)
210 return LZ4_compressBound(size);
214 #if IS_ENABLED(CONFIG_PSTORE_842_COMPRESS)
215 static int zbufsize_842(size_t size)
221 #if IS_ENABLED(CONFIG_PSTORE_ZSTD_COMPRESS)
222 static int zbufsize_zstd(size_t size)
224 return zstd_compress_bound(size);
228 static const struct pstore_zbackend *zbackend __ro_after_init;
230 static const struct pstore_zbackend zbackends[] = {
231 #if IS_ENABLED(CONFIG_PSTORE_DEFLATE_COMPRESS)
233 .zbufsize = zbufsize_deflate,
237 #if IS_ENABLED(CONFIG_PSTORE_LZO_COMPRESS)
239 .zbufsize = zbufsize_lzo,
243 #if IS_ENABLED(CONFIG_PSTORE_LZ4_COMPRESS)
245 .zbufsize = zbufsize_lz4,
249 #if IS_ENABLED(CONFIG_PSTORE_LZ4HC_COMPRESS)
251 .zbufsize = zbufsize_lz4,
255 #if IS_ENABLED(CONFIG_PSTORE_842_COMPRESS)
257 .zbufsize = zbufsize_842,
261 #if IS_ENABLED(CONFIG_PSTORE_ZSTD_COMPRESS)
263 .zbufsize = zbufsize_zstd,
270 static int pstore_compress(const void *in, void *out,
271 unsigned int inlen, unsigned int outlen)
275 if (!IS_ENABLED(CONFIG_PSTORE_COMPRESS))
278 ret = crypto_comp_compress(tfm, in, inlen, out, &outlen);
280 pr_err("crypto_comp_compress failed, ret = %d!\n", ret);
287 static void allocate_buf_for_compression(void)
289 struct crypto_comp *ctx;
293 /* Skip if not built-in or compression backend not selected yet. */
294 if (!IS_ENABLED(CONFIG_PSTORE_COMPRESS) || !zbackend)
297 /* Skip if no pstore backend yet or compression init already done. */
301 if (!crypto_has_comp(zbackend->name, 0, 0)) {
302 pr_err("Unknown compression: %s\n", zbackend->name);
306 size = zbackend->zbufsize(psinfo->bufsize);
308 pr_err("Invalid compression size for %s: %d\n",
309 zbackend->name, size);
313 buf = kmalloc(size, GFP_KERNEL);
315 pr_err("Failed %d byte compression buffer allocation for: %s\n",
316 size, zbackend->name);
320 ctx = crypto_alloc_comp(zbackend->name, 0, 0);
321 if (IS_ERR_OR_NULL(ctx)) {
323 pr_err("crypto_alloc_comp('%s') failed: %ld\n", zbackend->name,
328 /* A non-NULL big_oops_buf indicates compression is available. */
330 big_oops_buf_sz = size;
333 pr_info("Using crash dump compression: %s\n", zbackend->name);
336 static void free_buf_for_compression(void)
338 if (IS_ENABLED(CONFIG_PSTORE_COMPRESS) && tfm) {
339 crypto_free_comp(tfm);
348 * Called when compression fails, since the printk buffer
349 * would be fetched for compression calling it again when
350 * compression fails would have moved the iterator of
351 * printk buffer which results in fetching old contents.
352 * Copy the recent messages from big_oops_buf to psinfo->buf
354 static size_t copy_kmsg_to_buffer(int hsize, size_t len)
359 total_len = hsize + len;
361 if (total_len > psinfo->bufsize) {
362 diff = total_len - psinfo->bufsize + hsize;
363 memcpy(psinfo->buf, big_oops_buf, hsize);
364 memcpy(psinfo->buf + hsize, big_oops_buf + diff,
365 psinfo->bufsize - hsize);
366 total_len = psinfo->bufsize;
368 memcpy(psinfo->buf, big_oops_buf, total_len);
373 void pstore_record_init(struct pstore_record *record,
374 struct pstore_info *psinfo)
376 memset(record, 0, sizeof(*record));
378 record->psi = psinfo;
380 /* Report zeroed timestamp if called before timekeeping has resumed. */
381 record->time = ns_to_timespec64(ktime_get_real_fast_ns());
385 * callback from kmsg_dump. Save as much as we can (up to kmsg_bytes) from the
388 static void pstore_dump(struct kmsg_dumper *dumper,
389 enum kmsg_dump_reason reason)
391 struct kmsg_dump_iter iter;
392 unsigned long total = 0;
394 unsigned int part = 1;
395 unsigned long flags = 0;
399 why = kmsg_dump_reason_str(reason);
401 if (pstore_cannot_block_path(reason)) {
402 if (!spin_trylock_irqsave(&psinfo->buf_lock, flags)) {
403 pr_err("dump skipped in %s path because of concurrent dump\n",
404 in_nmi() ? "NMI" : why);
408 spin_lock_irqsave(&psinfo->buf_lock, flags);
411 kmsg_dump_rewind(&iter);
414 while (total < kmsg_bytes) {
420 struct pstore_record record;
422 pstore_record_init(&record, psinfo);
423 record.type = PSTORE_TYPE_DMESG;
424 record.count = oopscount;
425 record.reason = reason;
427 record.buf = psinfo->buf;
431 dst_size = big_oops_buf_sz;
434 dst_size = psinfo->bufsize;
437 /* Write dump header. */
438 header_size = snprintf(dst, dst_size, "%s#%d Part%u\n", why,
440 dst_size -= header_size;
442 /* Write dump contents. */
443 if (!kmsg_dump_get_buffer(&iter, true, dst + header_size,
444 dst_size, &dump_size))
448 zipped_len = pstore_compress(dst, psinfo->buf,
449 header_size + dump_size,
452 if (zipped_len > 0) {
453 record.compressed = true;
454 record.size = zipped_len;
456 record.size = copy_kmsg_to_buffer(header_size,
460 record.size = header_size + dump_size;
463 ret = psinfo->write(&record);
464 if (ret == 0 && reason == KMSG_DUMP_OOPS) {
465 pstore_new_entry = 1;
468 /* Preserve only the first non-zero returned value. */
473 total += record.size;
476 spin_unlock_irqrestore(&psinfo->buf_lock, flags);
479 pr_err_once("backend (%s) writing error (%d)\n", psinfo->name,
484 static struct kmsg_dumper pstore_dumper = {
489 * Register with kmsg_dump to save last part of console log on panic.
491 static void pstore_register_kmsg(void)
493 kmsg_dump_register(&pstore_dumper);
496 static void pstore_unregister_kmsg(void)
498 kmsg_dump_unregister(&pstore_dumper);
501 #ifdef CONFIG_PSTORE_CONSOLE
502 static void pstore_console_write(struct console *con, const char *s, unsigned c)
504 struct pstore_record record;
509 pstore_record_init(&record, psinfo);
510 record.type = PSTORE_TYPE_CONSOLE;
512 record.buf = (char *)s;
514 psinfo->write(&record);
517 static struct console pstore_console = {
518 .write = pstore_console_write,
522 static void pstore_register_console(void)
524 /* Show which backend is going to get console writes. */
525 strscpy(pstore_console.name, psinfo->name,
526 sizeof(pstore_console.name));
528 * Always initialize flags here since prior unregister_console()
529 * calls may have changed settings (specifically CON_ENABLED).
531 pstore_console.flags = CON_PRINTBUFFER | CON_ENABLED | CON_ANYTIME;
532 register_console(&pstore_console);
535 static void pstore_unregister_console(void)
537 unregister_console(&pstore_console);
540 static void pstore_register_console(void) {}
541 static void pstore_unregister_console(void) {}
544 static int pstore_write_user_compat(struct pstore_record *record,
545 const char __user *buf)
552 record->buf = memdup_user(buf, record->size);
553 if (IS_ERR(record->buf)) {
554 ret = PTR_ERR(record->buf);
558 ret = record->psi->write(record);
564 return unlikely(ret < 0) ? ret : record->size;
568 * platform specific persistent storage driver registers with
569 * us here. If pstore is already mounted, call the platform
570 * read function right away to populate the file system. If not
571 * then the pstore mount code will call us later to fill out
574 int pstore_register(struct pstore_info *psi)
576 if (backend && strcmp(backend, psi->name)) {
577 pr_warn("backend '%s' already in use: ignoring '%s'\n",
582 /* Sanity check flags. */
584 pr_warn("backend '%s' must support at least one frontend\n",
589 /* Check for required functions. */
590 if (!psi->read || !psi->write) {
591 pr_warn("backend '%s' must implement read() and write()\n",
596 mutex_lock(&psinfo_lock);
598 pr_warn("backend '%s' already loaded: ignoring '%s'\n",
599 psinfo->name, psi->name);
600 mutex_unlock(&psinfo_lock);
604 if (!psi->write_user)
605 psi->write_user = pstore_write_user_compat;
607 mutex_init(&psinfo->read_mutex);
608 spin_lock_init(&psinfo->buf_lock);
610 if (psi->flags & PSTORE_FLAGS_DMESG)
611 allocate_buf_for_compression();
613 pstore_get_records(0);
615 if (psi->flags & PSTORE_FLAGS_DMESG) {
616 pstore_dumper.max_reason = psinfo->max_reason;
617 pstore_register_kmsg();
619 if (psi->flags & PSTORE_FLAGS_CONSOLE)
620 pstore_register_console();
621 if (psi->flags & PSTORE_FLAGS_FTRACE)
622 pstore_register_ftrace();
623 if (psi->flags & PSTORE_FLAGS_PMSG)
624 pstore_register_pmsg();
626 /* Start watching for new records, if desired. */
630 * Update the module parameter backend, so it is visible
631 * through /sys/module/pstore/parameters/backend
633 backend = kstrdup(psi->name, GFP_KERNEL);
635 pr_info("Registered %s as persistent store backend\n", psi->name);
637 mutex_unlock(&psinfo_lock);
640 EXPORT_SYMBOL_GPL(pstore_register);
642 void pstore_unregister(struct pstore_info *psi)
644 /* It's okay to unregister nothing. */
648 mutex_lock(&psinfo_lock);
650 /* Only one backend can be registered at a time. */
651 if (WARN_ON(psi != psinfo)) {
652 mutex_unlock(&psinfo_lock);
656 /* Unregister all callbacks. */
657 if (psi->flags & PSTORE_FLAGS_PMSG)
658 pstore_unregister_pmsg();
659 if (psi->flags & PSTORE_FLAGS_FTRACE)
660 pstore_unregister_ftrace();
661 if (psi->flags & PSTORE_FLAGS_CONSOLE)
662 pstore_unregister_console();
663 if (psi->flags & PSTORE_FLAGS_DMESG)
664 pstore_unregister_kmsg();
666 /* Stop timer and make sure all work has finished. */
667 del_timer_sync(&pstore_timer);
668 flush_work(&pstore_work);
670 /* Remove all backend records from filesystem tree. */
671 pstore_put_backend_records(psi);
673 free_buf_for_compression();
679 pr_info("Unregistered %s as persistent store backend\n", psi->name);
680 mutex_unlock(&psinfo_lock);
682 EXPORT_SYMBOL_GPL(pstore_unregister);
684 static void decompress_record(struct pstore_record *record)
688 char *unzipped, *workspace;
690 if (!IS_ENABLED(CONFIG_PSTORE_COMPRESS) || !record->compressed)
693 /* Only PSTORE_TYPE_DMESG support compression. */
694 if (record->type != PSTORE_TYPE_DMESG) {
695 pr_warn("ignored compressed record type %d\n", record->type);
699 /* Missing compression buffer means compression was not initialized. */
701 pr_warn("no decompression method initialized!\n");
705 /* Allocate enough space to hold max decompression and ECC. */
706 unzipped_len = big_oops_buf_sz;
707 workspace = kmalloc(unzipped_len + record->ecc_notice_size,
712 /* After decompression "unzipped_len" is almost certainly smaller. */
713 ret = crypto_comp_decompress(tfm, record->buf, record->size,
714 workspace, &unzipped_len);
716 pr_err("crypto_comp_decompress failed, ret = %d!\n", ret);
721 /* Append ECC notice to decompressed buffer. */
722 memcpy(workspace + unzipped_len, record->buf + record->size,
723 record->ecc_notice_size);
725 /* Copy decompressed contents into an minimum-sized allocation. */
726 unzipped = kmemdup(workspace, unzipped_len + record->ecc_notice_size,
732 /* Swap out compressed contents with decompressed contents. */
734 record->buf = unzipped;
735 record->size = unzipped_len;
736 record->compressed = false;
740 * Read all the records from one persistent store backend. Create
741 * files in our filesystem. Don't warn about -EEXIST errors
742 * when we are re-scanning the backing store looking to add new
745 void pstore_get_backend_records(struct pstore_info *psi,
746 struct dentry *root, int quiet)
749 unsigned int stop_loop = 65536;
754 mutex_lock(&psi->read_mutex);
755 if (psi->open && psi->open(psi))
759 * Backend callback read() allocates record.buf. decompress_record()
760 * may reallocate record.buf. On success, pstore_mkfile() will keep
761 * the record.buf, so free it only on failure.
763 for (; stop_loop; stop_loop--) {
764 struct pstore_record *record;
767 record = kzalloc(sizeof(*record), GFP_KERNEL);
769 pr_err("out of memory creating record\n");
772 pstore_record_init(record, psi);
774 record->size = psi->read(record);
776 /* No more records left in backend? */
777 if (record->size <= 0) {
782 decompress_record(record);
783 rc = pstore_mkfile(root, record);
785 /* pstore_mkfile() did not take record, so free it. */
789 if (rc != -EEXIST || !quiet)
796 mutex_unlock(&psi->read_mutex);
799 pr_warn("failed to create %d record(s) from '%s'\n",
802 pr_err("looping? Too many records seen from '%s'\n",
806 static void pstore_dowork(struct work_struct *work)
808 pstore_get_records(1);
811 static void pstore_timefunc(struct timer_list *unused)
813 if (pstore_new_entry) {
814 pstore_new_entry = 0;
815 schedule_work(&pstore_work);
821 static void __init pstore_choose_compression(void)
823 const struct pstore_zbackend *step;
828 for (step = zbackends; step->name; step++) {
829 if (!strcmp(compress, step->name)) {
836 static int __init pstore_init(void)
840 pstore_choose_compression();
843 * Check if any pstore backends registered earlier but did not
844 * initialize compression because crypto was not ready. If so,
845 * initialize compression now.
847 allocate_buf_for_compression();
849 ret = pstore_init_fs();
851 free_buf_for_compression();
855 late_initcall(pstore_init);
857 static void __exit pstore_exit(void)
861 module_exit(pstore_exit)
863 MODULE_AUTHOR("Tony Luck <tony.luck@intel.com>");
864 MODULE_LICENSE("GPL");