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>
22 #include <linux/uaccess.h>
25 static struct kmem_cache *seq_file_cache __ro_after_init;
27 static void seq_set_overflow(struct seq_file *m)
32 static void *seq_buf_alloc(unsigned long size)
34 return kvmalloc(size, GFP_KERNEL_ACCOUNT);
38 * seq_open - initialize sequential file
39 * @file: file we initialize
40 * @op: method table describing the sequence
42 * seq_open() sets @file, associating it with a sequence described
43 * by @op. @op->start() sets the iterator up and returns the first
44 * element of sequence. @op->stop() shuts it down. @op->next()
45 * returns the next element of sequence. @op->show() prints element
46 * into the buffer. In case of error ->start() and ->next() return
47 * ERR_PTR(error). In the end of sequence they return %NULL. ->show()
48 * returns 0 in case of success and negative number in case of error.
49 * Returning SEQ_SKIP means "discard this element and move on".
50 * Note: seq_open() will allocate a struct seq_file and store its
51 * pointer in @file->private_data. This pointer should not be modified.
53 int seq_open(struct file *file, const struct seq_operations *op)
57 WARN_ON(file->private_data);
59 p = kmem_cache_zalloc(seq_file_cache, GFP_KERNEL);
63 file->private_data = p;
68 // No refcounting: the lifetime of 'p' is constrained
69 // to the lifetime of the file.
73 * seq_files support lseek() and pread(). They do not implement
74 * write() at all, but we clear FMODE_PWRITE here for historical
77 * If a client of seq_files a) implements file.write() and b) wishes to
78 * support pwrite() then that client will need to implement its own
79 * file.open() which calls seq_open() and then sets FMODE_PWRITE.
81 file->f_mode &= ~FMODE_PWRITE;
84 EXPORT_SYMBOL(seq_open);
86 static int traverse(struct seq_file *m, loff_t offset)
93 m->count = m->from = 0;
98 m->buf = seq_buf_alloc(m->size = PAGE_SIZE);
102 p = m->op->start(m, &m->index);
107 error = m->op->show(m, p);
110 if (unlikely(error)) {
114 if (seq_has_overflowed(m))
116 p = m->op->next(m, p, &m->index);
117 if (pos + m->count > offset) {
118 m->from = offset - pos;
134 m->buf = seq_buf_alloc(m->size <<= 1);
135 return !m->buf ? -ENOMEM : -EAGAIN;
139 * seq_read - ->read() method for sequential files.
140 * @file: the file to read from
141 * @buf: the buffer to read to
142 * @size: the maximum number of bytes to read
143 * @ppos: the current position in the file
145 * Ready-made ->f_op->read()
147 ssize_t seq_read(struct file *file, char __user *buf, size_t size, loff_t *ppos)
149 struct seq_file *m = file->private_data;
155 mutex_lock(&m->lock);
158 * if request is to read from zero offset, reset iterator to first
159 * record as it might have been already advanced by previous requests
166 /* Don't assume *ppos is where we left it */
167 if (unlikely(*ppos != m->read_pos)) {
168 while ((err = traverse(m, *ppos)) == -EAGAIN)
171 /* With prejudice... */
181 /* grab buffer if we didn't have one */
183 m->buf = seq_buf_alloc(m->size = PAGE_SIZE);
187 /* if not empty - flush it first */
189 n = min(m->count, size);
190 err = copy_to_user(buf, m->buf + m->from, n);
201 /* we need at least one record in buffer */
203 p = m->op->start(m, &m->index);
208 err = m->op->show(m, p);
213 if (unlikely(!m->count)) {
214 p = m->op->next(m, p, &m->index);
217 if (m->count < m->size)
222 m->buf = seq_buf_alloc(m->size <<= 1);
225 p = m->op->start(m, &m->index);
231 /* they want more? let's try to get some more */
233 size_t offs = m->count;
234 loff_t pos = m->index;
236 p = m->op->next(m, p, &m->index);
237 if (pos == m->index) {
238 pr_info_ratelimited("buggy .next function %ps did not update position index\n",
242 if (!p || IS_ERR(p)) {
246 if (m->count >= size)
248 err = m->op->show(m, p);
249 if (seq_has_overflowed(m) || err) {
251 if (likely(err <= 0))
256 n = min(m->count, size);
257 err = copy_to_user(buf, m->buf, n);
268 m->read_pos += copied;
270 mutex_unlock(&m->lock);
279 EXPORT_SYMBOL(seq_read);
282 * seq_lseek - ->llseek() method for sequential files.
283 * @file: the file in question
284 * @offset: new position
285 * @whence: 0 for absolute, 1 for relative position
287 * Ready-made ->f_op->llseek()
289 loff_t seq_lseek(struct file *file, loff_t offset, int whence)
291 struct seq_file *m = file->private_data;
292 loff_t retval = -EINVAL;
294 mutex_lock(&m->lock);
297 offset += file->f_pos;
303 if (offset != m->read_pos) {
304 while ((retval = traverse(m, offset)) == -EAGAIN)
307 /* with extreme prejudice... */
313 m->read_pos = offset;
314 retval = file->f_pos = offset;
317 file->f_pos = offset;
320 mutex_unlock(&m->lock);
323 EXPORT_SYMBOL(seq_lseek);
326 * seq_release - free the structures associated with sequential file.
327 * @file: file in question
330 * Frees the structures associated with sequential file; can be used
331 * as ->f_op->release() if you don't have private data to destroy.
333 int seq_release(struct inode *inode, struct file *file)
335 struct seq_file *m = file->private_data;
337 kmem_cache_free(seq_file_cache, m);
340 EXPORT_SYMBOL(seq_release);
343 * seq_escape - print string into buffer, escaping some characters
346 * @esc: set of characters that need escaping
348 * Puts string into buffer, replacing each occurrence of character from
349 * @esc with usual octal escape.
350 * Use seq_has_overflowed() to check for errors.
352 void seq_escape(struct seq_file *m, const char *s, const char *esc)
355 size_t size = seq_get_buf(m, &buf);
358 ret = string_escape_str(s, buf, size, ESCAPE_OCTAL, esc);
359 seq_commit(m, ret < size ? ret : -1);
361 EXPORT_SYMBOL(seq_escape);
363 void seq_escape_mem_ascii(struct seq_file *m, const char *src, size_t isz)
366 size_t size = seq_get_buf(m, &buf);
369 ret = string_escape_mem_ascii(src, isz, buf, size);
370 seq_commit(m, ret < size ? ret : -1);
372 EXPORT_SYMBOL(seq_escape_mem_ascii);
374 void seq_vprintf(struct seq_file *m, const char *f, va_list args)
378 if (m->count < m->size) {
379 len = vsnprintf(m->buf + m->count, m->size - m->count, f, args);
380 if (m->count + len < m->size) {
387 EXPORT_SYMBOL(seq_vprintf);
389 void seq_printf(struct seq_file *m, const char *f, ...)
394 seq_vprintf(m, f, args);
397 EXPORT_SYMBOL(seq_printf);
400 * mangle_path - mangle and copy path to buffer beginning
402 * @p: beginning of path in above buffer
403 * @esc: set of characters that need escaping
405 * Copy the path from @p to @s, replacing each occurrence of character from
406 * @esc with usual octal escape.
407 * Returns pointer past last written character in @s, or NULL in case of
410 char *mangle_path(char *s, const char *p, const char *esc)
416 } else if (!strchr(esc, c)) {
418 } else if (s + 4 > p) {
422 *s++ = '0' + ((c & 0300) >> 6);
423 *s++ = '0' + ((c & 070) >> 3);
424 *s++ = '0' + (c & 07);
429 EXPORT_SYMBOL(mangle_path);
432 * seq_path - seq_file interface to print a pathname
433 * @m: the seq_file handle
434 * @path: the struct path to print
435 * @esc: set of characters to escape in the output
437 * return the absolute path of 'path', as represented by the
438 * dentry / mnt pair in the path parameter.
440 int seq_path(struct seq_file *m, const struct path *path, const char *esc)
443 size_t size = seq_get_buf(m, &buf);
447 char *p = d_path(path, buf, size);
449 char *end = mangle_path(buf, p, esc);
458 EXPORT_SYMBOL(seq_path);
461 * seq_file_path - seq_file interface to print a pathname of a file
462 * @m: the seq_file handle
463 * @file: the struct file to print
464 * @esc: set of characters to escape in the output
466 * return the absolute path to the file.
468 int seq_file_path(struct seq_file *m, struct file *file, const char *esc)
470 return seq_path(m, &file->f_path, esc);
472 EXPORT_SYMBOL(seq_file_path);
475 * Same as seq_path, but relative to supplied root.
477 int seq_path_root(struct seq_file *m, const struct path *path,
478 const struct path *root, const char *esc)
481 size_t size = seq_get_buf(m, &buf);
482 int res = -ENAMETOOLONG;
487 p = __d_path(path, root, buf, size);
492 char *end = mangle_path(buf, p, esc);
501 return res < 0 && res != -ENAMETOOLONG ? res : 0;
505 * returns the path of the 'dentry' from the root of its filesystem.
507 int seq_dentry(struct seq_file *m, struct dentry *dentry, const char *esc)
510 size_t size = seq_get_buf(m, &buf);
514 char *p = dentry_path(dentry, buf, size);
516 char *end = mangle_path(buf, p, esc);
525 EXPORT_SYMBOL(seq_dentry);
527 static void *single_start(struct seq_file *p, loff_t *pos)
529 return NULL + (*pos == 0);
532 static void *single_next(struct seq_file *p, void *v, loff_t *pos)
538 static void single_stop(struct seq_file *p, void *v)
542 int single_open(struct file *file, int (*show)(struct seq_file *, void *),
545 struct seq_operations *op = kmalloc(sizeof(*op), GFP_KERNEL_ACCOUNT);
549 op->start = single_start;
550 op->next = single_next;
551 op->stop = single_stop;
553 res = seq_open(file, op);
555 ((struct seq_file *)file->private_data)->private = data;
561 EXPORT_SYMBOL(single_open);
563 int single_open_size(struct file *file, int (*show)(struct seq_file *, void *),
564 void *data, size_t size)
566 char *buf = seq_buf_alloc(size);
570 ret = single_open(file, show, data);
575 ((struct seq_file *)file->private_data)->buf = buf;
576 ((struct seq_file *)file->private_data)->size = size;
579 EXPORT_SYMBOL(single_open_size);
581 int single_release(struct inode *inode, struct file *file)
583 const struct seq_operations *op = ((struct seq_file *)file->private_data)->op;
584 int res = seq_release(inode, file);
588 EXPORT_SYMBOL(single_release);
590 int seq_release_private(struct inode *inode, struct file *file)
592 struct seq_file *seq = file->private_data;
596 return seq_release(inode, file);
598 EXPORT_SYMBOL(seq_release_private);
600 void *__seq_open_private(struct file *f, const struct seq_operations *ops,
605 struct seq_file *seq;
607 private = kzalloc(psize, GFP_KERNEL_ACCOUNT);
611 rc = seq_open(f, ops);
615 seq = f->private_data;
616 seq->private = private;
624 EXPORT_SYMBOL(__seq_open_private);
626 int seq_open_private(struct file *filp, const struct seq_operations *ops,
629 return __seq_open_private(filp, ops, psize) ? 0 : -ENOMEM;
631 EXPORT_SYMBOL(seq_open_private);
633 void seq_putc(struct seq_file *m, char c)
635 if (m->count >= m->size)
638 m->buf[m->count++] = c;
640 EXPORT_SYMBOL(seq_putc);
642 void seq_puts(struct seq_file *m, const char *s)
646 if (m->count + len >= m->size) {
650 memcpy(m->buf + m->count, s, len);
653 EXPORT_SYMBOL(seq_puts);
656 * A helper routine for putting decimal numbers without rich format of printf().
657 * only 'unsigned long long' is supported.
658 * @m: seq_file identifying the buffer to which data should be written
659 * @delimiter: a string which is printed before the number
661 * @width: a minimum field width
663 * This routine will put strlen(delimiter) + number into seq_filed.
664 * This routine is very quick when you show lots of numbers.
665 * In usual cases, it will be better to use seq_printf(). It's easier to read.
667 void seq_put_decimal_ull_width(struct seq_file *m, const char *delimiter,
668 unsigned long long num, unsigned int width)
672 if (m->count + 2 >= m->size) /* we'll write 2 bytes at least */
675 if (delimiter && delimiter[0]) {
676 if (delimiter[1] == 0)
677 seq_putc(m, delimiter[0]);
679 seq_puts(m, delimiter);
685 if (m->count + width >= m->size)
688 len = num_to_str(m->buf + m->count, m->size - m->count, num, width);
699 void seq_put_decimal_ull(struct seq_file *m, const char *delimiter,
700 unsigned long long num)
702 return seq_put_decimal_ull_width(m, delimiter, num, 0);
704 EXPORT_SYMBOL(seq_put_decimal_ull);
707 * seq_put_hex_ll - put a number in hexadecimal notation
708 * @m: seq_file identifying the buffer to which data should be written
709 * @delimiter: a string which is printed before the number
711 * @width: a minimum field width
713 * seq_put_hex_ll(m, "", v, 8) is equal to seq_printf(m, "%08llx", v)
715 * This routine is very quick when you show lots of numbers.
716 * In usual cases, it will be better to use seq_printf(). It's easier to read.
718 void seq_put_hex_ll(struct seq_file *m, const char *delimiter,
719 unsigned long long v, unsigned int width)
724 if (delimiter && delimiter[0]) {
725 if (delimiter[1] == 0)
726 seq_putc(m, delimiter[0]);
728 seq_puts(m, delimiter);
731 /* If x is 0, the result of __builtin_clzll is undefined */
735 len = (sizeof(v) * 8 - __builtin_clzll(v) + 3) / 4;
740 if (m->count + len > m->size) {
745 for (i = len - 1; i >= 0; i--) {
746 m->buf[m->count + i] = hex_asc[0xf & v];
752 void seq_put_decimal_ll(struct seq_file *m, const char *delimiter, long long num)
756 if (m->count + 3 >= m->size) /* we'll write 2 bytes at least */
759 if (delimiter && delimiter[0]) {
760 if (delimiter[1] == 0)
761 seq_putc(m, delimiter[0]);
763 seq_puts(m, delimiter);
766 if (m->count + 2 >= m->size)
770 m->buf[m->count++] = '-';
775 m->buf[m->count++] = num + '0';
779 len = num_to_str(m->buf + m->count, m->size - m->count, num, 0);
789 EXPORT_SYMBOL(seq_put_decimal_ll);
792 * seq_write - write arbitrary data to buffer
793 * @seq: seq_file identifying the buffer to which data should be written
794 * @data: data address
795 * @len: number of bytes
797 * Return 0 on success, non-zero otherwise.
799 int seq_write(struct seq_file *seq, const void *data, size_t len)
801 if (seq->count + len < seq->size) {
802 memcpy(seq->buf + seq->count, data, len);
806 seq_set_overflow(seq);
809 EXPORT_SYMBOL(seq_write);
812 * seq_pad - write padding spaces to buffer
813 * @m: seq_file identifying the buffer to which data should be written
814 * @c: the byte to append after padding if non-zero
816 void seq_pad(struct seq_file *m, char c)
818 int size = m->pad_until - m->count;
820 if (size + m->count > m->size) {
824 memset(m->buf + m->count, ' ', size);
830 EXPORT_SYMBOL(seq_pad);
832 /* A complete analogue of print_hex_dump() */
833 void seq_hex_dump(struct seq_file *m, const char *prefix_str, int prefix_type,
834 int rowsize, int groupsize, const void *buf, size_t len,
838 int i, linelen, remaining = len;
843 if (rowsize != 16 && rowsize != 32)
846 for (i = 0; i < len && !seq_has_overflowed(m); i += rowsize) {
847 linelen = min(remaining, rowsize);
848 remaining -= rowsize;
850 switch (prefix_type) {
851 case DUMP_PREFIX_ADDRESS:
852 seq_printf(m, "%s%p: ", prefix_str, ptr + i);
854 case DUMP_PREFIX_OFFSET:
855 seq_printf(m, "%s%.8x: ", prefix_str, i);
858 seq_printf(m, "%s", prefix_str);
862 size = seq_get_buf(m, &buffer);
863 ret = hex_dump_to_buffer(ptr + i, linelen, rowsize, groupsize,
864 buffer, size, ascii);
865 seq_commit(m, ret < size ? ret : -1);
870 EXPORT_SYMBOL(seq_hex_dump);
872 struct list_head *seq_list_start(struct list_head *head, loff_t pos)
874 struct list_head *lh;
876 list_for_each(lh, head)
882 EXPORT_SYMBOL(seq_list_start);
884 struct list_head *seq_list_start_head(struct list_head *head, loff_t pos)
889 return seq_list_start(head, pos - 1);
891 EXPORT_SYMBOL(seq_list_start_head);
893 struct list_head *seq_list_next(void *v, struct list_head *head, loff_t *ppos)
895 struct list_head *lh;
897 lh = ((struct list_head *)v)->next;
899 return lh == head ? NULL : lh;
901 EXPORT_SYMBOL(seq_list_next);
904 * seq_hlist_start - start an iteration of a hlist
905 * @head: the head of the hlist
906 * @pos: the start position of the sequence
908 * Called at seq_file->op->start().
910 struct hlist_node *seq_hlist_start(struct hlist_head *head, loff_t pos)
912 struct hlist_node *node;
914 hlist_for_each(node, head)
919 EXPORT_SYMBOL(seq_hlist_start);
922 * seq_hlist_start_head - start an iteration of a hlist
923 * @head: the head of the hlist
924 * @pos: the start position of the sequence
926 * Called at seq_file->op->start(). Call this function if you want to
927 * print a header at the top of the output.
929 struct hlist_node *seq_hlist_start_head(struct hlist_head *head, loff_t pos)
932 return SEQ_START_TOKEN;
934 return seq_hlist_start(head, pos - 1);
936 EXPORT_SYMBOL(seq_hlist_start_head);
939 * seq_hlist_next - move to the next position of the hlist
940 * @v: the current iterator
941 * @head: the head of the hlist
942 * @ppos: the current position
944 * Called at seq_file->op->next().
946 struct hlist_node *seq_hlist_next(void *v, struct hlist_head *head,
949 struct hlist_node *node = v;
952 if (v == SEQ_START_TOKEN)
957 EXPORT_SYMBOL(seq_hlist_next);
960 * seq_hlist_start_rcu - start an iteration of a hlist protected by RCU
961 * @head: the head of the hlist
962 * @pos: the start position of the sequence
964 * Called at seq_file->op->start().
966 * This list-traversal primitive may safely run concurrently with
967 * the _rcu list-mutation primitives such as hlist_add_head_rcu()
968 * as long as the traversal is guarded by rcu_read_lock().
970 struct hlist_node *seq_hlist_start_rcu(struct hlist_head *head,
973 struct hlist_node *node;
975 __hlist_for_each_rcu(node, head)
980 EXPORT_SYMBOL(seq_hlist_start_rcu);
983 * seq_hlist_start_head_rcu - start an iteration of a hlist protected by RCU
984 * @head: the head of the hlist
985 * @pos: the start position of the sequence
987 * Called at seq_file->op->start(). Call this function if you want to
988 * print a header at the top of the output.
990 * This list-traversal primitive may safely run concurrently with
991 * the _rcu list-mutation primitives such as hlist_add_head_rcu()
992 * as long as the traversal is guarded by rcu_read_lock().
994 struct hlist_node *seq_hlist_start_head_rcu(struct hlist_head *head,
998 return SEQ_START_TOKEN;
1000 return seq_hlist_start_rcu(head, pos - 1);
1002 EXPORT_SYMBOL(seq_hlist_start_head_rcu);
1005 * seq_hlist_next_rcu - move to the next position of the hlist protected by RCU
1006 * @v: the current iterator
1007 * @head: the head of the hlist
1008 * @ppos: the current position
1010 * Called at seq_file->op->next().
1012 * This list-traversal primitive may safely run concurrently with
1013 * the _rcu list-mutation primitives such as hlist_add_head_rcu()
1014 * as long as the traversal is guarded by rcu_read_lock().
1016 struct hlist_node *seq_hlist_next_rcu(void *v,
1017 struct hlist_head *head,
1020 struct hlist_node *node = v;
1023 if (v == SEQ_START_TOKEN)
1024 return rcu_dereference(head->first);
1026 return rcu_dereference(node->next);
1028 EXPORT_SYMBOL(seq_hlist_next_rcu);
1031 * seq_hlist_start_precpu - start an iteration of a percpu hlist array
1032 * @head: pointer to percpu array of struct hlist_heads
1033 * @cpu: pointer to cpu "cursor"
1034 * @pos: start position of sequence
1036 * Called at seq_file->op->start().
1039 seq_hlist_start_percpu(struct hlist_head __percpu *head, int *cpu, loff_t pos)
1041 struct hlist_node *node;
1043 for_each_possible_cpu(*cpu) {
1044 hlist_for_each(node, per_cpu_ptr(head, *cpu)) {
1051 EXPORT_SYMBOL(seq_hlist_start_percpu);
1054 * seq_hlist_next_percpu - move to the next position of the percpu hlist array
1055 * @v: pointer to current hlist_node
1056 * @head: pointer to percpu array of struct hlist_heads
1057 * @cpu: pointer to cpu "cursor"
1058 * @pos: start position of sequence
1060 * Called at seq_file->op->next().
1063 seq_hlist_next_percpu(void *v, struct hlist_head __percpu *head,
1064 int *cpu, loff_t *pos)
1066 struct hlist_node *node = v;
1073 for (*cpu = cpumask_next(*cpu, cpu_possible_mask); *cpu < nr_cpu_ids;
1074 *cpu = cpumask_next(*cpu, cpu_possible_mask)) {
1075 struct hlist_head *bucket = per_cpu_ptr(head, *cpu);
1077 if (!hlist_empty(bucket))
1078 return bucket->first;
1082 EXPORT_SYMBOL(seq_hlist_next_percpu);
1084 void __init seq_file_init(void)
1086 seq_file_cache = KMEM_CACHE(seq_file, SLAB_ACCOUNT|SLAB_PANIC);