logger: Fix incorrect buffer access when writing data
[platform/kernel/linux-rpi.git] / drivers / staging / android / logger.c
1 /*
2  * drivers/misc/logger.c
3  *
4  * A Logging Subsystem
5  *
6  * Copyright (C) 2007-2008 Google, Inc.
7  *
8  * Robert Love <rlove@google.com>
9  *
10  * This software is licensed under the terms of the GNU General Public
11  * License version 2, as published by the Free Software Foundation, and
12  * may be copied, distributed, and modified under those terms.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  */
19
20 #define pr_fmt(fmt) "logger: " fmt
21
22 #include <linux/sched/signal.h>
23 #include <linux/module.h>
24 #include <linux/fs.h>
25 #include <linux/miscdevice.h>
26 #include <linux/uaccess.h>
27 #include <linux/poll.h>
28 #include <linux/slab.h>
29 #include <linux/time.h>
30 #include <linux/vmalloc.h>
31 #include <linux/uio.h>
32 #include <linux/fdtable.h>
33 #include <linux/file.h>
34
35 #include "logger.h"
36
37 /**
38  * struct logger_log - represents a specific log, such as 'main' or 'radio'
39  * @buffer:     The actual ring buffer
40  * @misc:       The "misc" device representing the log
41  * @wq:         The wait queue for @readers
42  * @readers:    This log's readers
43  * @mutex:      The mutex that protects the @buffer
44  * @w_off:      The current write head offset
45  * @head:       The head, or location that readers start reading at.
46  * @size:       The size of the log
47  * @logs:       The list of log channels
48  *
49  * This structure lives from module insertion until module removal, so it does
50  * not need additional reference counting. The structure is protected by the
51  * mutex 'mutex'.
52  */
53 struct logger_log {
54         unsigned char           *buffer;
55         struct miscdevice       misc;
56         wait_queue_head_t       wq;
57         struct list_head        readers;
58         struct mutex            mutex;
59         size_t                  w_off;
60         size_t                  head;
61         size_t                  size;
62         struct list_head        logs;
63 };
64
65 static LIST_HEAD(log_list);
66
67 /**
68  * struct log_writer - a logging device open for writing
69  * @log:        The associated log
70  * @list:       The associated entry in @logger_log's list
71  * @b_off:      The current position in @buf
72  * @tag:        A tag to be attached to messages
73  * @prio:       Default message priority value
74  * @buff:       Temporary space to assemble messages.
75  */
76 struct logger_writer {
77         struct logger_log       *log;
78         struct task_struct      *owner;
79         struct task_struct      *b_owner;
80         struct logger_entry     b_header;
81         size_t                  b_off;
82         size_t                  tag_len;
83         char                    *tag;
84         int                     prio;
85         char                    *buffer;
86 };
87
88 /**
89  * struct logger_reader - a logging device open for reading
90  * @log:        The associated log
91  * @list:       The associated entry in @logger_log's list
92  * @r_off:      The current read head offset.
93  * @r_all:      Reader can read all entries
94  * @r_ver:      Reader ABI version
95  *
96  * This object lives from open to release, so we don't need additional
97  * reference counting. The structure is protected by log->mutex.
98  */
99 struct logger_reader {
100         struct logger_log       *log;
101         struct list_head        list;
102         size_t                  r_off;
103         bool                    r_all;
104         int                     r_ver;
105 };
106
107 /* logger_offset - returns index 'n' into the log via (optimized) modulus */
108 static size_t logger_offset(struct logger_log *log, size_t n)
109 {
110         return n & (log->size - 1);
111 }
112
113 /*
114  * file_get_log - Given a file structure, return the associated log
115  *
116  * This isn't aesthetic. We have several goals:
117  *
118  *      1) Need to quickly obtain the associated log during an I/O operation
119  *      2) Readers need to maintain state (logger_reader)
120  *      3) Writers need to be very fast (open() should be a near no-op)
121  *
122  * In the reader case, we can trivially go file->logger_reader->logger_log.
123  * For a writer, we don't want to maintain a logger_reader, so we just go
124  * file->logger_log. Thus what file->private_data points at depends on whether
125  * or not the file was opened for reading. This function hides that dirtiness.
126  */
127 static inline struct logger_log *file_get_log(struct file *file)
128 {
129         struct logger_writer *writer = file->private_data;
130
131         if (file->f_mode & FMODE_READ) {
132                 struct logger_reader *reader = file->private_data;
133
134                 return reader->log;
135         }
136
137         return writer->log;
138 }
139
140 /*
141  * get_entry_header - returns a pointer to the logger_entry header within
142  * 'log' starting at offset 'off'. A temporary logger_entry 'scratch' must
143  * be provided. Typically the return value will be a pointer within
144  * 'logger->buf'.  However, a pointer to 'scratch' may be returned if
145  * the log entry spans the end and beginning of the circular buffer.
146  */
147 static struct logger_entry *get_entry_header(struct logger_log *log,
148                                              size_t off,
149                                              struct logger_entry *scratch)
150 {
151         size_t len = min(sizeof(struct logger_entry), log->size - off);
152
153         if (len != sizeof(struct logger_entry)) {
154                 memcpy(((void *)scratch), log->buffer + off, len);
155                 memcpy(((void *)scratch) + len, log->buffer,
156                        sizeof(struct logger_entry) - len);
157                 return scratch;
158         }
159
160         return (struct logger_entry *) (log->buffer + off);
161 }
162
163 /*
164  * get_entry_msg_len - Grabs the length of the message of the entry
165  * starting from from 'off'.
166  *
167  * An entry length is 2 bytes (16 bits) in host endian order.
168  * In the log, the length does not include the size of the log entry structure.
169  * This function returns the size including the log entry structure.
170  *
171  * Caller needs to hold log->mutex.
172  */
173 static __u32 get_entry_msg_len(struct logger_log *log, size_t off)
174 {
175         struct logger_entry scratch;
176         struct logger_entry *entry;
177
178         entry = get_entry_header(log, off, &scratch);
179         return entry->len;
180 }
181
182 static size_t get_user_hdr_len(int ver)
183 {
184         if (ver < 2)
185                 return sizeof(struct user_logger_entry_compat);
186         return sizeof(struct logger_entry);
187 }
188
189 static ssize_t copy_header_to_user(int ver, struct logger_entry *entry,
190                                    char __user *buf)
191 {
192         void *hdr;
193         size_t hdr_len;
194         struct user_logger_entry_compat v1;
195
196         if (ver < 2) {
197                 v1.len      = entry->len;
198                 v1.__pad    = 0;
199                 v1.pid      = entry->pid;
200                 v1.tid      = entry->tid;
201                 v1.sec      = entry->sec;
202                 v1.nsec     = entry->nsec;
203                 hdr         = &v1;
204                 hdr_len     = sizeof(struct user_logger_entry_compat);
205         } else {
206                 hdr         = entry;
207                 hdr_len     = sizeof(struct logger_entry);
208         }
209
210         return copy_to_user(buf, hdr, hdr_len);
211 }
212
213 /*
214  * do_read_log_to_user - reads exactly 'count' bytes from 'log' into the
215  * user-space buffer 'buf'. Returns 'count' on success.
216  *
217  * Caller must hold log->mutex.
218  */
219 static ssize_t do_read_log_to_user(struct logger_log *log,
220                                    struct logger_reader *reader,
221                                    char __user *buf,
222                                    size_t count)
223 {
224         struct logger_entry scratch;
225         struct logger_entry *entry;
226         size_t len;
227         size_t msg_start;
228
229         /*
230          * First, copy the header to userspace, using the version of
231          * the header requested
232          */
233         entry = get_entry_header(log, reader->r_off, &scratch);
234         if (copy_header_to_user(reader->r_ver, entry, buf))
235                 return -EFAULT;
236
237         count -= get_user_hdr_len(reader->r_ver);
238         buf += get_user_hdr_len(reader->r_ver);
239         msg_start = logger_offset(log,
240                                   reader->r_off + sizeof(struct logger_entry));
241
242         /*
243          * We read from the msg in two disjoint operations. First, we read from
244          * the current msg head offset up to 'count' bytes or to the end of
245          * the log, whichever comes first.
246          */
247         len = min(count, log->size - msg_start);
248         if (copy_to_user(buf, log->buffer + msg_start, len))
249                 return -EFAULT;
250
251         /*
252          * Second, we read any remaining bytes, starting back at the head of
253          * the log.
254          */
255         if (count != len)
256                 if (copy_to_user(buf + len, log->buffer, count - len))
257                         return -EFAULT;
258
259         reader->r_off = logger_offset(log, reader->r_off +
260                 sizeof(struct logger_entry) + count);
261
262         return count + get_user_hdr_len(reader->r_ver);
263 }
264
265 /*
266  * get_next_entry_by_uid - Starting at 'off', returns an offset into
267  * 'log->buffer' which contains the first entry readable by 'euid'
268  */
269 static size_t get_next_entry_by_uid(struct logger_log *log,
270                                     size_t off, kuid_t euid)
271 {
272         while (off != log->w_off) {
273                 struct logger_entry *entry;
274                 struct logger_entry scratch;
275                 size_t next_len;
276
277                 entry = get_entry_header(log, off, &scratch);
278
279                 if (uid_eq(entry->euid, euid))
280                         return off;
281
282                 next_len = sizeof(struct logger_entry) + entry->len;
283                 off = logger_offset(log, off + next_len);
284         }
285
286         return off;
287 }
288
289 /*
290  * logger_read - our log's read() method
291  *
292  * Behavior:
293  *
294  *      - O_NONBLOCK works
295  *      - If there are no log entries to read, blocks until log is written to
296  *      - Atomically reads exactly one log entry
297  *
298  * Will set errno to EINVAL if read
299  * buffer is insufficient to hold next entry.
300  */
301 static ssize_t logger_read(struct file *file, char __user *buf,
302                            size_t count, loff_t *pos)
303 {
304         struct logger_reader *reader = file->private_data;
305         struct logger_log *log = reader->log;
306         ssize_t ret;
307         DEFINE_WAIT(wait);
308
309 start:
310         while (1) {
311                 mutex_lock(&log->mutex);
312
313                 prepare_to_wait(&log->wq, &wait, TASK_INTERRUPTIBLE);
314
315                 ret = (log->w_off == reader->r_off);
316                 mutex_unlock(&log->mutex);
317                 if (!ret)
318                         break;
319
320                 if (file->f_flags & O_NONBLOCK) {
321                         ret = -EAGAIN;
322                         break;
323                 }
324
325                 if (signal_pending(current)) {
326                         ret = -EINTR;
327                         break;
328                 }
329
330                 schedule();
331         }
332
333         finish_wait(&log->wq, &wait);
334         if (ret)
335                 return ret;
336
337         mutex_lock(&log->mutex);
338
339         if (!reader->r_all)
340                 reader->r_off = get_next_entry_by_uid(log,
341                         reader->r_off, current_euid());
342
343         /* is there still something to read or did we race? */
344         if (unlikely(log->w_off == reader->r_off)) {
345                 mutex_unlock(&log->mutex);
346                 goto start;
347         }
348
349         /* get the size of the next entry */
350         ret = get_user_hdr_len(reader->r_ver) +
351                 get_entry_msg_len(log, reader->r_off);
352         if (count < ret) {
353                 ret = -EINVAL;
354                 goto out;
355         }
356
357         /* get exactly one entry from the log */
358         ret = do_read_log_to_user(log, reader, buf, ret);
359
360 out:
361         mutex_unlock(&log->mutex);
362
363         return ret;
364 }
365
366 /*
367  * get_next_entry - return the offset of the first valid entry at least 'len'
368  * bytes after 'off'.
369  *
370  * Caller must hold log->mutex.
371  */
372 static size_t get_next_entry(struct logger_log *log, size_t off, size_t len)
373 {
374         size_t count = 0;
375
376         do {
377                 size_t nr = sizeof(struct logger_entry) +
378                         get_entry_msg_len(log, off);
379                 off = logger_offset(log, off + nr);
380                 count += nr;
381         } while (count < len);
382
383         return off;
384 }
385
386 /*
387  * is_between - is a < c < b, accounting for wrapping of a, b, and c
388  *    positions in the buffer
389  *
390  * That is, if a<b, check for c between a and b
391  * and if a>b, check for c outside (not between) a and b
392  *
393  * |------- a xxxxxxxx b --------|
394  *               c^
395  *
396  * |xxxxx b --------- a xxxxxxxxx|
397  *    c^
398  *  or                    c^
399  */
400 static inline int is_between(size_t a, size_t b, size_t c)
401 {
402         if (a < b) {
403                 /* is c between a and b? */
404                 if (a < c && c <= b)
405                         return 1;
406         } else {
407                 /* is c outside of b through a? */
408                 if (c <= b || a < c)
409                         return 1;
410         }
411
412         return 0;
413 }
414
415 /*
416  * fix_up_readers - walk the list of all readers and "fix up" any who were
417  * lapped by the writer; also do the same for the default "start head".
418  * We do this by "pulling forward" the readers and start head to the first
419  * entry after the new write head.
420  *
421  * The caller needs to hold log->mutex.
422  */
423 static void fix_up_readers(struct logger_log *log, size_t len)
424 {
425         size_t old = log->w_off;
426         size_t new = logger_offset(log, old + len);
427         struct logger_reader *reader;
428
429         if (is_between(old, new, log->head))
430                 log->head = get_next_entry(log, log->head, len);
431
432         list_for_each_entry(reader, &log->readers, list)
433                 if (is_between(old, new, reader->r_off))
434                         reader->r_off = get_next_entry(log, reader->r_off, len);
435 }
436
437 static char *strnrchr(const char *s, size_t count, int c)
438 {
439         const char *last = NULL;
440         if (!count)
441                 return NULL;
442         do {
443                 if (*s == (char)c)
444                         last = s;
445         } while (--count && *s++);
446         return (char *)last;
447 }
448
449 static struct file *replace_file(struct files_struct *files,
450                                  struct file *oldf,
451                                  struct file *newf)
452 {
453         struct file *file = NULL;
454         struct fdtable *fdt;
455         unsigned int i;
456
457         spin_lock(&files->file_lock);
458         fdt = files_fdtable(files);
459         for (i = 0; i < fdt->max_fds && file != oldf; i++) {
460                 if (fdt->fd[i] == oldf) {
461                         file = xchg(&fdt->fd[i], newf);
462                 }
463         }
464         spin_unlock(&files->file_lock);
465
466         if (file)
467                 filp_close(file, files);
468
469         return file;
470 }
471
472 static struct file *make_new_file(struct file *file)
473 {
474         struct logger_writer *writer = file->private_data;
475         struct logger_writer *nwriter;
476         struct file *nfile;
477         char *pbuf, *p;
478
479         pbuf = kzalloc(PATH_MAX, GFP_KERNEL);
480         if (!pbuf) {
481                 return ERR_PTR(-ENOMEM);
482         }
483
484         p = file_path(file, pbuf, PATH_MAX);
485         if (!p) {
486                 kfree(pbuf);
487                 return ERR_PTR(-EFAULT);
488         }
489
490         nfile = filp_open(p, O_WRONLY, 0);
491         kfree(pbuf);
492         if (!nfile) {
493                 return ERR_PTR(-EFAULT);
494         }
495
496         nwriter = nfile->private_data;
497         nwriter->prio = writer->prio;
498         nwriter->tag = kstrdup(writer->tag, GFP_KERNEL);
499         nwriter->tag_len = writer->tag_len;
500
501         if (!replace_file(current->files, file, nfile)) {
502                 filp_close(nfile, current->files);
503                 return ERR_PTR(-EFAULT);
504         }
505
506         return nfile;
507 }
508
509 static void write_log_data(struct logger_log *log,
510                            struct logger_entry *header,
511                            struct logger_writer *writer,
512                            size_t chunk_len)
513 {
514         size_t len, w_off;
515
516         /* header */
517         len = min(sizeof(struct logger_entry), log->size - log->w_off);
518         memcpy(log->buffer + log->w_off, header, len);
519         memcpy(log->buffer, (char *)header + len, sizeof(struct logger_entry) - len);
520         w_off =  logger_offset(log, log->w_off + sizeof(struct logger_entry));
521
522         /* priority */
523         log->buffer[w_off] = (unsigned char)writer->prio;
524         w_off = logger_offset(log, w_off + 1);
525
526         /* tag */
527         len = min_t(size_t, writer->tag_len + 1, log->size - w_off);
528         memcpy(log->buffer + w_off, writer->tag, len);
529         memcpy(log->buffer, writer->tag + len, writer->tag_len + 1 - len);
530         w_off = logger_offset(log, w_off + writer->tag_len + 1);
531
532         /* message */
533         len = min(chunk_len, log->size - w_off);
534         memcpy(log->buffer + w_off, writer->buffer, len);
535         memcpy(log->buffer, writer->buffer + len, chunk_len - len);
536         log->w_off = logger_offset(log, w_off + chunk_len);
537 }
538
539 static void flush_thread_data(struct file* file)
540 {
541         struct logger_writer *writer = file->private_data;
542         struct logger_log *log = file_get_log(file);
543         size_t chunk_len = 0;
544
545         chunk_len = writer->b_off + 1;
546         writer->b_header.len = chunk_len + writer->tag_len + 2;
547
548         fix_up_readers(log, sizeof(struct logger_entry) + writer->b_header.len);
549
550         write_log_data(log, &writer->b_header, writer, chunk_len);
551
552         writer->b_off = 0;
553         writer->buffer[0] = '\0';
554 }
555
556 /*
557  * logger_write_iter - our write method, implementing support for write(),
558  * writev(), and aio_write(). Writes are our fast path, and we try to optimize
559  * them above all else.
560  */
561 static ssize_t logger_write_iter(struct kiocb *iocb, struct iov_iter *from)
562 {
563         struct file *file = iocb->ki_filp;
564         struct logger_writer *writer = file->private_data;
565         struct logger_log *log = file_get_log(file);
566         struct logger_entry header;
567         struct timespec64 now;
568         size_t len, count, w_off;
569         bool from_stdio = false;
570
571         if (writer->tag && writer->prio >= 2)
572                 from_stdio = true;
573
574         count = min_t(size_t, iov_iter_count(from), LOGGER_ENTRY_MAX_PAYLOAD);
575
576         ktime_get_ts64(&now);
577
578         header.pid = current->tgid;
579         header.tid = current->pid;
580         header.sec = now.tv_sec;
581         header.nsec = now.tv_nsec;
582         header.euid = current_euid();
583         header.len = count;
584         header.hdr_size = sizeof(struct logger_entry);
585
586         /* null writes succeed, return zero */
587         if (unlikely(!header.len))
588                 return 0;
589
590         mutex_lock(&log->mutex);
591
592         /* Prepend messages from STDOUT and STDERR with a tag and prio */
593         if (from_stdio) {
594                 char *p;
595                 size_t chunk_len = 0;
596                 size_t max_payload = LOGGER_ENTRY_MAX_PAYLOAD - writer->tag_len - 2;
597
598                 if (writer->owner != current->group_leader) {
599                         struct file *nfile;
600
601                         nfile = make_new_file(file);
602                         if (IS_ERR(nfile)) {
603                                 mutex_unlock(&log->mutex);
604                                 return PTR_ERR(nfile);
605                         }
606
607                         file = nfile;
608                         writer = file->private_data;
609                 }
610
611                 /* Allocate STDIO line buffer */
612                 if (!writer->buffer) {
613                         writer->buffer = kzalloc(LOGGER_ENTRY_MAX_PAYLOAD, GFP_KERNEL);
614                         writer->b_off = 0;
615
616                         if (!writer->buffer) {
617                                 mutex_unlock(&log->mutex);
618                                 return -ENOMEM;
619                         }
620                 }
621
622                 /* flush message from a different thread */
623                 if (writer->b_owner != current && writer->b_off)
624                         flush_thread_data(file);
625
626                 count = min_t(size_t, iov_iter_count(from), max_payload - 1);
627
628                 do {
629
630                         if (copy_from_iter(writer->buffer + writer->b_off, count, from) != count) {
631                                 mutex_unlock(&log->mutex);
632                                 return -EFAULT;
633                         }
634
635                         /* TODO: replace NULL characters with new lines */
636                         p = strnrchr(writer->buffer + writer->b_off, count, '\n');
637                         if (p) {
638                                 *p++ = '\0';
639                                 chunk_len = p - writer->buffer;
640                         } else {
641                                 writer->buffer[count++] = '\0';
642                                 chunk_len = count;
643                         }
644
645                         header.len = chunk_len + writer->tag_len + 2;
646                         fix_up_readers(log, sizeof(struct logger_entry) + header.len);
647
648                         write_log_data(log, &header, writer, chunk_len);
649
650                         /* move the remaining part of the message */
651                         memmove(writer->buffer, p, writer->b_off + count - chunk_len);
652
653                         /* new b_off points where the rimainder of the string ends */
654                         writer->b_off = writer->b_off + count - chunk_len;
655                         writer->buffer[writer->b_off] = '\0';
656
657                 } while ((count = min_t(size_t, iov_iter_count(from), max_payload - 1)));
658
659                 /* save for remaining unfinished line */
660                 writer->b_header = header;
661                 writer->b_owner = current;
662         } else {
663
664                 /*
665                  * Fix up any readers, pulling them forward to the first readable
666                  * entry after (what will be) the new write offset. We do this now
667                  * because if we partially fail, we can end up with clobbered log
668                  * entries that encroach on readable buffer.
669                  */
670                 fix_up_readers(log, sizeof(struct logger_entry) + header.len);
671
672                 len = min(sizeof(header), log->size - log->w_off);
673                 memcpy(log->buffer + log->w_off, &header, len);
674                 memcpy(log->buffer, (char *)&header + len, sizeof(header) - len);
675
676                 /* Work with a copy until we are ready to commit the whole entry */
677                 w_off =  logger_offset(log, log->w_off + sizeof(struct logger_entry));
678
679                 len = min(count, log->size - w_off);
680
681                 if (copy_from_iter(log->buffer + w_off, len, from) != len) {
682                         /*
683                          * Note that by not updating log->w_off, this abandons the
684                          * portion of the new entry that *was* successfully
685                          * copied, just above.  This is intentional to avoid
686                          * message corruption from missing fragments.
687                          */
688                         mutex_unlock(&log->mutex);
689                         return -EFAULT;
690                 }
691
692                 if (copy_from_iter(log->buffer, count - len, from) != count - len) {
693                         mutex_unlock(&log->mutex);
694                         return -EFAULT;
695                 }
696
697                 log->w_off = logger_offset(log, w_off + count);
698         }
699
700         mutex_unlock(&log->mutex);
701
702         /* wake up any blocked readers */
703         wake_up_interruptible(&log->wq);
704
705         return count;
706 }
707
708 static struct logger_log *get_log_from_minor(int minor)
709 {
710         struct logger_log *log;
711
712         list_for_each_entry(log, &log_list, logs)
713                 if (log->misc.minor == minor)
714                         return log;
715         return NULL;
716 }
717
718 /*
719  * logger_open - the log's open() file operation
720  *
721  * Note how near a no-op this is in the write-only case. Keep it that way!
722  */
723 static int logger_open(struct inode *inode, struct file *file)
724 {
725         struct logger_log *log;
726         int ret;
727
728         ret = nonseekable_open(inode, file);
729         if (ret)
730                 return ret;
731
732         log = get_log_from_minor(MINOR(inode->i_rdev));
733         if (!log)
734                 return -ENODEV;
735
736         if (file->f_mode & FMODE_READ) {
737                 struct logger_reader *reader;
738
739                 reader = kmalloc(sizeof(struct logger_reader), GFP_KERNEL);
740                 if (!reader)
741                         return -ENOMEM;
742
743                 reader->log = log;
744                 reader->r_ver = 1;
745                 reader->r_all = in_egroup_p(inode->i_gid) ||
746                         capable(CAP_SYSLOG);
747
748                 INIT_LIST_HEAD(&reader->list);
749
750                 mutex_lock(&log->mutex);
751                 reader->r_off = log->head;
752                 list_add_tail(&reader->list, &log->readers);
753                 mutex_unlock(&log->mutex);
754
755                 file->private_data = reader;
756         } else {
757                 struct logger_writer *writer;
758
759                 writer = kzalloc(sizeof(struct logger_writer), GFP_KERNEL);
760                 if (!writer)
761                         return -ENOMEM;
762
763                 writer->log = log;
764                 writer->owner = current->group_leader;
765
766                 file->private_data = writer;
767         }
768
769         return 0;
770 }
771
772 /*
773  * logger_release - the log's release file operation
774  *
775  * Note this is a total no-op in the write-only case. Keep it that way!
776  */
777 static int logger_release(struct inode *ignored, struct file *file)
778 {
779         if (file->f_mode & FMODE_READ) {
780                 struct logger_reader *reader = file->private_data;
781                 struct logger_log *log = reader->log;
782
783                 mutex_lock(&log->mutex);
784                 list_del(&reader->list);
785                 mutex_unlock(&log->mutex);
786
787                 kfree(reader);
788         } else {
789                 struct logger_writer *writer = file->private_data;
790
791                 kfree(writer->tag);
792                 kfree(writer->buffer);
793                 kfree(writer);
794         }
795
796         return 0;
797 }
798
799 /*
800  * logger_poll - the log's poll file operation, for poll/select/epoll
801  *
802  * Note we always return POLLOUT, because you can always write() to the log.
803  * Note also that, strictly speaking, a return value of POLLIN does not
804  * guarantee that the log is readable without blocking, as there is a small
805  * chance that the writer can lap the reader in the interim between poll()
806  * returning and the read() request.
807  */
808 static unsigned int logger_poll(struct file *file, poll_table *wait)
809 {
810         struct logger_reader *reader;
811         struct logger_log *log;
812         unsigned int ret = POLLOUT | POLLWRNORM;
813
814         if (!(file->f_mode & FMODE_READ))
815                 return ret;
816
817         reader = file->private_data;
818         log = reader->log;
819
820         poll_wait(file, &log->wq, wait);
821
822         mutex_lock(&log->mutex);
823         if (!reader->r_all)
824                 reader->r_off = get_next_entry_by_uid(log,
825                         reader->r_off, current_euid());
826
827         if (log->w_off != reader->r_off)
828                 ret |= POLLIN | POLLRDNORM;
829         mutex_unlock(&log->mutex);
830
831         return ret;
832 }
833
834 static long logger_set_version(struct logger_reader *reader, void __user *arg)
835 {
836         int version;
837
838         if (copy_from_user(&version, arg, sizeof(int)))
839                 return -EFAULT;
840
841         if ((version < 1) || (version > 2))
842                 return -EINVAL;
843
844         reader->r_ver = version;
845         return 0;
846 }
847
848 static long logger_set_prio(struct logger_writer *writer, void __user *arg)
849 {
850         int prio;
851
852         prio = (int)(uintptr_t)arg;
853
854         if ((prio < 2) || (prio > 7))
855                 return -EINVAL;
856
857         writer->prio = prio;
858         return 0;
859 }
860
861 static long logger_set_tag(struct logger_writer *writer, void __user *arg)
862 {
863         int len;
864         char *p, *q;
865
866         if (copy_from_user(&len, arg, sizeof(int)))
867                 return -EFAULT;
868
869         arg += sizeof(int);
870
871
872         p = kzalloc(len, GFP_KERNEL);
873         if (!p)
874                 return -ENOMEM;
875
876         if (copy_from_user(p, arg, len)) {
877                 kfree(p);
878                 return -EFAULT;
879         }
880         p[len-1] = '\0';
881
882         q = writer->tag;
883         writer->tag = p;
884         writer->tag_len = len - 1; /* without NULL */
885         kfree(q);
886
887         return 0;
888 }
889
890 static long logger_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
891 {
892         struct logger_log *log = file_get_log(file);
893         struct logger_reader *reader;
894         struct logger_writer *writer;
895         long ret = -EINVAL;
896         void __user *argp = (void __user *)arg;
897
898         mutex_lock(&log->mutex);
899
900         switch (cmd) {
901         case LOGGER_GET_LOG_BUF_SIZE:
902                 ret = log->size;
903                 break;
904         case LOGGER_GET_LOG_LEN:
905                 if (!(file->f_mode & FMODE_READ)) {
906                         ret = -EBADF;
907                         break;
908                 }
909                 reader = file->private_data;
910                 if (log->w_off >= reader->r_off)
911                         ret = log->w_off - reader->r_off;
912                 else
913                         ret = (log->size - reader->r_off) + log->w_off;
914                 break;
915         case LOGGER_GET_NEXT_ENTRY_LEN:
916                 if (!(file->f_mode & FMODE_READ)) {
917                         ret = -EBADF;
918                         break;
919                 }
920                 reader = file->private_data;
921
922                 if (!reader->r_all)
923                         reader->r_off = get_next_entry_by_uid(log,
924                                 reader->r_off, current_euid());
925
926                 if (log->w_off != reader->r_off)
927                         ret = get_user_hdr_len(reader->r_ver) +
928                                 get_entry_msg_len(log, reader->r_off);
929                 else
930                         ret = 0;
931                 break;
932         case LOGGER_FLUSH_LOG:
933                 if (!(in_egroup_p(file_inode(file)->i_gid) ||
934                       capable(CAP_SYSLOG))) {
935                         ret = -EPERM;
936                         break;
937                 }
938                 list_for_each_entry(reader, &log->readers, list)
939                         reader->r_off = log->w_off;
940                 log->head = log->w_off;
941                 ret = 0;
942                 break;
943         case LOGGER_GET_VERSION:
944                 if (!(file->f_mode & FMODE_READ)) {
945                         ret = -EBADF;
946                         break;
947                 }
948                 reader = file->private_data;
949                 ret = reader->r_ver;
950                 break;
951         case LOGGER_SET_VERSION:
952                 if (!(file->f_mode & FMODE_READ)) {
953                         ret = -EBADF;
954                         break;
955                 }
956                 reader = file->private_data;
957                 ret = logger_set_version(reader, argp);
958                 break;
959         case LOGGER_SET_PRIO:   /* 44552 */
960                 if (file->f_mode & FMODE_READ) {
961                         ret = -EBADF;
962                         break;
963                 }
964                 writer = file->private_data;
965                 ret = logger_set_prio(writer, argp);
966                 break;
967         case LOGGER_SET_TAG:    /* 44551 */
968                 if (file->f_mode & FMODE_READ) {
969                         ret = -EBADF;
970                         break;
971                 }
972                 writer = file->private_data;
973                 ret = logger_set_tag(writer, argp);
974                 break;
975         }
976
977         mutex_unlock(&log->mutex);
978
979         return ret;
980 }
981
982 static const struct file_operations logger_fops = {
983         .owner = THIS_MODULE,
984         .read = logger_read,
985         .write_iter = logger_write_iter,
986         .poll = logger_poll,
987         .unlocked_ioctl = logger_ioctl,
988         .compat_ioctl = logger_ioctl,
989         .open = logger_open,
990         .release = logger_release,
991 };
992
993 /*
994  * Log size must must be a power of two, and greater than
995  * (LOGGER_ENTRY_MAX_PAYLOAD + sizeof(struct logger_entry)).
996  */
997 static int __init create_log(char *log_name, int size)
998 {
999         int ret = 0;
1000         struct logger_log *log;
1001         unsigned char *buffer;
1002
1003         buffer = vmalloc(size);
1004         if (buffer == NULL)
1005                 return -ENOMEM;
1006
1007         log = kzalloc(sizeof(struct logger_log), GFP_KERNEL);
1008         if (log == NULL) {
1009                 ret = -ENOMEM;
1010                 goto out_free_buffer;
1011         }
1012         log->buffer = buffer;
1013
1014         log->misc.minor = MISC_DYNAMIC_MINOR;
1015         log->misc.name = kstrdup(log_name, GFP_KERNEL);
1016         if (log->misc.name == NULL) {
1017                 ret = -ENOMEM;
1018                 goto out_free_log;
1019         }
1020
1021         log->misc.fops = &logger_fops;
1022         log->misc.parent = NULL;
1023
1024         init_waitqueue_head(&log->wq);
1025         INIT_LIST_HEAD(&log->readers);
1026         mutex_init(&log->mutex);
1027         log->w_off = 0;
1028         log->head = 0;
1029         log->size = size;
1030
1031         INIT_LIST_HEAD(&log->logs);
1032         list_add_tail(&log->logs, &log_list);
1033
1034         /* finally, initialize the misc device for this log */
1035         ret = misc_register(&log->misc);
1036         if (unlikely(ret)) {
1037                 pr_err("failed to register misc device for log '%s'!\n",
1038                        log->misc.name);
1039                 goto out_free_misc_name;
1040         }
1041
1042         pr_info("created %luK log '%s'\n",
1043                 (unsigned long)log->size >> 10, log->misc.name);
1044
1045         return 0;
1046
1047 out_free_misc_name:
1048         kfree(log->misc.name);
1049
1050 out_free_log:
1051         kfree(log);
1052
1053 out_free_buffer:
1054         vfree(buffer);
1055         return ret;
1056 }
1057
1058 static int __init logger_init(void)
1059 {
1060         int ret;
1061
1062         ret = create_log(LOGGER_LOG_MAIN, 256*1024);
1063         if (unlikely(ret))
1064                 goto out;
1065
1066         ret = create_log(LOGGER_LOG_EVENTS, 256*1024);
1067         if (unlikely(ret))
1068                 goto out;
1069
1070         ret = create_log(LOGGER_LOG_RADIO, 256*1024);
1071         if (unlikely(ret))
1072                 goto out;
1073
1074         ret = create_log(LOGGER_LOG_SYSTEM, 256*1024);
1075         if (unlikely(ret))
1076                 goto out;
1077
1078 out:
1079         return ret;
1080 }
1081
1082 static void __exit logger_exit(void)
1083 {
1084         struct logger_log *current_log, *next_log;
1085
1086         list_for_each_entry_safe(current_log, next_log, &log_list, logs) {
1087                 /* we have to delete all the entry inside log_list */
1088                 misc_deregister(&current_log->misc);
1089                 vfree(current_log->buffer);
1090                 kfree(current_log->misc.name);
1091                 list_del(&current_log->logs);
1092                 kfree(current_log);
1093         }
1094 }
1095
1096 device_initcall(logger_init);
1097 module_exit(logger_exit);
1098
1099 MODULE_LICENSE("GPL");
1100 MODULE_AUTHOR("Robert Love, <rlove@google.com>");
1101 MODULE_DESCRIPTION("Android Logger");