1 // SPDX-License-Identifier: GPL-2.0
5 * helper functions for making synthetic files from sequences of records.
6 * initial implementation -- AV, Oct 2001.
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11 #include <linux/cache.h>
13 #include <linux/export.h>
14 #include <linux/seq_file.h>
15 #include <linux/vmalloc.h>
16 #include <linux/slab.h>
17 #include <linux/cred.h>
19 #include <linux/printk.h>
20 #include <linux/string_helpers.h>
21 #include <linux/uio.h>
23 #include <linux/uaccess.h>
26 static struct kmem_cache *seq_file_cache __ro_after_init;
28 static void seq_set_overflow(struct seq_file *m)
33 static void *seq_buf_alloc(unsigned long size)
35 return kvmalloc(size, GFP_KERNEL_ACCOUNT);
39 * seq_open - initialize sequential file
40 * @file: file we initialize
41 * @op: method table describing the sequence
43 * seq_open() sets @file, associating it with a sequence described
44 * by @op. @op->start() sets the iterator up and returns the first
45 * element of sequence. @op->stop() shuts it down. @op->next()
46 * returns the next element of sequence. @op->show() prints element
47 * into the buffer. In case of error ->start() and ->next() return
48 * ERR_PTR(error). In the end of sequence they return %NULL. ->show()
49 * returns 0 in case of success and negative number in case of error.
50 * Returning SEQ_SKIP means "discard this element and move on".
51 * Note: seq_open() will allocate a struct seq_file and store its
52 * pointer in @file->private_data. This pointer should not be modified.
54 int seq_open(struct file *file, const struct seq_operations *op)
58 WARN_ON(file->private_data);
60 p = kmem_cache_zalloc(seq_file_cache, GFP_KERNEL);
64 file->private_data = p;
69 // No refcounting: the lifetime of 'p' is constrained
70 // to the lifetime of the file.
74 * seq_files support lseek() and pread(). They do not implement
75 * write() at all, but we clear FMODE_PWRITE here for historical
78 * If a client of seq_files a) implements file.write() and b) wishes to
79 * support pwrite() then that client will need to implement its own
80 * file.open() which calls seq_open() and then sets FMODE_PWRITE.
82 file->f_mode &= ~FMODE_PWRITE;
85 EXPORT_SYMBOL(seq_open);
87 static int traverse(struct seq_file *m, loff_t offset)
94 m->count = m->from = 0;
99 m->buf = seq_buf_alloc(m->size = PAGE_SIZE);
103 p = m->op->start(m, &m->index);
108 error = m->op->show(m, p);
111 if (unlikely(error)) {
115 if (seq_has_overflowed(m))
117 p = m->op->next(m, p, &m->index);
118 if (pos + m->count > offset) {
119 m->from = offset - pos;
135 m->buf = seq_buf_alloc(m->size <<= 1);
136 return !m->buf ? -ENOMEM : -EAGAIN;
140 * seq_read - ->read() method for sequential files.
141 * @file: the file to read from
142 * @buf: the buffer to read to
143 * @size: the maximum number of bytes to read
144 * @ppos: the current position in the file
146 * Ready-made ->f_op->read()
148 ssize_t seq_read(struct file *file, char __user *buf, size_t size, loff_t *ppos)
150 struct iovec iov = { .iov_base = buf, .iov_len = size};
152 struct iov_iter iter;
155 init_sync_kiocb(&kiocb, file);
156 iov_iter_init(&iter, READ, &iov, 1, size);
158 kiocb.ki_pos = *ppos;
159 ret = seq_read_iter(&kiocb, &iter);
160 *ppos = kiocb.ki_pos;
163 EXPORT_SYMBOL(seq_read);
166 * Ready-made ->f_op->read_iter()
168 ssize_t seq_read_iter(struct kiocb *iocb, struct iov_iter *iter)
170 struct seq_file *m = iocb->ki_filp->private_data;
176 if (!iov_iter_count(iter))
179 mutex_lock(&m->lock);
182 * if request is to read from zero offset, reset iterator to first
183 * record as it might have been already advanced by previous requests
185 if (iocb->ki_pos == 0) {
190 /* Don't assume ki_pos is where we left it */
191 if (unlikely(iocb->ki_pos != m->read_pos)) {
192 while ((err = traverse(m, iocb->ki_pos)) == -EAGAIN)
195 /* With prejudice... */
201 m->read_pos = iocb->ki_pos;
205 /* grab buffer if we didn't have one */
207 m->buf = seq_buf_alloc(m->size = PAGE_SIZE);
211 // something left in the buffer - copy it out first
213 n = copy_to_iter(m->buf + m->from, m->count, iter);
217 if (m->count) // hadn't managed to copy everything
220 // get a non-empty record in the buffer
222 p = m->op->start(m, &m->index);
225 if (!p || IS_ERR(p)) // EOF or an error
227 err = m->op->show(m, p);
228 if (err < 0) // hard error
230 if (unlikely(err)) // ->show() says "skip it"
232 if (unlikely(!m->count)) { // empty record
233 p = m->op->next(m, p, &m->index);
236 if (!seq_has_overflowed(m)) // got it
238 // need a bigger buffer
242 m->buf = seq_buf_alloc(m->size <<= 1);
245 p = m->op->start(m, &m->index);
252 // one non-empty record is in the buffer; if they want more,
253 // try to fit more in, but in any case we need to advance
254 // the iterator once for every record shown.
256 size_t offs = m->count;
257 loff_t pos = m->index;
259 p = m->op->next(m, p, &m->index);
260 if (pos == m->index) {
261 pr_info_ratelimited("buggy .next function %ps did not update position index\n",
265 if (!p || IS_ERR(p)) // no next record for us
267 if (m->count >= iov_iter_count(iter))
269 err = m->op->show(m, p);
270 if (err > 0) { // ->show() says "skip it"
272 } else if (err || seq_has_overflowed(m)) {
278 n = copy_to_iter(m->buf, m->count, iter);
283 if (unlikely(!copied)) {
284 copied = m->count ? -EFAULT : err;
286 iocb->ki_pos += copied;
287 m->read_pos += copied;
289 mutex_unlock(&m->lock);
295 EXPORT_SYMBOL(seq_read_iter);
298 * seq_lseek - ->llseek() method for sequential files.
299 * @file: the file in question
300 * @offset: new position
301 * @whence: 0 for absolute, 1 for relative position
303 * Ready-made ->f_op->llseek()
305 loff_t seq_lseek(struct file *file, loff_t offset, int whence)
307 struct seq_file *m = file->private_data;
308 loff_t retval = -EINVAL;
310 mutex_lock(&m->lock);
313 offset += file->f_pos;
319 if (offset != m->read_pos) {
320 while ((retval = traverse(m, offset)) == -EAGAIN)
323 /* with extreme prejudice... */
329 m->read_pos = offset;
330 retval = file->f_pos = offset;
333 file->f_pos = offset;
336 mutex_unlock(&m->lock);
339 EXPORT_SYMBOL(seq_lseek);
342 * seq_release - free the structures associated with sequential file.
343 * @file: file in question
346 * Frees the structures associated with sequential file; can be used
347 * as ->f_op->release() if you don't have private data to destroy.
349 int seq_release(struct inode *inode, struct file *file)
351 struct seq_file *m = file->private_data;
353 kmem_cache_free(seq_file_cache, m);
356 EXPORT_SYMBOL(seq_release);
359 * seq_escape_mem - print data into buffer, escaping some characters
361 * @src: source buffer
362 * @len: size of source buffer
363 * @flags: flags to pass to string_escape_mem()
364 * @esc: set of characters that need escaping
366 * Puts data into buffer, replacing each occurrence of character from
367 * given class (defined by @flags and @esc) with printable escaped sequence.
369 * Use seq_has_overflowed() to check for errors.
371 void seq_escape_mem(struct seq_file *m, const char *src, size_t len,
372 unsigned int flags, const char *esc)
375 size_t size = seq_get_buf(m, &buf);
378 ret = string_escape_mem(src, len, buf, size, flags, esc);
379 seq_commit(m, ret < size ? ret : -1);
381 EXPORT_SYMBOL(seq_escape_mem);
384 * seq_escape - print string into buffer, escaping some characters
387 * @esc: set of characters that need escaping
389 * Puts string into buffer, replacing each occurrence of character from
390 * @esc with usual octal escape.
391 * Use seq_has_overflowed() to check for errors.
393 void seq_escape(struct seq_file *m, const char *s, const char *esc)
395 seq_escape_str(m, s, ESCAPE_OCTAL, esc);
397 EXPORT_SYMBOL(seq_escape);
399 void seq_vprintf(struct seq_file *m, const char *f, va_list args)
403 if (m->count < m->size) {
404 len = vsnprintf(m->buf + m->count, m->size - m->count, f, args);
405 if (m->count + len < m->size) {
412 EXPORT_SYMBOL(seq_vprintf);
414 void seq_printf(struct seq_file *m, const char *f, ...)
419 seq_vprintf(m, f, args);
422 EXPORT_SYMBOL(seq_printf);
424 #ifdef CONFIG_BINARY_PRINTF
425 void seq_bprintf(struct seq_file *m, const char *f, const u32 *binary)
429 if (m->count < m->size) {
430 len = bstr_printf(m->buf + m->count, m->size - m->count, f,
432 if (m->count + len < m->size) {
439 EXPORT_SYMBOL(seq_bprintf);
440 #endif /* CONFIG_BINARY_PRINTF */
443 * mangle_path - mangle and copy path to buffer beginning
445 * @p: beginning of path in above buffer
446 * @esc: set of characters that need escaping
448 * Copy the path from @p to @s, replacing each occurrence of character from
449 * @esc with usual octal escape.
450 * Returns pointer past last written character in @s, or NULL in case of
453 char *mangle_path(char *s, const char *p, const char *esc)
459 } else if (!strchr(esc, c)) {
461 } else if (s + 4 > p) {
465 *s++ = '0' + ((c & 0300) >> 6);
466 *s++ = '0' + ((c & 070) >> 3);
467 *s++ = '0' + (c & 07);
472 EXPORT_SYMBOL(mangle_path);
475 * seq_path - seq_file interface to print a pathname
476 * @m: the seq_file handle
477 * @path: the struct path to print
478 * @esc: set of characters to escape in the output
480 * return the absolute path of 'path', as represented by the
481 * dentry / mnt pair in the path parameter.
483 int seq_path(struct seq_file *m, const struct path *path, const char *esc)
486 size_t size = seq_get_buf(m, &buf);
490 char *p = d_path(path, buf, size);
492 char *end = mangle_path(buf, p, esc);
501 EXPORT_SYMBOL(seq_path);
504 * seq_file_path - seq_file interface to print a pathname of a file
505 * @m: the seq_file handle
506 * @file: the struct file to print
507 * @esc: set of characters to escape in the output
509 * return the absolute path to the file.
511 int seq_file_path(struct seq_file *m, struct file *file, const char *esc)
513 return seq_path(m, &file->f_path, esc);
515 EXPORT_SYMBOL(seq_file_path);
518 * Same as seq_path, but relative to supplied root.
520 int seq_path_root(struct seq_file *m, const struct path *path,
521 const struct path *root, const char *esc)
524 size_t size = seq_get_buf(m, &buf);
525 int res = -ENAMETOOLONG;
530 p = __d_path(path, root, buf, size);
535 char *end = mangle_path(buf, p, esc);
544 return res < 0 && res != -ENAMETOOLONG ? res : 0;
548 * returns the path of the 'dentry' from the root of its filesystem.
550 int seq_dentry(struct seq_file *m, struct dentry *dentry, const char *esc)
553 size_t size = seq_get_buf(m, &buf);
557 char *p = dentry_path(dentry, buf, size);
559 char *end = mangle_path(buf, p, esc);
568 EXPORT_SYMBOL(seq_dentry);
570 static void *single_start(struct seq_file *p, loff_t *pos)
572 return NULL + (*pos == 0);
575 static void *single_next(struct seq_file *p, void *v, loff_t *pos)
581 static void single_stop(struct seq_file *p, void *v)
585 int single_open(struct file *file, int (*show)(struct seq_file *, void *),
588 struct seq_operations *op = kmalloc(sizeof(*op), GFP_KERNEL_ACCOUNT);
592 op->start = single_start;
593 op->next = single_next;
594 op->stop = single_stop;
596 res = seq_open(file, op);
598 ((struct seq_file *)file->private_data)->private = data;
604 EXPORT_SYMBOL(single_open);
606 int single_open_size(struct file *file, int (*show)(struct seq_file *, void *),
607 void *data, size_t size)
609 char *buf = seq_buf_alloc(size);
613 ret = single_open(file, show, data);
618 ((struct seq_file *)file->private_data)->buf = buf;
619 ((struct seq_file *)file->private_data)->size = size;
622 EXPORT_SYMBOL(single_open_size);
624 int single_release(struct inode *inode, struct file *file)
626 const struct seq_operations *op = ((struct seq_file *)file->private_data)->op;
627 int res = seq_release(inode, file);
631 EXPORT_SYMBOL(single_release);
633 int seq_release_private(struct inode *inode, struct file *file)
635 struct seq_file *seq = file->private_data;
639 return seq_release(inode, file);
641 EXPORT_SYMBOL(seq_release_private);
643 void *__seq_open_private(struct file *f, const struct seq_operations *ops,
648 struct seq_file *seq;
650 private = kzalloc(psize, GFP_KERNEL_ACCOUNT);
654 rc = seq_open(f, ops);
658 seq = f->private_data;
659 seq->private = private;
667 EXPORT_SYMBOL(__seq_open_private);
669 int seq_open_private(struct file *filp, const struct seq_operations *ops,
672 return __seq_open_private(filp, ops, psize) ? 0 : -ENOMEM;
674 EXPORT_SYMBOL(seq_open_private);
676 void seq_putc(struct seq_file *m, char c)
678 if (m->count >= m->size)
681 m->buf[m->count++] = c;
683 EXPORT_SYMBOL(seq_putc);
685 void seq_puts(struct seq_file *m, const char *s)
689 if (m->count + len >= m->size) {
693 memcpy(m->buf + m->count, s, len);
696 EXPORT_SYMBOL(seq_puts);
699 * seq_put_decimal_ull_width - A helper routine for putting decimal numbers
700 * without rich format of printf().
701 * only 'unsigned long long' is supported.
702 * @m: seq_file identifying the buffer to which data should be written
703 * @delimiter: a string which is printed before the number
705 * @width: a minimum field width
707 * This routine will put strlen(delimiter) + number into seq_filed.
708 * This routine is very quick when you show lots of numbers.
709 * In usual cases, it will be better to use seq_printf(). It's easier to read.
711 void seq_put_decimal_ull_width(struct seq_file *m, const char *delimiter,
712 unsigned long long num, unsigned int width)
716 if (m->count + 2 >= m->size) /* we'll write 2 bytes at least */
719 if (delimiter && delimiter[0]) {
720 if (delimiter[1] == 0)
721 seq_putc(m, delimiter[0]);
723 seq_puts(m, delimiter);
729 if (m->count + width >= m->size)
732 len = num_to_str(m->buf + m->count, m->size - m->count, num, width);
743 void seq_put_decimal_ull(struct seq_file *m, const char *delimiter,
744 unsigned long long num)
746 return seq_put_decimal_ull_width(m, delimiter, num, 0);
748 EXPORT_SYMBOL(seq_put_decimal_ull);
751 * seq_put_hex_ll - put a number in hexadecimal notation
752 * @m: seq_file identifying the buffer to which data should be written
753 * @delimiter: a string which is printed before the number
755 * @width: a minimum field width
757 * seq_put_hex_ll(m, "", v, 8) is equal to seq_printf(m, "%08llx", v)
759 * This routine is very quick when you show lots of numbers.
760 * In usual cases, it will be better to use seq_printf(). It's easier to read.
762 void seq_put_hex_ll(struct seq_file *m, const char *delimiter,
763 unsigned long long v, unsigned int width)
768 if (delimiter && delimiter[0]) {
769 if (delimiter[1] == 0)
770 seq_putc(m, delimiter[0]);
772 seq_puts(m, delimiter);
775 /* If x is 0, the result of __builtin_clzll is undefined */
779 len = (sizeof(v) * 8 - __builtin_clzll(v) + 3) / 4;
784 if (m->count + len > m->size) {
789 for (i = len - 1; i >= 0; i--) {
790 m->buf[m->count + i] = hex_asc[0xf & v];
796 void seq_put_decimal_ll(struct seq_file *m, const char *delimiter, long long num)
800 if (m->count + 3 >= m->size) /* we'll write 2 bytes at least */
803 if (delimiter && delimiter[0]) {
804 if (delimiter[1] == 0)
805 seq_putc(m, delimiter[0]);
807 seq_puts(m, delimiter);
810 if (m->count + 2 >= m->size)
814 m->buf[m->count++] = '-';
819 m->buf[m->count++] = num + '0';
823 len = num_to_str(m->buf + m->count, m->size - m->count, num, 0);
833 EXPORT_SYMBOL(seq_put_decimal_ll);
836 * seq_write - write arbitrary data to buffer
837 * @seq: seq_file identifying the buffer to which data should be written
838 * @data: data address
839 * @len: number of bytes
841 * Return 0 on success, non-zero otherwise.
843 int seq_write(struct seq_file *seq, const void *data, size_t len)
845 if (seq->count + len < seq->size) {
846 memcpy(seq->buf + seq->count, data, len);
850 seq_set_overflow(seq);
853 EXPORT_SYMBOL(seq_write);
856 * seq_pad - write padding spaces to buffer
857 * @m: seq_file identifying the buffer to which data should be written
858 * @c: the byte to append after padding if non-zero
860 void seq_pad(struct seq_file *m, char c)
862 int size = m->pad_until - m->count;
864 if (size + m->count > m->size) {
868 memset(m->buf + m->count, ' ', size);
874 EXPORT_SYMBOL(seq_pad);
876 /* A complete analogue of print_hex_dump() */
877 void seq_hex_dump(struct seq_file *m, const char *prefix_str, int prefix_type,
878 int rowsize, int groupsize, const void *buf, size_t len,
882 int i, linelen, remaining = len;
887 if (rowsize != 16 && rowsize != 32)
890 for (i = 0; i < len && !seq_has_overflowed(m); i += rowsize) {
891 linelen = min(remaining, rowsize);
892 remaining -= rowsize;
894 switch (prefix_type) {
895 case DUMP_PREFIX_ADDRESS:
896 seq_printf(m, "%s%p: ", prefix_str, ptr + i);
898 case DUMP_PREFIX_OFFSET:
899 seq_printf(m, "%s%.8x: ", prefix_str, i);
902 seq_printf(m, "%s", prefix_str);
906 size = seq_get_buf(m, &buffer);
907 ret = hex_dump_to_buffer(ptr + i, linelen, rowsize, groupsize,
908 buffer, size, ascii);
909 seq_commit(m, ret < size ? ret : -1);
914 EXPORT_SYMBOL(seq_hex_dump);
916 struct list_head *seq_list_start(struct list_head *head, loff_t pos)
918 struct list_head *lh;
920 list_for_each(lh, head)
926 EXPORT_SYMBOL(seq_list_start);
928 struct list_head *seq_list_start_head(struct list_head *head, loff_t pos)
933 return seq_list_start(head, pos - 1);
935 EXPORT_SYMBOL(seq_list_start_head);
937 struct list_head *seq_list_next(void *v, struct list_head *head, loff_t *ppos)
939 struct list_head *lh;
941 lh = ((struct list_head *)v)->next;
943 return lh == head ? NULL : lh;
945 EXPORT_SYMBOL(seq_list_next);
948 * seq_hlist_start - start an iteration of a hlist
949 * @head: the head of the hlist
950 * @pos: the start position of the sequence
952 * Called at seq_file->op->start().
954 struct hlist_node *seq_hlist_start(struct hlist_head *head, loff_t pos)
956 struct hlist_node *node;
958 hlist_for_each(node, head)
963 EXPORT_SYMBOL(seq_hlist_start);
966 * seq_hlist_start_head - start an iteration of a hlist
967 * @head: the head of the hlist
968 * @pos: the start position of the sequence
970 * Called at seq_file->op->start(). Call this function if you want to
971 * print a header at the top of the output.
973 struct hlist_node *seq_hlist_start_head(struct hlist_head *head, loff_t pos)
976 return SEQ_START_TOKEN;
978 return seq_hlist_start(head, pos - 1);
980 EXPORT_SYMBOL(seq_hlist_start_head);
983 * seq_hlist_next - move to the next position of the hlist
984 * @v: the current iterator
985 * @head: the head of the hlist
986 * @ppos: the current position
988 * Called at seq_file->op->next().
990 struct hlist_node *seq_hlist_next(void *v, struct hlist_head *head,
993 struct hlist_node *node = v;
996 if (v == SEQ_START_TOKEN)
1001 EXPORT_SYMBOL(seq_hlist_next);
1004 * seq_hlist_start_rcu - start an iteration of a hlist protected by RCU
1005 * @head: the head of the hlist
1006 * @pos: the start position of the sequence
1008 * Called at seq_file->op->start().
1010 * This list-traversal primitive may safely run concurrently with
1011 * the _rcu list-mutation primitives such as hlist_add_head_rcu()
1012 * as long as the traversal is guarded by rcu_read_lock().
1014 struct hlist_node *seq_hlist_start_rcu(struct hlist_head *head,
1017 struct hlist_node *node;
1019 __hlist_for_each_rcu(node, head)
1024 EXPORT_SYMBOL(seq_hlist_start_rcu);
1027 * seq_hlist_start_head_rcu - start an iteration of a hlist protected by RCU
1028 * @head: the head of the hlist
1029 * @pos: the start position of the sequence
1031 * Called at seq_file->op->start(). Call this function if you want to
1032 * print a header at the top of the output.
1034 * This list-traversal primitive may safely run concurrently with
1035 * the _rcu list-mutation primitives such as hlist_add_head_rcu()
1036 * as long as the traversal is guarded by rcu_read_lock().
1038 struct hlist_node *seq_hlist_start_head_rcu(struct hlist_head *head,
1042 return SEQ_START_TOKEN;
1044 return seq_hlist_start_rcu(head, pos - 1);
1046 EXPORT_SYMBOL(seq_hlist_start_head_rcu);
1049 * seq_hlist_next_rcu - move to the next position of the hlist protected by RCU
1050 * @v: the current iterator
1051 * @head: the head of the hlist
1052 * @ppos: the current position
1054 * Called at seq_file->op->next().
1056 * This list-traversal primitive may safely run concurrently with
1057 * the _rcu list-mutation primitives such as hlist_add_head_rcu()
1058 * as long as the traversal is guarded by rcu_read_lock().
1060 struct hlist_node *seq_hlist_next_rcu(void *v,
1061 struct hlist_head *head,
1064 struct hlist_node *node = v;
1067 if (v == SEQ_START_TOKEN)
1068 return rcu_dereference(head->first);
1070 return rcu_dereference(node->next);
1072 EXPORT_SYMBOL(seq_hlist_next_rcu);
1075 * seq_hlist_start_percpu - start an iteration of a percpu hlist array
1076 * @head: pointer to percpu array of struct hlist_heads
1077 * @cpu: pointer to cpu "cursor"
1078 * @pos: start position of sequence
1080 * Called at seq_file->op->start().
1083 seq_hlist_start_percpu(struct hlist_head __percpu *head, int *cpu, loff_t pos)
1085 struct hlist_node *node;
1087 for_each_possible_cpu(*cpu) {
1088 hlist_for_each(node, per_cpu_ptr(head, *cpu)) {
1095 EXPORT_SYMBOL(seq_hlist_start_percpu);
1098 * seq_hlist_next_percpu - move to the next position of the percpu hlist array
1099 * @v: pointer to current hlist_node
1100 * @head: pointer to percpu array of struct hlist_heads
1101 * @cpu: pointer to cpu "cursor"
1102 * @pos: start position of sequence
1104 * Called at seq_file->op->next().
1107 seq_hlist_next_percpu(void *v, struct hlist_head __percpu *head,
1108 int *cpu, loff_t *pos)
1110 struct hlist_node *node = v;
1117 for (*cpu = cpumask_next(*cpu, cpu_possible_mask); *cpu < nr_cpu_ids;
1118 *cpu = cpumask_next(*cpu, cpu_possible_mask)) {
1119 struct hlist_head *bucket = per_cpu_ptr(head, *cpu);
1121 if (!hlist_empty(bucket))
1122 return bucket->first;
1126 EXPORT_SYMBOL(seq_hlist_next_percpu);
1128 void __init seq_file_init(void)
1130 seq_file_cache = KMEM_CACHE(seq_file, SLAB_ACCOUNT|SLAB_PANIC);