xref: /linux/arch/powerpc/kernel/nvram_64.c (revision 9fb29c734f9e98adc1f2f3c4629fe487cb93f2dd)
1 /*
2  *  c 2001 PPC 64 Team, IBM Corp
3  *
4  *      This program is free software; you can redistribute it and/or
5  *      modify it under the terms of the GNU General Public License
6  *      as published by the Free Software Foundation; either version
7  *      2 of the License, or (at your option) any later version.
8  *
9  * /dev/nvram driver for PPC64
10  *
11  * This perhaps should live in drivers/char
12  *
13  * TODO: Split the /dev/nvram part (that one can use
14  *       drivers/char/generic_nvram.c) from the arch & partition
15  *       parsing code.
16  */
17 
18 #include <linux/types.h>
19 #include <linux/errno.h>
20 #include <linux/fs.h>
21 #include <linux/miscdevice.h>
22 #include <linux/fcntl.h>
23 #include <linux/nvram.h>
24 #include <linux/init.h>
25 #include <linux/slab.h>
26 #include <linux/spinlock.h>
27 #include <linux/kmsg_dump.h>
28 #include <linux/pagemap.h>
29 #include <linux/pstore.h>
30 #include <linux/zlib.h>
31 #include <linux/uaccess.h>
32 #include <asm/nvram.h>
33 #include <asm/rtas.h>
34 #include <asm/prom.h>
35 #include <asm/machdep.h>
36 
37 #undef DEBUG_NVRAM
38 
39 #define NVRAM_HEADER_LEN	sizeof(struct nvram_header)
40 #define NVRAM_BLOCK_LEN		NVRAM_HEADER_LEN
41 
42 /* If change this size, then change the size of NVNAME_LEN */
43 struct nvram_header {
44 	unsigned char signature;
45 	unsigned char checksum;
46 	unsigned short length;
47 	/* Terminating null required only for names < 12 chars. */
48 	char name[12];
49 };
50 
51 struct nvram_partition {
52 	struct list_head partition;
53 	struct nvram_header header;
54 	unsigned int index;
55 };
56 
57 static LIST_HEAD(nvram_partitions);
58 
59 #ifdef CONFIG_PPC_PSERIES
60 struct nvram_os_partition rtas_log_partition = {
61 	.name = "ibm,rtas-log",
62 	.req_size = 2079,
63 	.min_size = 1055,
64 	.index = -1,
65 	.os_partition = true
66 };
67 #endif
68 
69 struct nvram_os_partition oops_log_partition = {
70 	.name = "lnx,oops-log",
71 	.req_size = 4000,
72 	.min_size = 2000,
73 	.index = -1,
74 	.os_partition = true
75 };
76 
77 static const char *nvram_os_partitions[] = {
78 #ifdef CONFIG_PPC_PSERIES
79 	"ibm,rtas-log",
80 #endif
81 	"lnx,oops-log",
82 	NULL
83 };
84 
85 static void oops_to_nvram(struct kmsg_dumper *dumper,
86 			  enum kmsg_dump_reason reason);
87 
88 static struct kmsg_dumper nvram_kmsg_dumper = {
89 	.dump = oops_to_nvram
90 };
91 
92 /*
93  * For capturing and compressing an oops or panic report...
94 
95  * big_oops_buf[] holds the uncompressed text we're capturing.
96  *
97  * oops_buf[] holds the compressed text, preceded by a oops header.
98  * oops header has u16 holding the version of oops header (to differentiate
99  * between old and new format header) followed by u16 holding the length of
100  * the compressed* text (*Or uncompressed, if compression fails.) and u64
101  * holding the timestamp. oops_buf[] gets written to NVRAM.
102  *
103  * oops_log_info points to the header. oops_data points to the compressed text.
104  *
105  * +- oops_buf
106  * |                                   +- oops_data
107  * v                                   v
108  * +-----------+-----------+-----------+------------------------+
109  * | version   | length    | timestamp | text                   |
110  * | (2 bytes) | (2 bytes) | (8 bytes) | (oops_data_sz bytes)   |
111  * +-----------+-----------+-----------+------------------------+
112  * ^
113  * +- oops_log_info
114  *
115  * We preallocate these buffers during init to avoid kmalloc during oops/panic.
116  */
117 static size_t big_oops_buf_sz;
118 static char *big_oops_buf, *oops_buf;
119 static char *oops_data;
120 static size_t oops_data_sz;
121 
122 /* Compression parameters */
123 #define COMPR_LEVEL 6
124 #define WINDOW_BITS 12
125 #define MEM_LEVEL 4
126 static struct z_stream_s stream;
127 
128 #ifdef CONFIG_PSTORE
129 #ifdef CONFIG_PPC_POWERNV
130 static struct nvram_os_partition skiboot_partition = {
131 	.name = "ibm,skiboot",
132 	.index = -1,
133 	.os_partition = false
134 };
135 #endif
136 
137 #ifdef CONFIG_PPC_PSERIES
138 static struct nvram_os_partition of_config_partition = {
139 	.name = "of-config",
140 	.index = -1,
141 	.os_partition = false
142 };
143 #endif
144 
145 static struct nvram_os_partition common_partition = {
146 	.name = "common",
147 	.index = -1,
148 	.os_partition = false
149 };
150 
151 static enum pstore_type_id nvram_type_ids[] = {
152 	PSTORE_TYPE_DMESG,
153 	PSTORE_TYPE_PPC_COMMON,
154 	-1,
155 	-1,
156 	-1
157 };
158 static int read_type;
159 #endif
160 
161 /* nvram_write_os_partition
162  *
163  * We need to buffer the error logs into nvram to ensure that we have
164  * the failure information to decode.  If we have a severe error there
165  * is no way to guarantee that the OS or the machine is in a state to
166  * get back to user land and write the error to disk.  For example if
167  * the SCSI device driver causes a Machine Check by writing to a bad
168  * IO address, there is no way of guaranteeing that the device driver
169  * is in any state that is would also be able to write the error data
170  * captured to disk, thus we buffer it in NVRAM for analysis on the
171  * next boot.
172  *
173  * In NVRAM the partition containing the error log buffer will looks like:
174  * Header (in bytes):
175  * +-----------+----------+--------+------------+------------------+
176  * | signature | checksum | length | name       | data             |
177  * |0          |1         |2      3|4         15|16        length-1|
178  * +-----------+----------+--------+------------+------------------+
179  *
180  * The 'data' section would look like (in bytes):
181  * +--------------+------------+-----------------------------------+
182  * | event_logged | sequence # | error log                         |
183  * |0            3|4          7|8                  error_log_size-1|
184  * +--------------+------------+-----------------------------------+
185  *
186  * event_logged: 0 if event has not been logged to syslog, 1 if it has
187  * sequence #: The unique sequence # for each event. (until it wraps)
188  * error log: The error log from event_scan
189  */
190 int nvram_write_os_partition(struct nvram_os_partition *part,
191 			     char *buff, int length,
192 			     unsigned int err_type,
193 			     unsigned int error_log_cnt)
194 {
195 	int rc;
196 	loff_t tmp_index;
197 	struct err_log_info info;
198 
199 	if (part->index == -1)
200 		return -ESPIPE;
201 
202 	if (length > part->size)
203 		length = part->size;
204 
205 	info.error_type = cpu_to_be32(err_type);
206 	info.seq_num = cpu_to_be32(error_log_cnt);
207 
208 	tmp_index = part->index;
209 
210 	rc = ppc_md.nvram_write((char *)&info, sizeof(info), &tmp_index);
211 	if (rc <= 0) {
212 		pr_err("%s: Failed nvram_write (%d)\n", __func__, rc);
213 		return rc;
214 	}
215 
216 	rc = ppc_md.nvram_write(buff, length, &tmp_index);
217 	if (rc <= 0) {
218 		pr_err("%s: Failed nvram_write (%d)\n", __func__, rc);
219 		return rc;
220 	}
221 
222 	return 0;
223 }
224 
225 /* nvram_read_partition
226  *
227  * Reads nvram partition for at most 'length'
228  */
229 int nvram_read_partition(struct nvram_os_partition *part, char *buff,
230 			 int length, unsigned int *err_type,
231 			 unsigned int *error_log_cnt)
232 {
233 	int rc;
234 	loff_t tmp_index;
235 	struct err_log_info info;
236 
237 	if (part->index == -1)
238 		return -1;
239 
240 	if (length > part->size)
241 		length = part->size;
242 
243 	tmp_index = part->index;
244 
245 	if (part->os_partition) {
246 		rc = ppc_md.nvram_read((char *)&info, sizeof(info), &tmp_index);
247 		if (rc <= 0) {
248 			pr_err("%s: Failed nvram_read (%d)\n", __func__, rc);
249 			return rc;
250 		}
251 	}
252 
253 	rc = ppc_md.nvram_read(buff, length, &tmp_index);
254 	if (rc <= 0) {
255 		pr_err("%s: Failed nvram_read (%d)\n", __func__, rc);
256 		return rc;
257 	}
258 
259 	if (part->os_partition) {
260 		*error_log_cnt = be32_to_cpu(info.seq_num);
261 		*err_type = be32_to_cpu(info.error_type);
262 	}
263 
264 	return 0;
265 }
266 
267 /* nvram_init_os_partition
268  *
269  * This sets up a partition with an "OS" signature.
270  *
271  * The general strategy is the following:
272  * 1.) If a partition with the indicated name already exists...
273  *	- If it's large enough, use it.
274  *	- Otherwise, recycle it and keep going.
275  * 2.) Search for a free partition that is large enough.
276  * 3.) If there's not a free partition large enough, recycle any obsolete
277  * OS partitions and try again.
278  * 4.) Will first try getting a chunk that will satisfy the requested size.
279  * 5.) If a chunk of the requested size cannot be allocated, then try finding
280  * a chunk that will satisfy the minum needed.
281  *
282  * Returns 0 on success, else -1.
283  */
284 int __init nvram_init_os_partition(struct nvram_os_partition *part)
285 {
286 	loff_t p;
287 	int size;
288 
289 	/* Look for ours */
290 	p = nvram_find_partition(part->name, NVRAM_SIG_OS, &size);
291 
292 	/* Found one but too small, remove it */
293 	if (p && size < part->min_size) {
294 		pr_info("nvram: Found too small %s partition,"
295 					" removing it...\n", part->name);
296 		nvram_remove_partition(part->name, NVRAM_SIG_OS, NULL);
297 		p = 0;
298 	}
299 
300 	/* Create one if we didn't find */
301 	if (!p) {
302 		p = nvram_create_partition(part->name, NVRAM_SIG_OS,
303 					part->req_size, part->min_size);
304 		if (p == -ENOSPC) {
305 			pr_info("nvram: No room to create %s partition, "
306 				"deleting any obsolete OS partitions...\n",
307 				part->name);
308 			nvram_remove_partition(NULL, NVRAM_SIG_OS,
309 					nvram_os_partitions);
310 			p = nvram_create_partition(part->name, NVRAM_SIG_OS,
311 					part->req_size, part->min_size);
312 		}
313 	}
314 
315 	if (p <= 0) {
316 		pr_err("nvram: Failed to find or create %s"
317 		       " partition, err %d\n", part->name, (int)p);
318 		return -1;
319 	}
320 
321 	part->index = p;
322 	part->size = nvram_get_partition_size(p) - sizeof(struct err_log_info);
323 
324 	return 0;
325 }
326 
327 /* Derived from logfs_compress() */
328 static int nvram_compress(const void *in, void *out, size_t inlen,
329 							size_t outlen)
330 {
331 	int err, ret;
332 
333 	ret = -EIO;
334 	err = zlib_deflateInit2(&stream, COMPR_LEVEL, Z_DEFLATED, WINDOW_BITS,
335 						MEM_LEVEL, Z_DEFAULT_STRATEGY);
336 	if (err != Z_OK)
337 		goto error;
338 
339 	stream.next_in = in;
340 	stream.avail_in = inlen;
341 	stream.total_in = 0;
342 	stream.next_out = out;
343 	stream.avail_out = outlen;
344 	stream.total_out = 0;
345 
346 	err = zlib_deflate(&stream, Z_FINISH);
347 	if (err != Z_STREAM_END)
348 		goto error;
349 
350 	err = zlib_deflateEnd(&stream);
351 	if (err != Z_OK)
352 		goto error;
353 
354 	if (stream.total_out >= stream.total_in)
355 		goto error;
356 
357 	ret = stream.total_out;
358 error:
359 	return ret;
360 }
361 
362 /* Compress the text from big_oops_buf into oops_buf. */
363 static int zip_oops(size_t text_len)
364 {
365 	struct oops_log_info *oops_hdr = (struct oops_log_info *)oops_buf;
366 	int zipped_len = nvram_compress(big_oops_buf, oops_data, text_len,
367 								oops_data_sz);
368 	if (zipped_len < 0) {
369 		pr_err("nvram: compression failed; returned %d\n", zipped_len);
370 		pr_err("nvram: logging uncompressed oops/panic report\n");
371 		return -1;
372 	}
373 	oops_hdr->version = cpu_to_be16(OOPS_HDR_VERSION);
374 	oops_hdr->report_length = cpu_to_be16(zipped_len);
375 	oops_hdr->timestamp = cpu_to_be64(ktime_get_real_seconds());
376 	return 0;
377 }
378 
379 #ifdef CONFIG_PSTORE
380 static int nvram_pstore_open(struct pstore_info *psi)
381 {
382 	/* Reset the iterator to start reading partitions again */
383 	read_type = -1;
384 	return 0;
385 }
386 
387 /**
388  * nvram_pstore_write - pstore write callback for nvram
389  * @record:             pstore record to write, with @id to be set
390  *
391  * Called by pstore_dump() when an oops or panic report is logged in the
392  * printk buffer.
393  * Returns 0 on successful write.
394  */
395 static int nvram_pstore_write(struct pstore_record *record)
396 {
397 	int rc;
398 	unsigned int err_type = ERR_TYPE_KERNEL_PANIC;
399 	struct oops_log_info *oops_hdr = (struct oops_log_info *) oops_buf;
400 
401 	/* part 1 has the recent messages from printk buffer */
402 	if (record->part > 1 || (record->type != PSTORE_TYPE_DMESG))
403 		return -1;
404 
405 	if (clobbering_unread_rtas_event())
406 		return -1;
407 
408 	oops_hdr->version = cpu_to_be16(OOPS_HDR_VERSION);
409 	oops_hdr->report_length = cpu_to_be16(record->size);
410 	oops_hdr->timestamp = cpu_to_be64(ktime_get_real_seconds());
411 
412 	if (record->compressed)
413 		err_type = ERR_TYPE_KERNEL_PANIC_GZ;
414 
415 	rc = nvram_write_os_partition(&oops_log_partition, oops_buf,
416 		(int) (sizeof(*oops_hdr) + record->size), err_type,
417 		record->count);
418 
419 	if (rc != 0)
420 		return rc;
421 
422 	record->id = record->part;
423 	return 0;
424 }
425 
426 /*
427  * Reads the oops/panic report, rtas, of-config and common partition.
428  * Returns the length of the data we read from each partition.
429  * Returns 0 if we've been called before.
430  */
431 static ssize_t nvram_pstore_read(struct pstore_record *record)
432 {
433 	struct oops_log_info *oops_hdr;
434 	unsigned int err_type, id_no, size = 0;
435 	struct nvram_os_partition *part = NULL;
436 	char *buff = NULL;
437 	int sig = 0;
438 	loff_t p;
439 
440 	read_type++;
441 
442 	switch (nvram_type_ids[read_type]) {
443 	case PSTORE_TYPE_DMESG:
444 		part = &oops_log_partition;
445 		record->type = PSTORE_TYPE_DMESG;
446 		break;
447 	case PSTORE_TYPE_PPC_COMMON:
448 		sig = NVRAM_SIG_SYS;
449 		part = &common_partition;
450 		record->type = PSTORE_TYPE_PPC_COMMON;
451 		record->id = PSTORE_TYPE_PPC_COMMON;
452 		record->time.tv_sec = 0;
453 		record->time.tv_nsec = 0;
454 		break;
455 #ifdef CONFIG_PPC_PSERIES
456 	case PSTORE_TYPE_PPC_RTAS:
457 		part = &rtas_log_partition;
458 		record->type = PSTORE_TYPE_PPC_RTAS;
459 		record->time.tv_sec = last_rtas_event;
460 		record->time.tv_nsec = 0;
461 		break;
462 	case PSTORE_TYPE_PPC_OF:
463 		sig = NVRAM_SIG_OF;
464 		part = &of_config_partition;
465 		record->type = PSTORE_TYPE_PPC_OF;
466 		record->id = PSTORE_TYPE_PPC_OF;
467 		record->time.tv_sec = 0;
468 		record->time.tv_nsec = 0;
469 		break;
470 #endif
471 #ifdef CONFIG_PPC_POWERNV
472 	case PSTORE_TYPE_PPC_OPAL:
473 		sig = NVRAM_SIG_FW;
474 		part = &skiboot_partition;
475 		record->type = PSTORE_TYPE_PPC_OPAL;
476 		record->id = PSTORE_TYPE_PPC_OPAL;
477 		record->time.tv_sec = 0;
478 		record->time.tv_nsec = 0;
479 		break;
480 #endif
481 	default:
482 		return 0;
483 	}
484 
485 	if (!part->os_partition) {
486 		p = nvram_find_partition(part->name, sig, &size);
487 		if (p <= 0) {
488 			pr_err("nvram: Failed to find partition %s, "
489 				"err %d\n", part->name, (int)p);
490 			return 0;
491 		}
492 		part->index = p;
493 		part->size = size;
494 	}
495 
496 	buff = kmalloc(part->size, GFP_KERNEL);
497 
498 	if (!buff)
499 		return -ENOMEM;
500 
501 	if (nvram_read_partition(part, buff, part->size, &err_type, &id_no)) {
502 		kfree(buff);
503 		return 0;
504 	}
505 
506 	record->count = 0;
507 
508 	if (part->os_partition)
509 		record->id = id_no;
510 
511 	if (nvram_type_ids[read_type] == PSTORE_TYPE_DMESG) {
512 		size_t length, hdr_size;
513 
514 		oops_hdr = (struct oops_log_info *)buff;
515 		if (be16_to_cpu(oops_hdr->version) < OOPS_HDR_VERSION) {
516 			/* Old format oops header had 2-byte record size */
517 			hdr_size = sizeof(u16);
518 			length = be16_to_cpu(oops_hdr->version);
519 			record->time.tv_sec = 0;
520 			record->time.tv_nsec = 0;
521 		} else {
522 			hdr_size = sizeof(*oops_hdr);
523 			length = be16_to_cpu(oops_hdr->report_length);
524 			record->time.tv_sec = be64_to_cpu(oops_hdr->timestamp);
525 			record->time.tv_nsec = 0;
526 		}
527 		record->buf = kmemdup(buff + hdr_size, length, GFP_KERNEL);
528 		kfree(buff);
529 		if (record->buf == NULL)
530 			return -ENOMEM;
531 
532 		record->ecc_notice_size = 0;
533 		if (err_type == ERR_TYPE_KERNEL_PANIC_GZ)
534 			record->compressed = true;
535 		else
536 			record->compressed = false;
537 		return length;
538 	}
539 
540 	record->buf = buff;
541 	return part->size;
542 }
543 
544 static struct pstore_info nvram_pstore_info = {
545 	.owner = THIS_MODULE,
546 	.name = "nvram",
547 	.flags = PSTORE_FLAGS_DMESG,
548 	.open = nvram_pstore_open,
549 	.read = nvram_pstore_read,
550 	.write = nvram_pstore_write,
551 };
552 
553 static int nvram_pstore_init(void)
554 {
555 	int rc = 0;
556 
557 	if (machine_is(pseries)) {
558 		nvram_type_ids[2] = PSTORE_TYPE_PPC_RTAS;
559 		nvram_type_ids[3] = PSTORE_TYPE_PPC_OF;
560 	} else
561 		nvram_type_ids[2] = PSTORE_TYPE_PPC_OPAL;
562 
563 	nvram_pstore_info.buf = oops_data;
564 	nvram_pstore_info.bufsize = oops_data_sz;
565 
566 	rc = pstore_register(&nvram_pstore_info);
567 	if (rc && (rc != -EPERM))
568 		/* Print error only when pstore.backend == nvram */
569 		pr_err("nvram: pstore_register() failed, returned %d. "
570 				"Defaults to kmsg_dump\n", rc);
571 
572 	return rc;
573 }
574 #else
575 static int nvram_pstore_init(void)
576 {
577 	return -1;
578 }
579 #endif
580 
581 void __init nvram_init_oops_partition(int rtas_partition_exists)
582 {
583 	int rc;
584 
585 	rc = nvram_init_os_partition(&oops_log_partition);
586 	if (rc != 0) {
587 #ifdef CONFIG_PPC_PSERIES
588 		if (!rtas_partition_exists) {
589 			pr_err("nvram: Failed to initialize oops partition!");
590 			return;
591 		}
592 		pr_notice("nvram: Using %s partition to log both"
593 			" RTAS errors and oops/panic reports\n",
594 			rtas_log_partition.name);
595 		memcpy(&oops_log_partition, &rtas_log_partition,
596 						sizeof(rtas_log_partition));
597 #else
598 		pr_err("nvram: Failed to initialize oops partition!");
599 		return;
600 #endif
601 	}
602 	oops_buf = kmalloc(oops_log_partition.size, GFP_KERNEL);
603 	if (!oops_buf) {
604 		pr_err("nvram: No memory for %s partition\n",
605 						oops_log_partition.name);
606 		return;
607 	}
608 	oops_data = oops_buf + sizeof(struct oops_log_info);
609 	oops_data_sz = oops_log_partition.size - sizeof(struct oops_log_info);
610 
611 	rc = nvram_pstore_init();
612 
613 	if (!rc)
614 		return;
615 
616 	/*
617 	 * Figure compression (preceded by elimination of each line's <n>
618 	 * severity prefix) will reduce the oops/panic report to at most
619 	 * 45% of its original size.
620 	 */
621 	big_oops_buf_sz = (oops_data_sz * 100) / 45;
622 	big_oops_buf = kmalloc(big_oops_buf_sz, GFP_KERNEL);
623 	if (big_oops_buf) {
624 		stream.workspace =  kmalloc(zlib_deflate_workspacesize(
625 					WINDOW_BITS, MEM_LEVEL), GFP_KERNEL);
626 		if (!stream.workspace) {
627 			pr_err("nvram: No memory for compression workspace; "
628 				"skipping compression of %s partition data\n",
629 				oops_log_partition.name);
630 			kfree(big_oops_buf);
631 			big_oops_buf = NULL;
632 		}
633 	} else {
634 		pr_err("No memory for uncompressed %s data; "
635 			"skipping compression\n", oops_log_partition.name);
636 		stream.workspace = NULL;
637 	}
638 
639 	rc = kmsg_dump_register(&nvram_kmsg_dumper);
640 	if (rc != 0) {
641 		pr_err("nvram: kmsg_dump_register() failed; returned %d\n", rc);
642 		kfree(oops_buf);
643 		kfree(big_oops_buf);
644 		kfree(stream.workspace);
645 	}
646 }
647 
648 /*
649  * This is our kmsg_dump callback, called after an oops or panic report
650  * has been written to the printk buffer.  We want to capture as much
651  * of the printk buffer as possible.  First, capture as much as we can
652  * that we think will compress sufficiently to fit in the lnx,oops-log
653  * partition.  If that's too much, go back and capture uncompressed text.
654  */
655 static void oops_to_nvram(struct kmsg_dumper *dumper,
656 			  enum kmsg_dump_reason reason)
657 {
658 	struct oops_log_info *oops_hdr = (struct oops_log_info *)oops_buf;
659 	static unsigned int oops_count = 0;
660 	static bool panicking = false;
661 	static DEFINE_SPINLOCK(lock);
662 	unsigned long flags;
663 	size_t text_len;
664 	unsigned int err_type = ERR_TYPE_KERNEL_PANIC_GZ;
665 	int rc = -1;
666 
667 	switch (reason) {
668 	case KMSG_DUMP_RESTART:
669 	case KMSG_DUMP_HALT:
670 	case KMSG_DUMP_POWEROFF:
671 		/* These are almost always orderly shutdowns. */
672 		return;
673 	case KMSG_DUMP_OOPS:
674 		break;
675 	case KMSG_DUMP_PANIC:
676 		panicking = true;
677 		break;
678 	case KMSG_DUMP_EMERG:
679 		if (panicking)
680 			/* Panic report already captured. */
681 			return;
682 		break;
683 	default:
684 		pr_err("%s: ignoring unrecognized KMSG_DUMP_* reason %d\n",
685 		       __func__, (int) reason);
686 		return;
687 	}
688 
689 	if (clobbering_unread_rtas_event())
690 		return;
691 
692 	if (!spin_trylock_irqsave(&lock, flags))
693 		return;
694 
695 	if (big_oops_buf) {
696 		kmsg_dump_get_buffer(dumper, false,
697 				     big_oops_buf, big_oops_buf_sz, &text_len);
698 		rc = zip_oops(text_len);
699 	}
700 	if (rc != 0) {
701 		kmsg_dump_rewind(dumper);
702 		kmsg_dump_get_buffer(dumper, false,
703 				     oops_data, oops_data_sz, &text_len);
704 		err_type = ERR_TYPE_KERNEL_PANIC;
705 		oops_hdr->version = cpu_to_be16(OOPS_HDR_VERSION);
706 		oops_hdr->report_length = cpu_to_be16(text_len);
707 		oops_hdr->timestamp = cpu_to_be64(ktime_get_real_seconds());
708 	}
709 
710 	(void) nvram_write_os_partition(&oops_log_partition, oops_buf,
711 		(int) (sizeof(*oops_hdr) + text_len), err_type,
712 		++oops_count);
713 
714 	spin_unlock_irqrestore(&lock, flags);
715 }
716 
717 static loff_t dev_nvram_llseek(struct file *file, loff_t offset, int origin)
718 {
719 	if (ppc_md.nvram_size == NULL)
720 		return -ENODEV;
721 	return generic_file_llseek_size(file, offset, origin, MAX_LFS_FILESIZE,
722 					ppc_md.nvram_size());
723 }
724 
725 
726 static ssize_t dev_nvram_read(struct file *file, char __user *buf,
727 			  size_t count, loff_t *ppos)
728 {
729 	ssize_t ret;
730 	char *tmp = NULL;
731 	ssize_t size;
732 
733 	if (!ppc_md.nvram_size) {
734 		ret = -ENODEV;
735 		goto out;
736 	}
737 
738 	size = ppc_md.nvram_size();
739 	if (size < 0) {
740 		ret = size;
741 		goto out;
742 	}
743 
744 	if (*ppos >= size) {
745 		ret = 0;
746 		goto out;
747 	}
748 
749 	count = min_t(size_t, count, size - *ppos);
750 	count = min(count, PAGE_SIZE);
751 
752 	tmp = kmalloc(count, GFP_KERNEL);
753 	if (!tmp) {
754 		ret = -ENOMEM;
755 		goto out;
756 	}
757 
758 	ret = ppc_md.nvram_read(tmp, count, ppos);
759 	if (ret <= 0)
760 		goto out;
761 
762 	if (copy_to_user(buf, tmp, ret))
763 		ret = -EFAULT;
764 
765 out:
766 	kfree(tmp);
767 	return ret;
768 
769 }
770 
771 static ssize_t dev_nvram_write(struct file *file, const char __user *buf,
772 			  size_t count, loff_t *ppos)
773 {
774 	ssize_t ret;
775 	char *tmp = NULL;
776 	ssize_t size;
777 
778 	ret = -ENODEV;
779 	if (!ppc_md.nvram_size)
780 		goto out;
781 
782 	ret = 0;
783 	size = ppc_md.nvram_size();
784 	if (*ppos >= size || size < 0)
785 		goto out;
786 
787 	count = min_t(size_t, count, size - *ppos);
788 	count = min(count, PAGE_SIZE);
789 
790 	tmp = memdup_user(buf, count);
791 	if (IS_ERR(tmp)) {
792 		ret = PTR_ERR(tmp);
793 		goto out;
794 	}
795 
796 	ret = ppc_md.nvram_write(tmp, count, ppos);
797 
798 	kfree(tmp);
799 out:
800 	return ret;
801 }
802 
803 static long dev_nvram_ioctl(struct file *file, unsigned int cmd,
804 			    unsigned long arg)
805 {
806 	switch(cmd) {
807 #ifdef CONFIG_PPC_PMAC
808 	case OBSOLETE_PMAC_NVRAM_GET_OFFSET:
809 		printk(KERN_WARNING "nvram: Using obsolete PMAC_NVRAM_GET_OFFSET ioctl\n");
810 		/* fall through */
811 	case IOC_NVRAM_GET_OFFSET: {
812 		int part, offset;
813 
814 		if (!machine_is(powermac))
815 			return -EINVAL;
816 		if (copy_from_user(&part, (void __user*)arg, sizeof(part)) != 0)
817 			return -EFAULT;
818 		if (part < pmac_nvram_OF || part > pmac_nvram_NR)
819 			return -EINVAL;
820 		offset = pmac_get_partition(part);
821 		if (offset < 0)
822 			return offset;
823 		if (copy_to_user((void __user*)arg, &offset, sizeof(offset)) != 0)
824 			return -EFAULT;
825 		return 0;
826 	}
827 #endif /* CONFIG_PPC_PMAC */
828 	default:
829 		return -EINVAL;
830 	}
831 }
832 
833 static const struct file_operations nvram_fops = {
834 	.owner		= THIS_MODULE,
835 	.llseek		= dev_nvram_llseek,
836 	.read		= dev_nvram_read,
837 	.write		= dev_nvram_write,
838 	.unlocked_ioctl	= dev_nvram_ioctl,
839 };
840 
841 static struct miscdevice nvram_dev = {
842 	NVRAM_MINOR,
843 	"nvram",
844 	&nvram_fops
845 };
846 
847 
848 #ifdef DEBUG_NVRAM
849 static void __init nvram_print_partitions(char * label)
850 {
851 	struct nvram_partition * tmp_part;
852 
853 	printk(KERN_WARNING "--------%s---------\n", label);
854 	printk(KERN_WARNING "indx\t\tsig\tchks\tlen\tname\n");
855 	list_for_each_entry(tmp_part, &nvram_partitions, partition) {
856 		printk(KERN_WARNING "%4d    \t%02x\t%02x\t%d\t%12.12s\n",
857 		       tmp_part->index, tmp_part->header.signature,
858 		       tmp_part->header.checksum, tmp_part->header.length,
859 		       tmp_part->header.name);
860 	}
861 }
862 #endif
863 
864 
865 static int __init nvram_write_header(struct nvram_partition * part)
866 {
867 	loff_t tmp_index;
868 	int rc;
869 	struct nvram_header phead;
870 
871 	memcpy(&phead, &part->header, NVRAM_HEADER_LEN);
872 	phead.length = cpu_to_be16(phead.length);
873 
874 	tmp_index = part->index;
875 	rc = ppc_md.nvram_write((char *)&phead, NVRAM_HEADER_LEN, &tmp_index);
876 
877 	return rc;
878 }
879 
880 
881 static unsigned char __init nvram_checksum(struct nvram_header *p)
882 {
883 	unsigned int c_sum, c_sum2;
884 	unsigned short *sp = (unsigned short *)p->name; /* assume 6 shorts */
885 	c_sum = p->signature + p->length + sp[0] + sp[1] + sp[2] + sp[3] + sp[4] + sp[5];
886 
887 	/* The sum may have spilled into the 3rd byte.  Fold it back. */
888 	c_sum = ((c_sum & 0xffff) + (c_sum >> 16)) & 0xffff;
889 	/* The sum cannot exceed 2 bytes.  Fold it into a checksum */
890 	c_sum2 = (c_sum >> 8) + (c_sum << 8);
891 	c_sum = ((c_sum + c_sum2) >> 8) & 0xff;
892 	return c_sum;
893 }
894 
895 /*
896  * Per the criteria passed via nvram_remove_partition(), should this
897  * partition be removed?  1=remove, 0=keep
898  */
899 static int nvram_can_remove_partition(struct nvram_partition *part,
900 		const char *name, int sig, const char *exceptions[])
901 {
902 	if (part->header.signature != sig)
903 		return 0;
904 	if (name) {
905 		if (strncmp(name, part->header.name, 12))
906 			return 0;
907 	} else if (exceptions) {
908 		const char **except;
909 		for (except = exceptions; *except; except++) {
910 			if (!strncmp(*except, part->header.name, 12))
911 				return 0;
912 		}
913 	}
914 	return 1;
915 }
916 
917 /**
918  * nvram_remove_partition - Remove one or more partitions in nvram
919  * @name: name of the partition to remove, or NULL for a
920  *        signature only match
921  * @sig: signature of the partition(s) to remove
922  * @exceptions: When removing all partitions with a matching signature,
923  *        leave these alone.
924  */
925 
926 int __init nvram_remove_partition(const char *name, int sig,
927 						const char *exceptions[])
928 {
929 	struct nvram_partition *part, *prev, *tmp;
930 	int rc;
931 
932 	list_for_each_entry(part, &nvram_partitions, partition) {
933 		if (!nvram_can_remove_partition(part, name, sig, exceptions))
934 			continue;
935 
936 		/* Make partition a free partition */
937 		part->header.signature = NVRAM_SIG_FREE;
938 		memset(part->header.name, 'w', 12);
939 		part->header.checksum = nvram_checksum(&part->header);
940 		rc = nvram_write_header(part);
941 		if (rc <= 0) {
942 			printk(KERN_ERR "nvram_remove_partition: nvram_write failed (%d)\n", rc);
943 			return rc;
944 		}
945 	}
946 
947 	/* Merge contiguous ones */
948 	prev = NULL;
949 	list_for_each_entry_safe(part, tmp, &nvram_partitions, partition) {
950 		if (part->header.signature != NVRAM_SIG_FREE) {
951 			prev = NULL;
952 			continue;
953 		}
954 		if (prev) {
955 			prev->header.length += part->header.length;
956 			prev->header.checksum = nvram_checksum(&prev->header);
957 			rc = nvram_write_header(prev);
958 			if (rc <= 0) {
959 				printk(KERN_ERR "nvram_remove_partition: nvram_write failed (%d)\n", rc);
960 				return rc;
961 			}
962 			list_del(&part->partition);
963 			kfree(part);
964 		} else
965 			prev = part;
966 	}
967 
968 	return 0;
969 }
970 
971 /**
972  * nvram_create_partition - Create a partition in nvram
973  * @name: name of the partition to create
974  * @sig: signature of the partition to create
975  * @req_size: size of data to allocate in bytes
976  * @min_size: minimum acceptable size (0 means req_size)
977  *
978  * Returns a negative error code or a positive nvram index
979  * of the beginning of the data area of the newly created
980  * partition. If you provided a min_size smaller than req_size
981  * you need to query for the actual size yourself after the
982  * call using nvram_partition_get_size().
983  */
984 loff_t __init nvram_create_partition(const char *name, int sig,
985 				     int req_size, int min_size)
986 {
987 	struct nvram_partition *part;
988 	struct nvram_partition *new_part;
989 	struct nvram_partition *free_part = NULL;
990 	static char nv_init_vals[16];
991 	loff_t tmp_index;
992 	long size = 0;
993 	int rc;
994 
995 	/* Convert sizes from bytes to blocks */
996 	req_size = _ALIGN_UP(req_size, NVRAM_BLOCK_LEN) / NVRAM_BLOCK_LEN;
997 	min_size = _ALIGN_UP(min_size, NVRAM_BLOCK_LEN) / NVRAM_BLOCK_LEN;
998 
999 	/* If no minimum size specified, make it the same as the
1000 	 * requested size
1001 	 */
1002 	if (min_size == 0)
1003 		min_size = req_size;
1004 	if (min_size > req_size)
1005 		return -EINVAL;
1006 
1007 	/* Now add one block to each for the header */
1008 	req_size += 1;
1009 	min_size += 1;
1010 
1011 	/* Find a free partition that will give us the maximum needed size
1012 	   If can't find one that will give us the minimum size needed */
1013 	list_for_each_entry(part, &nvram_partitions, partition) {
1014 		if (part->header.signature != NVRAM_SIG_FREE)
1015 			continue;
1016 
1017 		if (part->header.length >= req_size) {
1018 			size = req_size;
1019 			free_part = part;
1020 			break;
1021 		}
1022 		if (part->header.length > size &&
1023 		    part->header.length >= min_size) {
1024 			size = part->header.length;
1025 			free_part = part;
1026 		}
1027 	}
1028 	if (!size)
1029 		return -ENOSPC;
1030 
1031 	/* Create our OS partition */
1032 	new_part = kzalloc(sizeof(*new_part), GFP_KERNEL);
1033 	if (!new_part) {
1034 		pr_err("%s: kmalloc failed\n", __func__);
1035 		return -ENOMEM;
1036 	}
1037 
1038 	new_part->index = free_part->index;
1039 	new_part->header.signature = sig;
1040 	new_part->header.length = size;
1041 	memcpy(new_part->header.name, name, strnlen(name, sizeof(new_part->header.name)));
1042 	new_part->header.checksum = nvram_checksum(&new_part->header);
1043 
1044 	rc = nvram_write_header(new_part);
1045 	if (rc <= 0) {
1046 		pr_err("%s: nvram_write_header failed (%d)\n", __func__, rc);
1047 		kfree(new_part);
1048 		return rc;
1049 	}
1050 	list_add_tail(&new_part->partition, &free_part->partition);
1051 
1052 	/* Adjust or remove the partition we stole the space from */
1053 	if (free_part->header.length > size) {
1054 		free_part->index += size * NVRAM_BLOCK_LEN;
1055 		free_part->header.length -= size;
1056 		free_part->header.checksum = nvram_checksum(&free_part->header);
1057 		rc = nvram_write_header(free_part);
1058 		if (rc <= 0) {
1059 			pr_err("%s: nvram_write_header failed (%d)\n",
1060 			       __func__, rc);
1061 			return rc;
1062 		}
1063 	} else {
1064 		list_del(&free_part->partition);
1065 		kfree(free_part);
1066 	}
1067 
1068 	/* Clear the new partition */
1069 	for (tmp_index = new_part->index + NVRAM_HEADER_LEN;
1070 	     tmp_index <  ((size - 1) * NVRAM_BLOCK_LEN);
1071 	     tmp_index += NVRAM_BLOCK_LEN) {
1072 		rc = ppc_md.nvram_write(nv_init_vals, NVRAM_BLOCK_LEN, &tmp_index);
1073 		if (rc <= 0) {
1074 			pr_err("%s: nvram_write failed (%d)\n",
1075 			       __func__, rc);
1076 			return rc;
1077 		}
1078 	}
1079 
1080 	return new_part->index + NVRAM_HEADER_LEN;
1081 }
1082 
1083 /**
1084  * nvram_get_partition_size - Get the data size of an nvram partition
1085  * @data_index: This is the offset of the start of the data of
1086  *              the partition. The same value that is returned by
1087  *              nvram_create_partition().
1088  */
1089 int nvram_get_partition_size(loff_t data_index)
1090 {
1091 	struct nvram_partition *part;
1092 
1093 	list_for_each_entry(part, &nvram_partitions, partition) {
1094 		if (part->index + NVRAM_HEADER_LEN == data_index)
1095 			return (part->header.length - 1) * NVRAM_BLOCK_LEN;
1096 	}
1097 	return -1;
1098 }
1099 
1100 
1101 /**
1102  * nvram_find_partition - Find an nvram partition by signature and name
1103  * @name: Name of the partition or NULL for any name
1104  * @sig: Signature to test against
1105  * @out_size: if non-NULL, returns the size of the data part of the partition
1106  */
1107 loff_t nvram_find_partition(const char *name, int sig, int *out_size)
1108 {
1109 	struct nvram_partition *p;
1110 
1111 	list_for_each_entry(p, &nvram_partitions, partition) {
1112 		if (p->header.signature == sig &&
1113 		    (!name || !strncmp(p->header.name, name, 12))) {
1114 			if (out_size)
1115 				*out_size = (p->header.length - 1) *
1116 					NVRAM_BLOCK_LEN;
1117 			return p->index + NVRAM_HEADER_LEN;
1118 		}
1119 	}
1120 	return 0;
1121 }
1122 
1123 int __init nvram_scan_partitions(void)
1124 {
1125 	loff_t cur_index = 0;
1126 	struct nvram_header phead;
1127 	struct nvram_partition * tmp_part;
1128 	unsigned char c_sum;
1129 	char * header;
1130 	int total_size;
1131 	int err;
1132 
1133 	if (ppc_md.nvram_size == NULL || ppc_md.nvram_size() <= 0)
1134 		return -ENODEV;
1135 	total_size = ppc_md.nvram_size();
1136 
1137 	header = kmalloc(NVRAM_HEADER_LEN, GFP_KERNEL);
1138 	if (!header) {
1139 		printk(KERN_ERR "nvram_scan_partitions: Failed kmalloc\n");
1140 		return -ENOMEM;
1141 	}
1142 
1143 	while (cur_index < total_size) {
1144 
1145 		err = ppc_md.nvram_read(header, NVRAM_HEADER_LEN, &cur_index);
1146 		if (err != NVRAM_HEADER_LEN) {
1147 			printk(KERN_ERR "nvram_scan_partitions: Error parsing "
1148 			       "nvram partitions\n");
1149 			goto out;
1150 		}
1151 
1152 		cur_index -= NVRAM_HEADER_LEN; /* nvram_read will advance us */
1153 
1154 		memcpy(&phead, header, NVRAM_HEADER_LEN);
1155 
1156 		phead.length = be16_to_cpu(phead.length);
1157 
1158 		err = 0;
1159 		c_sum = nvram_checksum(&phead);
1160 		if (c_sum != phead.checksum) {
1161 			printk(KERN_WARNING "WARNING: nvram partition checksum"
1162 			       " was %02x, should be %02x!\n",
1163 			       phead.checksum, c_sum);
1164 			printk(KERN_WARNING "Terminating nvram partition scan\n");
1165 			goto out;
1166 		}
1167 		if (!phead.length) {
1168 			printk(KERN_WARNING "WARNING: nvram corruption "
1169 			       "detected: 0-length partition\n");
1170 			goto out;
1171 		}
1172 		tmp_part = kmalloc(sizeof(*tmp_part), GFP_KERNEL);
1173 		err = -ENOMEM;
1174 		if (!tmp_part) {
1175 			printk(KERN_ERR "nvram_scan_partitions: kmalloc failed\n");
1176 			goto out;
1177 		}
1178 
1179 		memcpy(&tmp_part->header, &phead, NVRAM_HEADER_LEN);
1180 		tmp_part->index = cur_index;
1181 		list_add_tail(&tmp_part->partition, &nvram_partitions);
1182 
1183 		cur_index += phead.length * NVRAM_BLOCK_LEN;
1184 	}
1185 	err = 0;
1186 
1187 #ifdef DEBUG_NVRAM
1188 	nvram_print_partitions("NVRAM Partitions");
1189 #endif
1190 
1191  out:
1192 	kfree(header);
1193 	return err;
1194 }
1195 
1196 static int __init nvram_init(void)
1197 {
1198 	int rc;
1199 
1200 	BUILD_BUG_ON(NVRAM_BLOCK_LEN != 16);
1201 
1202 	if (ppc_md.nvram_size == NULL || ppc_md.nvram_size() <= 0)
1203 		return  -ENODEV;
1204 
1205   	rc = misc_register(&nvram_dev);
1206 	if (rc != 0) {
1207 		printk(KERN_ERR "nvram_init: failed to register device\n");
1208 		return rc;
1209 	}
1210 
1211   	return rc;
1212 }
1213 device_initcall(nvram_init);
1214