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 if (unlikely(size > MAX_RW_COUNT))
38 return kvmalloc(size, GFP_KERNEL_ACCOUNT);
42 * seq_open - initialize sequential file
43 * @file: file we initialize
44 * @op: method table describing the sequence
46 * seq_open() sets @file, associating it with a sequence described
47 * by @op. @op->start() sets the iterator up and returns the first
48 * element of sequence. @op->stop() shuts it down. @op->next()
49 * returns the next element of sequence. @op->show() prints element
50 * into the buffer. In case of error ->start() and ->next() return
51 * ERR_PTR(error). In the end of sequence they return %NULL. ->show()
52 * returns 0 in case of success and negative number in case of error.
53 * Returning SEQ_SKIP means "discard this element and move on".
54 * Note: seq_open() will allocate a struct seq_file and store its
55 * pointer in @file->private_data. This pointer should not be modified.
57 int seq_open(struct file *file, const struct seq_operations *op)
61 WARN_ON(file->private_data);
63 p = kmem_cache_zalloc(seq_file_cache, GFP_KERNEL);
67 file->private_data = p;
72 // No refcounting: the lifetime of 'p' is constrained
73 // to the lifetime of the file.
77 * seq_files support lseek() and pread(). They do not implement
78 * write() at all, but we clear FMODE_PWRITE here for historical
81 * If a client of seq_files a) implements file.write() and b) wishes to
82 * support pwrite() then that client will need to implement its own
83 * file.open() which calls seq_open() and then sets FMODE_PWRITE.
85 file->f_mode &= ~FMODE_PWRITE;
88 EXPORT_SYMBOL(seq_open);
90 static int traverse(struct seq_file *m, loff_t offset)
97 m->count = m->from = 0;
102 m->buf = seq_buf_alloc(m->size = PAGE_SIZE);
106 p = m->op->start(m, &m->index);
111 error = m->op->show(m, p);
114 if (unlikely(error)) {
118 if (seq_has_overflowed(m))
120 p = m->op->next(m, p, &m->index);
121 if (pos + m->count > offset) {
122 m->from = offset - pos;
138 m->buf = seq_buf_alloc(m->size <<= 1);
139 return !m->buf ? -ENOMEM : -EAGAIN;
143 * seq_read - ->read() method for sequential files.
144 * @file: the file to read from
145 * @buf: the buffer to read to
146 * @size: the maximum number of bytes to read
147 * @ppos: the current position in the file
149 * Ready-made ->f_op->read()
151 ssize_t seq_read(struct file *file, char __user *buf, size_t size, loff_t *ppos)
153 struct iovec iov = { .iov_base = buf, .iov_len = size};
155 struct iov_iter iter;
158 init_sync_kiocb(&kiocb, file);
159 iov_iter_init(&iter, READ, &iov, 1, size);
161 kiocb.ki_pos = *ppos;
162 ret = seq_read_iter(&kiocb, &iter);
163 *ppos = kiocb.ki_pos;
166 EXPORT_SYMBOL(seq_read);
169 * Ready-made ->f_op->read_iter()
171 ssize_t seq_read_iter(struct kiocb *iocb, struct iov_iter *iter)
173 struct seq_file *m = iocb->ki_filp->private_data;
179 if (!iov_iter_count(iter))
182 mutex_lock(&m->lock);
185 * if request is to read from zero offset, reset iterator to first
186 * record as it might have been already advanced by previous requests
188 if (iocb->ki_pos == 0) {
193 /* Don't assume ki_pos is where we left it */
194 if (unlikely(iocb->ki_pos != m->read_pos)) {
195 while ((err = traverse(m, iocb->ki_pos)) == -EAGAIN)
198 /* With prejudice... */
204 m->read_pos = iocb->ki_pos;
208 /* grab buffer if we didn't have one */
210 m->buf = seq_buf_alloc(m->size = PAGE_SIZE);
214 // something left in the buffer - copy it out first
216 n = copy_to_iter(m->buf + m->from, m->count, iter);
220 if (m->count) // hadn't managed to copy everything
223 // get a non-empty record in the buffer
225 p = m->op->start(m, &m->index);
228 if (!p || IS_ERR(p)) // EOF or an error
230 err = m->op->show(m, p);
231 if (err < 0) // hard error
233 if (unlikely(err)) // ->show() says "skip it"
235 if (unlikely(!m->count)) { // empty record
236 p = m->op->next(m, p, &m->index);
239 if (!seq_has_overflowed(m)) // got it
241 // need a bigger buffer
245 m->buf = seq_buf_alloc(m->size <<= 1);
248 p = m->op->start(m, &m->index);
255 // one non-empty record is in the buffer; if they want more,
256 // try to fit more in, but in any case we need to advance
257 // the iterator once for every record shown.
259 size_t offs = m->count;
260 loff_t pos = m->index;
262 p = m->op->next(m, p, &m->index);
263 if (pos == m->index) {
264 pr_info_ratelimited("buggy .next function %ps did not update position index\n",
268 if (!p || IS_ERR(p)) // no next record for us
270 if (m->count >= iov_iter_count(iter))
272 err = m->op->show(m, p);
273 if (err > 0) { // ->show() says "skip it"
275 } else if (err || seq_has_overflowed(m)) {
281 n = copy_to_iter(m->buf, m->count, iter);
286 if (unlikely(!copied)) {
287 copied = m->count ? -EFAULT : err;
289 iocb->ki_pos += copied;
290 m->read_pos += copied;
292 mutex_unlock(&m->lock);
298 EXPORT_SYMBOL(seq_read_iter);
301 * seq_lseek - ->llseek() method for sequential files.
302 * @file: the file in question
303 * @offset: new position
304 * @whence: 0 for absolute, 1 for relative position
306 * Ready-made ->f_op->llseek()
308 loff_t seq_lseek(struct file *file, loff_t offset, int whence)
310 struct seq_file *m = file->private_data;
311 loff_t retval = -EINVAL;
313 mutex_lock(&m->lock);
316 offset += file->f_pos;
322 if (offset != m->read_pos) {
323 while ((retval = traverse(m, offset)) == -EAGAIN)
326 /* with extreme prejudice... */
332 m->read_pos = offset;
333 retval = file->f_pos = offset;
336 file->f_pos = offset;
339 mutex_unlock(&m->lock);
342 EXPORT_SYMBOL(seq_lseek);
345 * seq_release - free the structures associated with sequential file.
346 * @file: file in question
349 * Frees the structures associated with sequential file; can be used
350 * as ->f_op->release() if you don't have private data to destroy.
352 int seq_release(struct inode *inode, struct file *file)
354 struct seq_file *m = file->private_data;
356 kmem_cache_free(seq_file_cache, m);
359 EXPORT_SYMBOL(seq_release);
362 * seq_escape_mem - print data into buffer, escaping some characters
364 * @src: source buffer
365 * @len: size of source buffer
366 * @flags: flags to pass to string_escape_mem()
367 * @esc: set of characters that need escaping
369 * Puts data into buffer, replacing each occurrence of character from
370 * given class (defined by @flags and @esc) with printable escaped sequence.
372 * Use seq_has_overflowed() to check for errors.
374 void seq_escape_mem(struct seq_file *m, const char *src, size_t len,
375 unsigned int flags, const char *esc)
378 size_t size = seq_get_buf(m, &buf);
381 ret = string_escape_mem(src, len, buf, size, flags, esc);
382 seq_commit(m, ret < size ? ret : -1);
384 EXPORT_SYMBOL(seq_escape_mem);
386 void seq_vprintf(struct seq_file *m, const char *f, va_list args)
390 if (m->count < m->size) {
391 len = vsnprintf(m->buf + m->count, m->size - m->count, f, args);
392 if (m->count + len < m->size) {
399 EXPORT_SYMBOL(seq_vprintf);
401 void seq_printf(struct seq_file *m, const char *f, ...)
406 seq_vprintf(m, f, args);
409 EXPORT_SYMBOL(seq_printf);
411 #ifdef CONFIG_BINARY_PRINTF
412 void seq_bprintf(struct seq_file *m, const char *f, const u32 *binary)
416 if (m->count < m->size) {
417 len = bstr_printf(m->buf + m->count, m->size - m->count, f,
419 if (m->count + len < m->size) {
426 EXPORT_SYMBOL(seq_bprintf);
427 #endif /* CONFIG_BINARY_PRINTF */
430 * mangle_path - mangle and copy path to buffer beginning
432 * @p: beginning of path in above buffer
433 * @esc: set of characters that need escaping
435 * Copy the path from @p to @s, replacing each occurrence of character from
436 * @esc with usual octal escape.
437 * Returns pointer past last written character in @s, or NULL in case of
440 char *mangle_path(char *s, const char *p, const char *esc)
446 } else if (!strchr(esc, c)) {
448 } else if (s + 4 > p) {
452 *s++ = '0' + ((c & 0300) >> 6);
453 *s++ = '0' + ((c & 070) >> 3);
454 *s++ = '0' + (c & 07);
459 EXPORT_SYMBOL(mangle_path);
462 * seq_path - seq_file interface to print a pathname
463 * @m: the seq_file handle
464 * @path: the struct path to print
465 * @esc: set of characters to escape in the output
467 * return the absolute path of 'path', as represented by the
468 * dentry / mnt pair in the path parameter.
470 int seq_path(struct seq_file *m, const struct path *path, const char *esc)
473 size_t size = seq_get_buf(m, &buf);
477 char *p = d_path(path, buf, size);
479 char *end = mangle_path(buf, p, esc);
488 EXPORT_SYMBOL(seq_path);
491 * seq_file_path - seq_file interface to print a pathname of a file
492 * @m: the seq_file handle
493 * @file: the struct file to print
494 * @esc: set of characters to escape in the output
496 * return the absolute path to the file.
498 int seq_file_path(struct seq_file *m, struct file *file, const char *esc)
500 return seq_path(m, &file->f_path, esc);
502 EXPORT_SYMBOL(seq_file_path);
505 * Same as seq_path, but relative to supplied root.
507 int seq_path_root(struct seq_file *m, const struct path *path,
508 const struct path *root, const char *esc)
511 size_t size = seq_get_buf(m, &buf);
512 int res = -ENAMETOOLONG;
517 p = __d_path(path, root, buf, size);
522 char *end = mangle_path(buf, p, esc);
531 return res < 0 && res != -ENAMETOOLONG ? res : 0;
535 * returns the path of the 'dentry' from the root of its filesystem.
537 int seq_dentry(struct seq_file *m, struct dentry *dentry, const char *esc)
540 size_t size = seq_get_buf(m, &buf);
544 char *p = dentry_path(dentry, buf, size);
546 char *end = mangle_path(buf, p, esc);
555 EXPORT_SYMBOL(seq_dentry);
557 void *single_start(struct seq_file *p, loff_t *pos)
559 return *pos ? NULL : SEQ_START_TOKEN;
562 static void *single_next(struct seq_file *p, void *v, loff_t *pos)
568 static void single_stop(struct seq_file *p, void *v)
572 int single_open(struct file *file, int (*show)(struct seq_file *, void *),
575 struct seq_operations *op = kmalloc(sizeof(*op), GFP_KERNEL_ACCOUNT);
579 op->start = single_start;
580 op->next = single_next;
581 op->stop = single_stop;
583 res = seq_open(file, op);
585 ((struct seq_file *)file->private_data)->private = data;
591 EXPORT_SYMBOL(single_open);
593 int single_open_size(struct file *file, int (*show)(struct seq_file *, void *),
594 void *data, size_t size)
596 char *buf = seq_buf_alloc(size);
600 ret = single_open(file, show, data);
605 ((struct seq_file *)file->private_data)->buf = buf;
606 ((struct seq_file *)file->private_data)->size = size;
609 EXPORT_SYMBOL(single_open_size);
611 int single_release(struct inode *inode, struct file *file)
613 const struct seq_operations *op = ((struct seq_file *)file->private_data)->op;
614 int res = seq_release(inode, file);
618 EXPORT_SYMBOL(single_release);
620 int seq_release_private(struct inode *inode, struct file *file)
622 struct seq_file *seq = file->private_data;
626 return seq_release(inode, file);
628 EXPORT_SYMBOL(seq_release_private);
630 void *__seq_open_private(struct file *f, const struct seq_operations *ops,
635 struct seq_file *seq;
637 private = kzalloc(psize, GFP_KERNEL_ACCOUNT);
641 rc = seq_open(f, ops);
645 seq = f->private_data;
646 seq->private = private;
654 EXPORT_SYMBOL(__seq_open_private);
656 int seq_open_private(struct file *filp, const struct seq_operations *ops,
659 return __seq_open_private(filp, ops, psize) ? 0 : -ENOMEM;
661 EXPORT_SYMBOL(seq_open_private);
663 void seq_putc(struct seq_file *m, char c)
665 if (m->count >= m->size)
668 m->buf[m->count++] = c;
670 EXPORT_SYMBOL(seq_putc);
672 void seq_puts(struct seq_file *m, const char *s)
676 if (m->count + len >= m->size) {
680 memcpy(m->buf + m->count, s, len);
683 EXPORT_SYMBOL(seq_puts);
686 * seq_put_decimal_ull_width - A helper routine for putting decimal numbers
687 * without rich format of printf().
688 * only 'unsigned long long' is supported.
689 * @m: seq_file identifying the buffer to which data should be written
690 * @delimiter: a string which is printed before the number
692 * @width: a minimum field width
694 * This routine will put strlen(delimiter) + number into seq_filed.
695 * This routine is very quick when you show lots of numbers.
696 * In usual cases, it will be better to use seq_printf(). It's easier to read.
698 void seq_put_decimal_ull_width(struct seq_file *m, const char *delimiter,
699 unsigned long long num, unsigned int width)
703 if (m->count + 2 >= m->size) /* we'll write 2 bytes at least */
706 if (delimiter && delimiter[0]) {
707 if (delimiter[1] == 0)
708 seq_putc(m, delimiter[0]);
710 seq_puts(m, delimiter);
716 if (m->count + width >= m->size)
719 len = num_to_str(m->buf + m->count, m->size - m->count, num, width);
730 void seq_put_decimal_ull(struct seq_file *m, const char *delimiter,
731 unsigned long long num)
733 return seq_put_decimal_ull_width(m, delimiter, num, 0);
735 EXPORT_SYMBOL(seq_put_decimal_ull);
738 * seq_put_hex_ll - put a number in hexadecimal notation
739 * @m: seq_file identifying the buffer to which data should be written
740 * @delimiter: a string which is printed before the number
742 * @width: a minimum field width
744 * seq_put_hex_ll(m, "", v, 8) is equal to seq_printf(m, "%08llx", v)
746 * This routine is very quick when you show lots of numbers.
747 * In usual cases, it will be better to use seq_printf(). It's easier to read.
749 void seq_put_hex_ll(struct seq_file *m, const char *delimiter,
750 unsigned long long v, unsigned int width)
755 if (delimiter && delimiter[0]) {
756 if (delimiter[1] == 0)
757 seq_putc(m, delimiter[0]);
759 seq_puts(m, delimiter);
762 /* If x is 0, the result of __builtin_clzll is undefined */
766 len = (sizeof(v) * 8 - __builtin_clzll(v) + 3) / 4;
771 if (m->count + len > m->size) {
776 for (i = len - 1; i >= 0; i--) {
777 m->buf[m->count + i] = hex_asc[0xf & v];
783 void seq_put_decimal_ll(struct seq_file *m, const char *delimiter, long long num)
787 if (m->count + 3 >= m->size) /* we'll write 2 bytes at least */
790 if (delimiter && delimiter[0]) {
791 if (delimiter[1] == 0)
792 seq_putc(m, delimiter[0]);
794 seq_puts(m, delimiter);
797 if (m->count + 2 >= m->size)
801 m->buf[m->count++] = '-';
806 m->buf[m->count++] = num + '0';
810 len = num_to_str(m->buf + m->count, m->size - m->count, num, 0);
820 EXPORT_SYMBOL(seq_put_decimal_ll);
823 * seq_write - write arbitrary data to buffer
824 * @seq: seq_file identifying the buffer to which data should be written
825 * @data: data address
826 * @len: number of bytes
828 * Return 0 on success, non-zero otherwise.
830 int seq_write(struct seq_file *seq, const void *data, size_t len)
832 if (seq->count + len < seq->size) {
833 memcpy(seq->buf + seq->count, data, len);
837 seq_set_overflow(seq);
840 EXPORT_SYMBOL(seq_write);
843 * seq_pad - write padding spaces to buffer
844 * @m: seq_file identifying the buffer to which data should be written
845 * @c: the byte to append after padding if non-zero
847 void seq_pad(struct seq_file *m, char c)
849 int size = m->pad_until - m->count;
851 if (size + m->count > m->size) {
855 memset(m->buf + m->count, ' ', size);
861 EXPORT_SYMBOL(seq_pad);
863 /* A complete analogue of print_hex_dump() */
864 void seq_hex_dump(struct seq_file *m, const char *prefix_str, int prefix_type,
865 int rowsize, int groupsize, const void *buf, size_t len,
869 int i, linelen, remaining = len;
874 if (rowsize != 16 && rowsize != 32)
877 for (i = 0; i < len && !seq_has_overflowed(m); i += rowsize) {
878 linelen = min(remaining, rowsize);
879 remaining -= rowsize;
881 switch (prefix_type) {
882 case DUMP_PREFIX_ADDRESS:
883 seq_printf(m, "%s%p: ", prefix_str, ptr + i);
885 case DUMP_PREFIX_OFFSET:
886 seq_printf(m, "%s%.8x: ", prefix_str, i);
889 seq_printf(m, "%s", prefix_str);
893 size = seq_get_buf(m, &buffer);
894 ret = hex_dump_to_buffer(ptr + i, linelen, rowsize, groupsize,
895 buffer, size, ascii);
896 seq_commit(m, ret < size ? ret : -1);
901 EXPORT_SYMBOL(seq_hex_dump);
903 struct list_head *seq_list_start(struct list_head *head, loff_t pos)
905 struct list_head *lh;
907 list_for_each(lh, head)
913 EXPORT_SYMBOL(seq_list_start);
915 struct list_head *seq_list_start_head(struct list_head *head, loff_t pos)
920 return seq_list_start(head, pos - 1);
922 EXPORT_SYMBOL(seq_list_start_head);
924 struct list_head *seq_list_next(void *v, struct list_head *head, loff_t *ppos)
926 struct list_head *lh;
928 lh = ((struct list_head *)v)->next;
930 return lh == head ? NULL : lh;
932 EXPORT_SYMBOL(seq_list_next);
935 * seq_hlist_start - start an iteration of a hlist
936 * @head: the head of the hlist
937 * @pos: the start position of the sequence
939 * Called at seq_file->op->start().
941 struct hlist_node *seq_hlist_start(struct hlist_head *head, loff_t pos)
943 struct hlist_node *node;
945 hlist_for_each(node, head)
950 EXPORT_SYMBOL(seq_hlist_start);
953 * seq_hlist_start_head - start an iteration of a hlist
954 * @head: the head of the hlist
955 * @pos: the start position of the sequence
957 * Called at seq_file->op->start(). Call this function if you want to
958 * print a header at the top of the output.
960 struct hlist_node *seq_hlist_start_head(struct hlist_head *head, loff_t pos)
963 return SEQ_START_TOKEN;
965 return seq_hlist_start(head, pos - 1);
967 EXPORT_SYMBOL(seq_hlist_start_head);
970 * seq_hlist_next - move to the next position of the hlist
971 * @v: the current iterator
972 * @head: the head of the hlist
973 * @ppos: the current position
975 * Called at seq_file->op->next().
977 struct hlist_node *seq_hlist_next(void *v, struct hlist_head *head,
980 struct hlist_node *node = v;
983 if (v == SEQ_START_TOKEN)
988 EXPORT_SYMBOL(seq_hlist_next);
991 * seq_hlist_start_rcu - start an iteration of a hlist protected by RCU
992 * @head: the head of the hlist
993 * @pos: the start position of the sequence
995 * Called at seq_file->op->start().
997 * This list-traversal primitive may safely run concurrently with
998 * the _rcu list-mutation primitives such as hlist_add_head_rcu()
999 * as long as the traversal is guarded by rcu_read_lock().
1001 struct hlist_node *seq_hlist_start_rcu(struct hlist_head *head,
1004 struct hlist_node *node;
1006 __hlist_for_each_rcu(node, head)
1011 EXPORT_SYMBOL(seq_hlist_start_rcu);
1014 * seq_hlist_start_head_rcu - start an iteration of a hlist protected by RCU
1015 * @head: the head of the hlist
1016 * @pos: the start position of the sequence
1018 * Called at seq_file->op->start(). Call this function if you want to
1019 * print a header at the top of the output.
1021 * This list-traversal primitive may safely run concurrently with
1022 * the _rcu list-mutation primitives such as hlist_add_head_rcu()
1023 * as long as the traversal is guarded by rcu_read_lock().
1025 struct hlist_node *seq_hlist_start_head_rcu(struct hlist_head *head,
1029 return SEQ_START_TOKEN;
1031 return seq_hlist_start_rcu(head, pos - 1);
1033 EXPORT_SYMBOL(seq_hlist_start_head_rcu);
1036 * seq_hlist_next_rcu - move to the next position of the hlist protected by RCU
1037 * @v: the current iterator
1038 * @head: the head of the hlist
1039 * @ppos: the current position
1041 * Called at seq_file->op->next().
1043 * This list-traversal primitive may safely run concurrently with
1044 * the _rcu list-mutation primitives such as hlist_add_head_rcu()
1045 * as long as the traversal is guarded by rcu_read_lock().
1047 struct hlist_node *seq_hlist_next_rcu(void *v,
1048 struct hlist_head *head,
1051 struct hlist_node *node = v;
1054 if (v == SEQ_START_TOKEN)
1055 return rcu_dereference(head->first);
1057 return rcu_dereference(node->next);
1059 EXPORT_SYMBOL(seq_hlist_next_rcu);
1062 * seq_hlist_start_percpu - start an iteration of a percpu hlist array
1063 * @head: pointer to percpu array of struct hlist_heads
1064 * @cpu: pointer to cpu "cursor"
1065 * @pos: start position of sequence
1067 * Called at seq_file->op->start().
1070 seq_hlist_start_percpu(struct hlist_head __percpu *head, int *cpu, loff_t pos)
1072 struct hlist_node *node;
1074 for_each_possible_cpu(*cpu) {
1075 hlist_for_each(node, per_cpu_ptr(head, *cpu)) {
1082 EXPORT_SYMBOL(seq_hlist_start_percpu);
1085 * seq_hlist_next_percpu - move to the next position of the percpu hlist array
1086 * @v: pointer to current hlist_node
1087 * @head: pointer to percpu array of struct hlist_heads
1088 * @cpu: pointer to cpu "cursor"
1089 * @pos: start position of sequence
1091 * Called at seq_file->op->next().
1094 seq_hlist_next_percpu(void *v, struct hlist_head __percpu *head,
1095 int *cpu, loff_t *pos)
1097 struct hlist_node *node = v;
1104 for (*cpu = cpumask_next(*cpu, cpu_possible_mask); *cpu < nr_cpu_ids;
1105 *cpu = cpumask_next(*cpu, cpu_possible_mask)) {
1106 struct hlist_head *bucket = per_cpu_ptr(head, *cpu);
1108 if (!hlist_empty(bucket))
1109 return bucket->first;
1113 EXPORT_SYMBOL(seq_hlist_next_percpu);
1115 void __init seq_file_init(void)
1117 seq_file_cache = KMEM_CACHE(seq_file, SLAB_ACCOUNT|SLAB_PANIC);