GNU Linux-libre 4.19.264-gnu1
[releases.git] / arch / powerpc / kernel / nvram_64.c
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         case IOC_NVRAM_GET_OFFSET: {
811                 int part, offset;
812
813                 if (!machine_is(powermac))
814                         return -EINVAL;
815                 if (copy_from_user(&part, (void __user*)arg, sizeof(part)) != 0)
816                         return -EFAULT;
817                 if (part < pmac_nvram_OF || part > pmac_nvram_NR)
818                         return -EINVAL;
819                 offset = pmac_get_partition(part);
820                 if (offset < 0)
821                         return offset;
822                 if (copy_to_user((void __user*)arg, &offset, sizeof(offset)) != 0)
823                         return -EFAULT;
824                 return 0;
825         }
826 #endif /* CONFIG_PPC_PMAC */
827         default:
828                 return -EINVAL;
829         }
830 }
831
832 static const struct file_operations nvram_fops = {
833         .owner          = THIS_MODULE,
834         .llseek         = dev_nvram_llseek,
835         .read           = dev_nvram_read,
836         .write          = dev_nvram_write,
837         .unlocked_ioctl = dev_nvram_ioctl,
838 };
839
840 static struct miscdevice nvram_dev = {
841         NVRAM_MINOR,
842         "nvram",
843         &nvram_fops
844 };
845
846
847 #ifdef DEBUG_NVRAM
848 static void __init nvram_print_partitions(char * label)
849 {
850         struct nvram_partition * tmp_part;
851         
852         printk(KERN_WARNING "--------%s---------\n", label);
853         printk(KERN_WARNING "indx\t\tsig\tchks\tlen\tname\n");
854         list_for_each_entry(tmp_part, &nvram_partitions, partition) {
855                 printk(KERN_WARNING "%4d    \t%02x\t%02x\t%d\t%12.12s\n",
856                        tmp_part->index, tmp_part->header.signature,
857                        tmp_part->header.checksum, tmp_part->header.length,
858                        tmp_part->header.name);
859         }
860 }
861 #endif
862
863
864 static int __init nvram_write_header(struct nvram_partition * part)
865 {
866         loff_t tmp_index;
867         int rc;
868         struct nvram_header phead;
869
870         memcpy(&phead, &part->header, NVRAM_HEADER_LEN);
871         phead.length = cpu_to_be16(phead.length);
872
873         tmp_index = part->index;
874         rc = ppc_md.nvram_write((char *)&phead, NVRAM_HEADER_LEN, &tmp_index);
875
876         return rc;
877 }
878
879
880 static unsigned char __init nvram_checksum(struct nvram_header *p)
881 {
882         unsigned int c_sum, c_sum2;
883         unsigned short *sp = (unsigned short *)p->name; /* assume 6 shorts */
884         c_sum = p->signature + p->length + sp[0] + sp[1] + sp[2] + sp[3] + sp[4] + sp[5];
885
886         /* The sum may have spilled into the 3rd byte.  Fold it back. */
887         c_sum = ((c_sum & 0xffff) + (c_sum >> 16)) & 0xffff;
888         /* The sum cannot exceed 2 bytes.  Fold it into a checksum */
889         c_sum2 = (c_sum >> 8) + (c_sum << 8);
890         c_sum = ((c_sum + c_sum2) >> 8) & 0xff;
891         return c_sum;
892 }
893
894 /*
895  * Per the criteria passed via nvram_remove_partition(), should this
896  * partition be removed?  1=remove, 0=keep
897  */
898 static int nvram_can_remove_partition(struct nvram_partition *part,
899                 const char *name, int sig, const char *exceptions[])
900 {
901         if (part->header.signature != sig)
902                 return 0;
903         if (name) {
904                 if (strncmp(name, part->header.name, 12))
905                         return 0;
906         } else if (exceptions) {
907                 const char **except;
908                 for (except = exceptions; *except; except++) {
909                         if (!strncmp(*except, part->header.name, 12))
910                                 return 0;
911                 }
912         }
913         return 1;
914 }
915
916 /**
917  * nvram_remove_partition - Remove one or more partitions in nvram
918  * @name: name of the partition to remove, or NULL for a
919  *        signature only match
920  * @sig: signature of the partition(s) to remove
921  * @exceptions: When removing all partitions with a matching signature,
922  *        leave these alone.
923  */
924
925 int __init nvram_remove_partition(const char *name, int sig,
926                                                 const char *exceptions[])
927 {
928         struct nvram_partition *part, *prev, *tmp;
929         int rc;
930
931         list_for_each_entry(part, &nvram_partitions, partition) {
932                 if (!nvram_can_remove_partition(part, name, sig, exceptions))
933                         continue;
934
935                 /* Make partition a free partition */
936                 part->header.signature = NVRAM_SIG_FREE;
937                 memset(part->header.name, 'w', 12);
938                 part->header.checksum = nvram_checksum(&part->header);
939                 rc = nvram_write_header(part);
940                 if (rc <= 0) {
941                         printk(KERN_ERR "nvram_remove_partition: nvram_write failed (%d)\n", rc);
942                         return rc;
943                 }
944         }
945
946         /* Merge contiguous ones */
947         prev = NULL;
948         list_for_each_entry_safe(part, tmp, &nvram_partitions, partition) {
949                 if (part->header.signature != NVRAM_SIG_FREE) {
950                         prev = NULL;
951                         continue;
952                 }
953                 if (prev) {
954                         prev->header.length += part->header.length;
955                         prev->header.checksum = nvram_checksum(&prev->header);
956                         rc = nvram_write_header(prev);
957                         if (rc <= 0) {
958                                 printk(KERN_ERR "nvram_remove_partition: nvram_write failed (%d)\n", rc);
959                                 return rc;
960                         }
961                         list_del(&part->partition);
962                         kfree(part);
963                 } else
964                         prev = part;
965         }
966         
967         return 0;
968 }
969
970 /**
971  * nvram_create_partition - Create a partition in nvram
972  * @name: name of the partition to create
973  * @sig: signature of the partition to create
974  * @req_size: size of data to allocate in bytes
975  * @min_size: minimum acceptable size (0 means req_size)
976  *
977  * Returns a negative error code or a positive nvram index
978  * of the beginning of the data area of the newly created
979  * partition. If you provided a min_size smaller than req_size
980  * you need to query for the actual size yourself after the
981  * call using nvram_partition_get_size().
982  */
983 loff_t __init nvram_create_partition(const char *name, int sig,
984                                      int req_size, int min_size)
985 {
986         struct nvram_partition *part;
987         struct nvram_partition *new_part;
988         struct nvram_partition *free_part = NULL;
989         static char nv_init_vals[16];
990         loff_t tmp_index;
991         long size = 0;
992         int rc;
993
994         /* Convert sizes from bytes to blocks */
995         req_size = _ALIGN_UP(req_size, NVRAM_BLOCK_LEN) / NVRAM_BLOCK_LEN;
996         min_size = _ALIGN_UP(min_size, NVRAM_BLOCK_LEN) / NVRAM_BLOCK_LEN;
997
998         /* If no minimum size specified, make it the same as the
999          * requested size
1000          */
1001         if (min_size == 0)
1002                 min_size = req_size;
1003         if (min_size > req_size)
1004                 return -EINVAL;
1005
1006         /* Now add one block to each for the header */
1007         req_size += 1;
1008         min_size += 1;
1009
1010         /* Find a free partition that will give us the maximum needed size 
1011            If can't find one that will give us the minimum size needed */
1012         list_for_each_entry(part, &nvram_partitions, partition) {
1013                 if (part->header.signature != NVRAM_SIG_FREE)
1014                         continue;
1015
1016                 if (part->header.length >= req_size) {
1017                         size = req_size;
1018                         free_part = part;
1019                         break;
1020                 }
1021                 if (part->header.length > size &&
1022                     part->header.length >= min_size) {
1023                         size = part->header.length;
1024                         free_part = part;
1025                 }
1026         }
1027         if (!size)
1028                 return -ENOSPC;
1029         
1030         /* Create our OS partition */
1031         new_part = kzalloc(sizeof(*new_part), GFP_KERNEL);
1032         if (!new_part) {
1033                 pr_err("%s: kmalloc failed\n", __func__);
1034                 return -ENOMEM;
1035         }
1036
1037         new_part->index = free_part->index;
1038         new_part->header.signature = sig;
1039         new_part->header.length = size;
1040         memcpy(new_part->header.name, name, strnlen(name, sizeof(new_part->header.name)));
1041         new_part->header.checksum = nvram_checksum(&new_part->header);
1042
1043         rc = nvram_write_header(new_part);
1044         if (rc <= 0) {
1045                 pr_err("%s: nvram_write_header failed (%d)\n", __func__, rc);
1046                 kfree(new_part);
1047                 return rc;
1048         }
1049         list_add_tail(&new_part->partition, &free_part->partition);
1050
1051         /* Adjust or remove the partition we stole the space from */
1052         if (free_part->header.length > size) {
1053                 free_part->index += size * NVRAM_BLOCK_LEN;
1054                 free_part->header.length -= size;
1055                 free_part->header.checksum = nvram_checksum(&free_part->header);
1056                 rc = nvram_write_header(free_part);
1057                 if (rc <= 0) {
1058                         pr_err("%s: nvram_write_header failed (%d)\n",
1059                                __func__, rc);
1060                         return rc;
1061                 }
1062         } else {
1063                 list_del(&free_part->partition);
1064                 kfree(free_part);
1065         } 
1066
1067         /* Clear the new partition */
1068         for (tmp_index = new_part->index + NVRAM_HEADER_LEN;
1069              tmp_index <  ((size - 1) * NVRAM_BLOCK_LEN);
1070              tmp_index += NVRAM_BLOCK_LEN) {
1071                 rc = ppc_md.nvram_write(nv_init_vals, NVRAM_BLOCK_LEN, &tmp_index);
1072                 if (rc <= 0) {
1073                         pr_err("%s: nvram_write failed (%d)\n",
1074                                __func__, rc);
1075                         return rc;
1076                 }
1077         }
1078
1079         return new_part->index + NVRAM_HEADER_LEN;
1080 }
1081
1082 /**
1083  * nvram_get_partition_size - Get the data size of an nvram partition
1084  * @data_index: This is the offset of the start of the data of
1085  *              the partition. The same value that is returned by
1086  *              nvram_create_partition().
1087  */
1088 int nvram_get_partition_size(loff_t data_index)
1089 {
1090         struct nvram_partition *part;
1091         
1092         list_for_each_entry(part, &nvram_partitions, partition) {
1093                 if (part->index + NVRAM_HEADER_LEN == data_index)
1094                         return (part->header.length - 1) * NVRAM_BLOCK_LEN;
1095         }
1096         return -1;
1097 }
1098
1099
1100 /**
1101  * nvram_find_partition - Find an nvram partition by signature and name
1102  * @name: Name of the partition or NULL for any name
1103  * @sig: Signature to test against
1104  * @out_size: if non-NULL, returns the size of the data part of the partition
1105  */
1106 loff_t nvram_find_partition(const char *name, int sig, int *out_size)
1107 {
1108         struct nvram_partition *p;
1109
1110         list_for_each_entry(p, &nvram_partitions, partition) {
1111                 if (p->header.signature == sig &&
1112                     (!name || !strncmp(p->header.name, name, 12))) {
1113                         if (out_size)
1114                                 *out_size = (p->header.length - 1) *
1115                                         NVRAM_BLOCK_LEN;
1116                         return p->index + NVRAM_HEADER_LEN;
1117                 }
1118         }
1119         return 0;
1120 }
1121
1122 int __init nvram_scan_partitions(void)
1123 {
1124         loff_t cur_index = 0;
1125         struct nvram_header phead;
1126         struct nvram_partition * tmp_part;
1127         unsigned char c_sum;
1128         char * header;
1129         int total_size;
1130         int err;
1131
1132         if (ppc_md.nvram_size == NULL || ppc_md.nvram_size() <= 0)
1133                 return -ENODEV;
1134         total_size = ppc_md.nvram_size();
1135         
1136         header = kmalloc(NVRAM_HEADER_LEN, GFP_KERNEL);
1137         if (!header) {
1138                 printk(KERN_ERR "nvram_scan_partitions: Failed kmalloc\n");
1139                 return -ENOMEM;
1140         }
1141
1142         while (cur_index < total_size) {
1143
1144                 err = ppc_md.nvram_read(header, NVRAM_HEADER_LEN, &cur_index);
1145                 if (err != NVRAM_HEADER_LEN) {
1146                         printk(KERN_ERR "nvram_scan_partitions: Error parsing "
1147                                "nvram partitions\n");
1148                         goto out;
1149                 }
1150
1151                 cur_index -= NVRAM_HEADER_LEN; /* nvram_read will advance us */
1152
1153                 memcpy(&phead, header, NVRAM_HEADER_LEN);
1154
1155                 phead.length = be16_to_cpu(phead.length);
1156
1157                 err = 0;
1158                 c_sum = nvram_checksum(&phead);
1159                 if (c_sum != phead.checksum) {
1160                         printk(KERN_WARNING "WARNING: nvram partition checksum"
1161                                " was %02x, should be %02x!\n",
1162                                phead.checksum, c_sum);
1163                         printk(KERN_WARNING "Terminating nvram partition scan\n");
1164                         goto out;
1165                 }
1166                 if (!phead.length) {
1167                         printk(KERN_WARNING "WARNING: nvram corruption "
1168                                "detected: 0-length partition\n");
1169                         goto out;
1170                 }
1171                 tmp_part = kmalloc(sizeof(*tmp_part), GFP_KERNEL);
1172                 err = -ENOMEM;
1173                 if (!tmp_part) {
1174                         printk(KERN_ERR "nvram_scan_partitions: kmalloc failed\n");
1175                         goto out;
1176                 }
1177                 
1178                 memcpy(&tmp_part->header, &phead, NVRAM_HEADER_LEN);
1179                 tmp_part->index = cur_index;
1180                 list_add_tail(&tmp_part->partition, &nvram_partitions);
1181                 
1182                 cur_index += phead.length * NVRAM_BLOCK_LEN;
1183         }
1184         err = 0;
1185
1186 #ifdef DEBUG_NVRAM
1187         nvram_print_partitions("NVRAM Partitions");
1188 #endif
1189
1190  out:
1191         kfree(header);
1192         return err;
1193 }
1194
1195 static int __init nvram_init(void)
1196 {
1197         int rc;
1198         
1199         BUILD_BUG_ON(NVRAM_BLOCK_LEN != 16);
1200
1201         if (ppc_md.nvram_size == NULL || ppc_md.nvram_size() <= 0)
1202                 return  -ENODEV;
1203
1204         rc = misc_register(&nvram_dev);
1205         if (rc != 0) {
1206                 printk(KERN_ERR "nvram_init: failed to register device\n");
1207                 return rc;
1208         }
1209         
1210         return rc;
1211 }
1212 device_initcall(nvram_init);