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