• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Persistent Storage - platform driver interface parts.
4  *
5  * Copyright (C) 2007-2008 Google, Inc.
6  * Copyright (C) 2010 Intel Corporation <tony.luck@intel.com>
7  */
8 
9 #define pr_fmt(fmt) "pstore: " fmt
10 
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 #ifdef CONFIG_PSTORE_BLACKBOX
20 #include <linux/stacktrace.h>
21 #include <linux/blackbox.h>
22 #endif
23 #if IS_ENABLED(CONFIG_PSTORE_LZO_COMPRESS)
24 #include <linux/lzo.h>
25 #endif
26 #if IS_ENABLED(CONFIG_PSTORE_LZ4_COMPRESS) || IS_ENABLED(CONFIG_PSTORE_LZ4HC_COMPRESS)
27 #include <linux/lz4.h>
28 #endif
29 #if IS_ENABLED(CONFIG_PSTORE_ZSTD_COMPRESS)
30 #include <linux/zstd.h>
31 #endif
32 #include <linux/crypto.h>
33 #include <linux/string.h>
34 #include <linux/timer.h>
35 #include <linux/slab.h>
36 #include <linux/uaccess.h>
37 #include <linux/jiffies.h>
38 #include <linux/workqueue.h>
39 
40 #include "internal.h"
41 
42 /*
43  * We defer making "oops" entries appear in pstore - see
44  * whether the system is actually still running well enough
45  * to let someone see the entry
46  */
47 static int pstore_update_ms = -1;
48 module_param_named(update_ms, pstore_update_ms, int, 0600);
49 MODULE_PARM_DESC(update_ms, "milliseconds before pstore updates its content "
50 		 "(default is -1, which means runtime updates are disabled; "
51 		 "enabling this option may not be safe; it may lead to further "
52 		 "corruption on Oopses)");
53 
54 /* Names should be in the same order as the enum pstore_type_id */
55 static const char * const pstore_type_names[] = {
56 	"dmesg",
57 	"mce",
58 	"console",
59 	"ftrace",
60 	"rtas",
61 	"powerpc-ofw",
62 	"powerpc-common",
63 	"pmsg",
64 	"powerpc-opal",
65 	"blackbox",
66 };
67 
68 static int pstore_new_entry;
69 
70 static void pstore_timefunc(struct timer_list *);
71 static DEFINE_TIMER(pstore_timer, pstore_timefunc);
72 
73 static void pstore_dowork(struct work_struct *);
74 static DECLARE_WORK(pstore_work, pstore_dowork);
75 
76 /*
77  * psinfo_lock protects "psinfo" during calls to
78  * pstore_register(), pstore_unregister(), and
79  * the filesystem mount/unmount routines.
80  */
81 static DEFINE_MUTEX(psinfo_lock);
82 struct pstore_info *psinfo;
83 
84 static char *backend;
85 module_param(backend, charp, 0444);
86 MODULE_PARM_DESC(backend, "specific backend to use");
87 
88 static char *compress =
89 #ifdef CONFIG_PSTORE_COMPRESS_DEFAULT
90 		CONFIG_PSTORE_COMPRESS_DEFAULT;
91 #else
92 		NULL;
93 #endif
94 module_param(compress, charp, 0444);
95 MODULE_PARM_DESC(compress, "compression to use");
96 
97 /* Compression parameters */
98 static struct crypto_comp *tfm;
99 
100 struct pstore_zbackend {
101 	int (*zbufsize)(size_t size);
102 	const char *name;
103 };
104 
105 static char *big_oops_buf;
106 static size_t big_oops_buf_sz;
107 
108 /* How much of the console log to snapshot */
109 unsigned long kmsg_bytes = PSTORE_DEFAULT_KMSG_BYTES;
110 
pstore_set_kmsg_bytes(int bytes)111 void pstore_set_kmsg_bytes(int bytes)
112 {
113 	kmsg_bytes = bytes;
114 }
115 
116 /* Tag each group of saved records with a sequence number */
117 static int	oopscount;
118 
pstore_type_to_name(enum pstore_type_id type)119 const char *pstore_type_to_name(enum pstore_type_id type)
120 {
121 	BUILD_BUG_ON(ARRAY_SIZE(pstore_type_names) != PSTORE_TYPE_MAX);
122 
123 	if (WARN_ON_ONCE(type >= PSTORE_TYPE_MAX))
124 		return "unknown";
125 
126 	return pstore_type_names[type];
127 }
128 EXPORT_SYMBOL_GPL(pstore_type_to_name);
129 
pstore_name_to_type(const char * name)130 enum pstore_type_id pstore_name_to_type(const char *name)
131 {
132 	int i;
133 
134 	for (i = 0; i < PSTORE_TYPE_MAX; i++) {
135 		if (!strcmp(pstore_type_names[i], name))
136 			return i;
137 	}
138 
139 	return PSTORE_TYPE_MAX;
140 }
141 EXPORT_SYMBOL_GPL(pstore_name_to_type);
142 
pstore_timer_kick(void)143 static void pstore_timer_kick(void)
144 {
145 	if (pstore_update_ms < 0)
146 		return;
147 
148 	mod_timer(&pstore_timer, jiffies + msecs_to_jiffies(pstore_update_ms));
149 }
150 
151 /*
152  * Should pstore_dump() wait for a concurrent pstore_dump()? If
153  * not, the current pstore_dump() will report a failure to dump
154  * and return.
155  */
pstore_cannot_wait(enum kmsg_dump_reason reason)156 static bool pstore_cannot_wait(enum kmsg_dump_reason reason)
157 {
158 	/* In NMI path, pstore shouldn't block regardless of reason. */
159 	if (in_nmi())
160 		return true;
161 
162 	switch (reason) {
163 	/* In panic case, other cpus are stopped by smp_send_stop(). */
164 	case KMSG_DUMP_PANIC:
165 	/* Emergency restart shouldn't be blocked. */
166 	case KMSG_DUMP_EMERG:
167 		return true;
168 	default:
169 		return false;
170 	}
171 }
172 
173 #if IS_ENABLED(CONFIG_PSTORE_DEFLATE_COMPRESS)
zbufsize_deflate(size_t size)174 static int zbufsize_deflate(size_t size)
175 {
176 	size_t cmpr;
177 
178 	switch (size) {
179 	/* buffer range for efivars */
180 	case 1000 ... 2000:
181 		cmpr = 56;
182 		break;
183 	case 2001 ... 3000:
184 		cmpr = 54;
185 		break;
186 	case 3001 ... 3999:
187 		cmpr = 52;
188 		break;
189 	/* buffer range for nvram, erst */
190 	case 4000 ... 10000:
191 		cmpr = 45;
192 		break;
193 	default:
194 		cmpr = 60;
195 		break;
196 	}
197 
198 	return (size * 100) / cmpr;
199 }
200 #endif
201 
202 #if IS_ENABLED(CONFIG_PSTORE_LZO_COMPRESS)
zbufsize_lzo(size_t size)203 static int zbufsize_lzo(size_t size)
204 {
205 	return lzo1x_worst_compress(size);
206 }
207 #endif
208 
209 #if IS_ENABLED(CONFIG_PSTORE_LZ4_COMPRESS) || IS_ENABLED(CONFIG_PSTORE_LZ4HC_COMPRESS)
zbufsize_lz4(size_t size)210 static int zbufsize_lz4(size_t size)
211 {
212 	return LZ4_compressBound(size);
213 }
214 #endif
215 
216 #if IS_ENABLED(CONFIG_PSTORE_842_COMPRESS)
zbufsize_842(size_t size)217 static int zbufsize_842(size_t size)
218 {
219 	return size;
220 }
221 #endif
222 
223 #if IS_ENABLED(CONFIG_PSTORE_ZSTD_COMPRESS)
zbufsize_zstd(size_t size)224 static int zbufsize_zstd(size_t size)
225 {
226 	return ZSTD_compressBound(size);
227 }
228 #endif
229 
230 static const struct pstore_zbackend *zbackend __ro_after_init;
231 
232 static const struct pstore_zbackend zbackends[] = {
233 #if IS_ENABLED(CONFIG_PSTORE_DEFLATE_COMPRESS)
234 	{
235 		.zbufsize	= zbufsize_deflate,
236 		.name		= "deflate",
237 	},
238 #endif
239 #if IS_ENABLED(CONFIG_PSTORE_LZO_COMPRESS)
240 	{
241 		.zbufsize	= zbufsize_lzo,
242 		.name		= "lzo",
243 	},
244 #endif
245 #if IS_ENABLED(CONFIG_PSTORE_LZ4_COMPRESS)
246 	{
247 		.zbufsize	= zbufsize_lz4,
248 		.name		= "lz4",
249 	},
250 #endif
251 #if IS_ENABLED(CONFIG_PSTORE_LZ4HC_COMPRESS)
252 	{
253 		.zbufsize	= zbufsize_lz4,
254 		.name		= "lz4hc",
255 	},
256 #endif
257 #if IS_ENABLED(CONFIG_PSTORE_842_COMPRESS)
258 	{
259 		.zbufsize	= zbufsize_842,
260 		.name		= "842",
261 	},
262 #endif
263 #if IS_ENABLED(CONFIG_PSTORE_ZSTD_COMPRESS)
264 	{
265 		.zbufsize	= zbufsize_zstd,
266 		.name		= "zstd",
267 	},
268 #endif
269 	{ }
270 };
271 
pstore_compress(const void * in,void * out,unsigned int inlen,unsigned int outlen)272 static int pstore_compress(const void *in, void *out,
273 			   unsigned int inlen, unsigned int outlen)
274 {
275 	int ret;
276 
277 	if (!IS_ENABLED(CONFIG_PSTORE_COMPRESS))
278 		return -EINVAL;
279 
280 	ret = crypto_comp_compress(tfm, in, inlen, out, &outlen);
281 	if (ret) {
282 		pr_err("crypto_comp_compress failed, ret = %d!\n", ret);
283 		return ret;
284 	}
285 
286 	return outlen;
287 }
288 
allocate_buf_for_compression(void)289 static void allocate_buf_for_compression(void)
290 {
291 	struct crypto_comp *ctx;
292 	int size;
293 	char *buf;
294 
295 	/* Skip if not built-in or compression backend not selected yet. */
296 	if (!IS_ENABLED(CONFIG_PSTORE_COMPRESS) || !zbackend)
297 		return;
298 
299 	/* Skip if no pstore backend yet or compression init already done. */
300 	if (!psinfo || tfm)
301 		return;
302 
303 	if (!crypto_has_comp(zbackend->name, 0, 0)) {
304 		pr_err("Unknown compression: %s\n", zbackend->name);
305 		return;
306 	}
307 
308 	size = zbackend->zbufsize(psinfo->bufsize);
309 	if (size <= 0) {
310 		pr_err("Invalid compression size for %s: %d\n",
311 		       zbackend->name, size);
312 		return;
313 	}
314 
315 	buf = kmalloc(size, GFP_KERNEL);
316 	if (!buf) {
317 		pr_err("Failed %d byte compression buffer allocation for: %s\n",
318 		       size, zbackend->name);
319 		return;
320 	}
321 
322 	ctx = crypto_alloc_comp(zbackend->name, 0, 0);
323 	if (IS_ERR_OR_NULL(ctx)) {
324 		kfree(buf);
325 		pr_err("crypto_alloc_comp('%s') failed: %ld\n", zbackend->name,
326 		       PTR_ERR(ctx));
327 		return;
328 	}
329 
330 	/* A non-NULL big_oops_buf indicates compression is available. */
331 	tfm = ctx;
332 	big_oops_buf_sz = size;
333 	big_oops_buf = buf;
334 
335 	pr_info("Using crash dump compression: %s\n", zbackend->name);
336 }
337 
free_buf_for_compression(void)338 static void free_buf_for_compression(void)
339 {
340 	if (IS_ENABLED(CONFIG_PSTORE_COMPRESS) && tfm) {
341 		crypto_free_comp(tfm);
342 		tfm = NULL;
343 	}
344 	kfree(big_oops_buf);
345 	big_oops_buf = NULL;
346 	big_oops_buf_sz = 0;
347 }
348 
349 /*
350  * Called when compression fails, since the printk buffer
351  * would be fetched for compression calling it again when
352  * compression fails would have moved the iterator of
353  * printk buffer which results in fetching old contents.
354  * Copy the recent messages from big_oops_buf to psinfo->buf
355  */
copy_kmsg_to_buffer(int hsize,size_t len)356 static size_t copy_kmsg_to_buffer(int hsize, size_t len)
357 {
358 	size_t total_len;
359 	size_t diff;
360 
361 	total_len = hsize + len;
362 
363 	if (total_len > psinfo->bufsize) {
364 		diff = total_len - psinfo->bufsize + hsize;
365 		memcpy(psinfo->buf, big_oops_buf, hsize);
366 		memcpy(psinfo->buf + hsize, big_oops_buf + diff,
367 					psinfo->bufsize - hsize);
368 		total_len = psinfo->bufsize;
369 	} else
370 		memcpy(psinfo->buf, big_oops_buf, total_len);
371 
372 	return total_len;
373 }
374 
pstore_record_init(struct pstore_record * record,struct pstore_info * psinfo)375 void pstore_record_init(struct pstore_record *record,
376 			struct pstore_info *psinfo)
377 {
378 	memset(record, 0, sizeof(*record));
379 
380 	record->psi = psinfo;
381 
382 	/* Report zeroed timestamp if called before timekeeping has resumed. */
383 	record->time = ns_to_timespec64(ktime_get_real_fast_ns());
384 }
385 
386 /*
387  * Store the customised fault log
388  */
389 #ifdef CONFIG_PSTORE_BLACKBOX
390 #define PSTORE_FLAG           "PSTORE"
391 #define CALLSTACK_MAX_ENTRIES 20
dump_stacktrace(char * pbuf,size_t buf_size,bool is_panic)392 static void dump_stacktrace(char *pbuf, size_t buf_size, bool is_panic)
393 {
394 	int i;
395 	size_t stack_len = 0;
396 	size_t com_len = 0;
397 	unsigned long entries[CALLSTACK_MAX_ENTRIES];
398 	unsigned int nr_entries;
399 	char tmp_buf[ERROR_DESC_MAX_LEN];
400 	bool find_panic = false;
401 
402 	if (unlikely(!pbuf || !buf_size))
403 		return;
404 
405 	memset(pbuf, 0, buf_size);
406 	memset(tmp_buf, 0, sizeof(tmp_buf));
407 	nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 0);
408 	com_len = scnprintf(pbuf, buf_size, "Comm:%s,CPU:%d,Stack:",
409 						current->comm, raw_smp_processor_id());
410 	for (i = 0; i < nr_entries; i++) {
411 		if (stack_len >= sizeof(tmp_buf)) {
412 			tmp_buf[sizeof(tmp_buf) - 1] = '\0';
413 			break;
414 		}
415 		stack_len += scnprintf(tmp_buf + stack_len, sizeof(tmp_buf) - stack_len,
416 				"%pS-", (void *)entries[i]);
417 		if (!find_panic && is_panic) {
418 			if (strncmp(tmp_buf, "panic", strlen("panic")) == 0)
419 				find_panic = true;
420 			else
421 				(void)memset(tmp_buf, 0, sizeof(tmp_buf));
422 		}
423 	}
424 	if (com_len >= buf_size)
425 		return;
426 	stack_len = min(buf_size - com_len, strlen(tmp_buf));
427 	memcpy(pbuf + com_len, tmp_buf, stack_len);
428 	*(pbuf + buf_size - 1) = '\0';
429 }
430 
pstore_blackbox_dump(struct kmsg_dumper * dumper,enum kmsg_dump_reason reason)431 void pstore_blackbox_dump(struct kmsg_dumper *dumper,
432 						enum kmsg_dump_reason reason)
433 {
434 #if defined(CONFIG_PSTORE_BLK)
435 	const char *why;
436 	int        ret;
437 
438 	if (!pstore_blk_ready)
439 		return;
440 
441 	why = kmsg_dump_reason_str(reason);
442 
443 	if (down_trylock(&psinfo->buf_lock)) {
444 		/* Failed to acquire lock: give up if we cannot wait. */
445 		if (pstore_cannot_wait(reason)) {
446 			pr_err("dump skipped in %s path: may corrupt error record\n",
447 					in_nmi() ? "NMI" : why);
448 			return;
449 		}
450 		if (down_interruptible(&psinfo->buf_lock)) {
451 			pr_err("could not grab semaphore?!\n");
452 			return;
453 		}
454 	}
455 
456 	char *dst;
457 	size_t dst_size;
458 	struct pstore_record record;
459 	struct fault_log_info *pfault_log_info = (struct fault_log_info *)psinfo->buf;
460 
461 	memset(pfault_log_info, 0, sizeof(*pfault_log_info));
462 
463 	pstore_record_init(&record, psinfo);
464 
465 	record.type = PSTORE_TYPE_BLACKBOX;
466 	record.reason = reason;
467 
468 	memcpy(pfault_log_info->flag, LOG_FLAG, strlen(LOG_FLAG));
469 	strncpy(pfault_log_info->info.event, why,
470 					min(strlen(why), sizeof(pfault_log_info->info.event) - 1));
471 	strncpy(pfault_log_info->info.module, PSTORE_FLAG,
472 					min(strlen(PSTORE_FLAG), sizeof(pfault_log_info->info.module) - 1));
473 	get_timestamp(pfault_log_info->info.error_time, TIMESTAMP_MAX_LEN);
474 	dump_stacktrace(pfault_log_info->info.error_desc, sizeof(pfault_log_info->info.error_desc), false);
475 
476 	record.buf = psinfo->buf;
477 
478 	dst = psinfo->buf;
479 	dst_size = psinfo->bufsize;
480 
481 	dst_size -= sizeof(struct fault_log_info);
482 
483 	(void)kmsg_dump_get_buffer(dumper, true, dst + sizeof(struct fault_log_info),
484 								dst_size, &(pfault_log_info->len));
485 
486 	record.size = sizeof(struct fault_log_info) + pfault_log_info->len;
487 	ret = psinfo->write(&record);
488 
489 	up(&psinfo->buf_lock);
490 
491 #endif
492 }
493 EXPORT_SYMBOL_GPL(pstore_blackbox_dump);
494 #endif
495 
496 /*
497  * callback from kmsg_dump. Save as much as we can (up to kmsg_bytes) from the
498  * end of the buffer.
499  */
pstore_dump(struct kmsg_dumper * dumper,enum kmsg_dump_reason reason)500 static void pstore_dump(struct kmsg_dumper *dumper,
501 			enum kmsg_dump_reason reason)
502 {
503 	unsigned long	total = 0;
504 	const char	*why;
505 	unsigned int	part = 1;
506 	int		ret;
507 
508 	why = kmsg_dump_reason_str(reason);
509 
510 	if (down_trylock(&psinfo->buf_lock)) {
511 		/* Failed to acquire lock: give up if we cannot wait. */
512 		if (pstore_cannot_wait(reason)) {
513 			pr_err("dump skipped in %s path: may corrupt error record\n",
514 				in_nmi() ? "NMI" : why);
515 			return;
516 		}
517 		if (down_interruptible(&psinfo->buf_lock)) {
518 			pr_err("could not grab semaphore?!\n");
519 			return;
520 		}
521 	}
522 
523 	oopscount++;
524 	while (total < kmsg_bytes) {
525 		char *dst;
526 		size_t dst_size;
527 		int header_size;
528 		int zipped_len = -1;
529 		size_t dump_size;
530 		struct pstore_record record;
531 
532 		pstore_record_init(&record, psinfo);
533 		record.type = PSTORE_TYPE_DMESG;
534 		record.count = oopscount;
535 		record.reason = reason;
536 		record.part = part;
537 		record.buf = psinfo->buf;
538 
539 		if (big_oops_buf) {
540 			dst = big_oops_buf;
541 			dst_size = big_oops_buf_sz;
542 		} else {
543 			dst = psinfo->buf;
544 			dst_size = psinfo->bufsize;
545 		}
546 
547 		/* Write dump header. */
548 		header_size = snprintf(dst, dst_size, "%s#%d Part%u\n", why,
549 				 oopscount, part);
550 		dst_size -= header_size;
551 
552 		/* Write dump contents. */
553 		if (!kmsg_dump_get_buffer(dumper, true, dst + header_size,
554 					  dst_size, &dump_size))
555 			break;
556 
557 		if (big_oops_buf) {
558 			zipped_len = pstore_compress(dst, psinfo->buf,
559 						header_size + dump_size,
560 						psinfo->bufsize);
561 
562 			if (zipped_len > 0) {
563 				record.compressed = true;
564 				record.size = zipped_len;
565 			} else {
566 				record.size = copy_kmsg_to_buffer(header_size,
567 								  dump_size);
568 			}
569 		} else {
570 			record.size = header_size + dump_size;
571 		}
572 
573 		ret = psinfo->write(&record);
574 		if (ret == 0 && reason == KMSG_DUMP_OOPS) {
575 			pstore_new_entry = 1;
576 			pstore_timer_kick();
577 		}
578 
579 		total += record.size;
580 		part++;
581 	}
582 
583 	up(&psinfo->buf_lock);
584 }
585 
586 static struct kmsg_dumper pstore_dumper = {
587 	.dump = pstore_dump,
588 };
589 
590 /*
591  * Register with kmsg_dump to save last part of console log on panic.
592  */
pstore_register_kmsg(void)593 static void pstore_register_kmsg(void)
594 {
595 	kmsg_dump_register(&pstore_dumper);
596 }
597 
pstore_unregister_kmsg(void)598 static void pstore_unregister_kmsg(void)
599 {
600 	kmsg_dump_unregister(&pstore_dumper);
601 }
602 
603 #ifdef CONFIG_PSTORE_CONSOLE
pstore_console_write(struct console * con,const char * s,unsigned c)604 static void pstore_console_write(struct console *con, const char *s, unsigned c)
605 {
606 	struct pstore_record record;
607 
608 	if (!c)
609 		return;
610 
611 	pstore_record_init(&record, psinfo);
612 	record.type = PSTORE_TYPE_CONSOLE;
613 
614 	record.buf = (char *)s;
615 	record.size = c;
616 	psinfo->write(&record);
617 }
618 
619 static struct console pstore_console = {
620 	.write	= pstore_console_write,
621 	.index	= -1,
622 };
623 
pstore_register_console(void)624 static void pstore_register_console(void)
625 {
626 	/* Show which backend is going to get console writes. */
627 	strscpy(pstore_console.name, psinfo->name,
628 		sizeof(pstore_console.name));
629 	/*
630 	 * Always initialize flags here since prior unregister_console()
631 	 * calls may have changed settings (specifically CON_ENABLED).
632 	 */
633 	pstore_console.flags = CON_PRINTBUFFER | CON_ENABLED | CON_ANYTIME;
634 	register_console(&pstore_console);
635 }
636 
pstore_unregister_console(void)637 static void pstore_unregister_console(void)
638 {
639 	unregister_console(&pstore_console);
640 }
641 #else
pstore_register_console(void)642 static void pstore_register_console(void) {}
pstore_unregister_console(void)643 static void pstore_unregister_console(void) {}
644 #endif
645 
pstore_write_user_compat(struct pstore_record * record,const char __user * buf)646 static int pstore_write_user_compat(struct pstore_record *record,
647 				    const char __user *buf)
648 {
649 	int ret = 0;
650 
651 	if (record->buf)
652 		return -EINVAL;
653 
654 	record->buf = memdup_user(buf, record->size);
655 	if (IS_ERR(record->buf)) {
656 		ret = PTR_ERR(record->buf);
657 		goto out;
658 	}
659 
660 	ret = record->psi->write(record);
661 
662 	kfree(record->buf);
663 out:
664 	record->buf = NULL;
665 
666 	return unlikely(ret < 0) ? ret : record->size;
667 }
668 
669 /*
670  * platform specific persistent storage driver registers with
671  * us here. If pstore is already mounted, call the platform
672  * read function right away to populate the file system. If not
673  * then the pstore mount code will call us later to fill out
674  * the file system.
675  */
pstore_register(struct pstore_info * psi)676 int pstore_register(struct pstore_info *psi)
677 {
678 	if (backend && strcmp(backend, psi->name)) {
679 		pr_warn("ignoring unexpected backend '%s'\n", psi->name);
680 		return -EPERM;
681 	}
682 
683 	/* Sanity check flags. */
684 	if (!psi->flags) {
685 		pr_warn("backend '%s' must support at least one frontend\n",
686 			psi->name);
687 		return -EINVAL;
688 	}
689 
690 	/* Check for required functions. */
691 	if (!psi->read || !psi->write) {
692 		pr_warn("backend '%s' must implement read() and write()\n",
693 			psi->name);
694 		return -EINVAL;
695 	}
696 
697 	mutex_lock(&psinfo_lock);
698 	if (psinfo) {
699 		pr_warn("backend '%s' already loaded: ignoring '%s'\n",
700 			psinfo->name, psi->name);
701 		mutex_unlock(&psinfo_lock);
702 		return -EBUSY;
703 	}
704 
705 	if (!psi->write_user)
706 		psi->write_user = pstore_write_user_compat;
707 	psinfo = psi;
708 	mutex_init(&psinfo->read_mutex);
709 	sema_init(&psinfo->buf_lock, 1);
710 
711 	if (psi->flags & PSTORE_FLAGS_DMESG)
712 		allocate_buf_for_compression();
713 
714 	pstore_get_records(0);
715 
716 	if (psi->flags & PSTORE_FLAGS_DMESG) {
717 		pstore_dumper.max_reason = psinfo->max_reason;
718 		pstore_register_kmsg();
719 	}
720 	if (psi->flags & PSTORE_FLAGS_CONSOLE)
721 		pstore_register_console();
722 	if (psi->flags & PSTORE_FLAGS_FTRACE)
723 		pstore_register_ftrace();
724 	if (psi->flags & PSTORE_FLAGS_PMSG)
725 		pstore_register_pmsg();
726 
727 	/* Start watching for new records, if desired. */
728 	pstore_timer_kick();
729 
730 	/*
731 	 * Update the module parameter backend, so it is visible
732 	 * through /sys/module/pstore/parameters/backend
733 	 */
734 	backend = kstrdup(psi->name, GFP_KERNEL);
735 
736 	pr_info("Registered %s as persistent store backend\n", psi->name);
737 
738 	mutex_unlock(&psinfo_lock);
739 	return 0;
740 }
741 EXPORT_SYMBOL_GPL(pstore_register);
742 
pstore_unregister(struct pstore_info * psi)743 void pstore_unregister(struct pstore_info *psi)
744 {
745 	/* It's okay to unregister nothing. */
746 	if (!psi)
747 		return;
748 
749 	mutex_lock(&psinfo_lock);
750 
751 	/* Only one backend can be registered at a time. */
752 	if (WARN_ON(psi != psinfo)) {
753 		mutex_unlock(&psinfo_lock);
754 		return;
755 	}
756 
757 	/* Unregister all callbacks. */
758 	if (psi->flags & PSTORE_FLAGS_PMSG)
759 		pstore_unregister_pmsg();
760 	if (psi->flags & PSTORE_FLAGS_FTRACE)
761 		pstore_unregister_ftrace();
762 	if (psi->flags & PSTORE_FLAGS_CONSOLE)
763 		pstore_unregister_console();
764 	if (psi->flags & PSTORE_FLAGS_DMESG)
765 		pstore_unregister_kmsg();
766 
767 	/* Stop timer and make sure all work has finished. */
768 	del_timer_sync(&pstore_timer);
769 	flush_work(&pstore_work);
770 
771 	/* Remove all backend records from filesystem tree. */
772 	pstore_put_backend_records(psi);
773 
774 	free_buf_for_compression();
775 
776 	psinfo = NULL;
777 	kfree(backend);
778 	backend = NULL;
779 	mutex_unlock(&psinfo_lock);
780 }
781 EXPORT_SYMBOL_GPL(pstore_unregister);
782 
decompress_record(struct pstore_record * record)783 static void decompress_record(struct pstore_record *record)
784 {
785 	int ret;
786 	int unzipped_len;
787 	char *unzipped, *workspace;
788 
789 	if (!IS_ENABLED(CONFIG_PSTORE_COMPRESS) || !record->compressed)
790 		return;
791 
792 	/* Only PSTORE_TYPE_DMESG support compression. */
793 	if (record->type != PSTORE_TYPE_DMESG) {
794 		pr_warn("ignored compressed record type %d\n", record->type);
795 		return;
796 	}
797 
798 	/* Missing compression buffer means compression was not initialized. */
799 	if (!big_oops_buf) {
800 		pr_warn("no decompression method initialized!\n");
801 		return;
802 	}
803 
804 	/* Allocate enough space to hold max decompression and ECC. */
805 	unzipped_len = big_oops_buf_sz;
806 	workspace = kmalloc(unzipped_len + record->ecc_notice_size,
807 			    GFP_KERNEL);
808 	if (!workspace)
809 		return;
810 
811 	/* After decompression "unzipped_len" is almost certainly smaller. */
812 	ret = crypto_comp_decompress(tfm, record->buf, record->size,
813 					  workspace, &unzipped_len);
814 	if (ret) {
815 		pr_err("crypto_comp_decompress failed, ret = %d!\n", ret);
816 		kfree(workspace);
817 		return;
818 	}
819 
820 	/* Append ECC notice to decompressed buffer. */
821 	memcpy(workspace + unzipped_len, record->buf + record->size,
822 	       record->ecc_notice_size);
823 
824 	/* Copy decompressed contents into an minimum-sized allocation. */
825 	unzipped = kmemdup(workspace, unzipped_len + record->ecc_notice_size,
826 			   GFP_KERNEL);
827 	kfree(workspace);
828 	if (!unzipped)
829 		return;
830 
831 	/* Swap out compressed contents with decompressed contents. */
832 	kfree(record->buf);
833 	record->buf = unzipped;
834 	record->size = unzipped_len;
835 	record->compressed = false;
836 }
837 
838 /*
839  * Read all the records from one persistent store backend. Create
840  * files in our filesystem.  Don't warn about -EEXIST errors
841  * when we are re-scanning the backing store looking to add new
842  * error records.
843  */
pstore_get_backend_records(struct pstore_info * psi,struct dentry * root,int quiet)844 void pstore_get_backend_records(struct pstore_info *psi,
845 				struct dentry *root, int quiet)
846 {
847 	int failed = 0;
848 	unsigned int stop_loop = 65536;
849 
850 	if (!psi || !root)
851 		return;
852 
853 	mutex_lock(&psi->read_mutex);
854 	if (psi->open && psi->open(psi))
855 		goto out;
856 
857 	/*
858 	 * Backend callback read() allocates record.buf. decompress_record()
859 	 * may reallocate record.buf. On success, pstore_mkfile() will keep
860 	 * the record.buf, so free it only on failure.
861 	 */
862 	for (; stop_loop; stop_loop--) {
863 		struct pstore_record *record;
864 		int rc;
865 
866 		record = kzalloc(sizeof(*record), GFP_KERNEL);
867 		if (!record) {
868 			pr_err("out of memory creating record\n");
869 			break;
870 		}
871 		pstore_record_init(record, psi);
872 
873 		record->size = psi->read(record);
874 
875 		/* No more records left in backend? */
876 		if (record->size <= 0) {
877 			kfree(record);
878 			break;
879 		}
880 
881 		decompress_record(record);
882 		rc = pstore_mkfile(root, record);
883 		if (rc) {
884 			/* pstore_mkfile() did not take record, so free it. */
885 			kfree(record->buf);
886 			kfree(record);
887 			if (rc != -EEXIST || !quiet)
888 				failed++;
889 		}
890 	}
891 	if (psi->close)
892 		psi->close(psi);
893 out:
894 	mutex_unlock(&psi->read_mutex);
895 
896 	if (failed)
897 		pr_warn("failed to create %d record(s) from '%s'\n",
898 			failed, psi->name);
899 	if (!stop_loop)
900 		pr_err("looping? Too many records seen from '%s'\n",
901 			psi->name);
902 }
903 
pstore_dowork(struct work_struct * work)904 static void pstore_dowork(struct work_struct *work)
905 {
906 	pstore_get_records(1);
907 }
908 
pstore_timefunc(struct timer_list * unused)909 static void pstore_timefunc(struct timer_list *unused)
910 {
911 	if (pstore_new_entry) {
912 		pstore_new_entry = 0;
913 		schedule_work(&pstore_work);
914 	}
915 
916 	pstore_timer_kick();
917 }
918 
pstore_choose_compression(void)919 static void __init pstore_choose_compression(void)
920 {
921 	const struct pstore_zbackend *step;
922 
923 	if (!compress)
924 		return;
925 
926 	for (step = zbackends; step->name; step++) {
927 		if (!strcmp(compress, step->name)) {
928 			zbackend = step;
929 			return;
930 		}
931 	}
932 }
933 
pstore_init(void)934 static int __init pstore_init(void)
935 {
936 	int ret;
937 
938 	pstore_choose_compression();
939 
940 	/*
941 	 * Check if any pstore backends registered earlier but did not
942 	 * initialize compression because crypto was not ready. If so,
943 	 * initialize compression now.
944 	 */
945 	allocate_buf_for_compression();
946 
947 	ret = pstore_init_fs();
948 	if (ret)
949 		free_buf_for_compression();
950 
951 	return ret;
952 }
953 late_initcall(pstore_init);
954 
pstore_exit(void)955 static void __exit pstore_exit(void)
956 {
957 	pstore_exit_fs();
958 }
959 module_exit(pstore_exit)
960 
961 MODULE_AUTHOR("Tony Luck <tony.luck@intel.com>");
962 MODULE_LICENSE("GPL");
963