GNU Linux-libre 4.19.264-gnu1
[releases.git] / kernel / trace / blktrace.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
4  *
5  */
6
7 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
8
9 #include <linux/kernel.h>
10 #include <linux/blkdev.h>
11 #include <linux/blktrace_api.h>
12 #include <linux/percpu.h>
13 #include <linux/init.h>
14 #include <linux/mutex.h>
15 #include <linux/slab.h>
16 #include <linux/debugfs.h>
17 #include <linux/export.h>
18 #include <linux/time.h>
19 #include <linux/uaccess.h>
20 #include <linux/list.h>
21 #include <linux/blk-cgroup.h>
22
23 #include "../../block/blk.h"
24
25 #include <trace/events/block.h>
26
27 #include "trace_output.h"
28
29 #ifdef CONFIG_BLK_DEV_IO_TRACE
30
31 static unsigned int blktrace_seq __read_mostly = 1;
32
33 static struct trace_array *blk_tr;
34 static bool blk_tracer_enabled __read_mostly;
35
36 static LIST_HEAD(running_trace_list);
37 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(running_trace_lock);
38
39 /* Select an alternative, minimalistic output than the original one */
40 #define TRACE_BLK_OPT_CLASSIC   0x1
41 #define TRACE_BLK_OPT_CGROUP    0x2
42 #define TRACE_BLK_OPT_CGNAME    0x4
43
44 static struct tracer_opt blk_tracer_opts[] = {
45         /* Default disable the minimalistic output */
46         { TRACER_OPT(blk_classic, TRACE_BLK_OPT_CLASSIC) },
47 #ifdef CONFIG_BLK_CGROUP
48         { TRACER_OPT(blk_cgroup, TRACE_BLK_OPT_CGROUP) },
49         { TRACER_OPT(blk_cgname, TRACE_BLK_OPT_CGNAME) },
50 #endif
51         { }
52 };
53
54 static struct tracer_flags blk_tracer_flags = {
55         .val  = 0,
56         .opts = blk_tracer_opts,
57 };
58
59 /* Global reference count of probes */
60 static DEFINE_MUTEX(blk_probe_mutex);
61 static int blk_probes_ref;
62
63 static void blk_register_tracepoints(void);
64 static void blk_unregister_tracepoints(void);
65
66 /*
67  * Send out a notify message.
68  */
69 static void trace_note(struct blk_trace *bt, pid_t pid, int action,
70                        const void *data, size_t len,
71                        union kernfs_node_id *cgid)
72 {
73         struct blk_io_trace *t;
74         struct ring_buffer_event *event = NULL;
75         struct ring_buffer *buffer = NULL;
76         int pc = 0;
77         int cpu = smp_processor_id();
78         bool blk_tracer = blk_tracer_enabled;
79         ssize_t cgid_len = cgid ? sizeof(*cgid) : 0;
80
81         if (blk_tracer) {
82                 buffer = blk_tr->trace_buffer.buffer;
83                 pc = preempt_count();
84                 event = trace_buffer_lock_reserve(buffer, TRACE_BLK,
85                                                   sizeof(*t) + len + cgid_len,
86                                                   0, pc);
87                 if (!event)
88                         return;
89                 t = ring_buffer_event_data(event);
90                 goto record_it;
91         }
92
93         if (!bt->rchan)
94                 return;
95
96         t = relay_reserve(bt->rchan, sizeof(*t) + len + cgid_len);
97         if (t) {
98                 t->magic = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION;
99                 t->time = ktime_to_ns(ktime_get());
100 record_it:
101                 t->device = bt->dev;
102                 t->action = action | (cgid ? __BLK_TN_CGROUP : 0);
103                 t->pid = pid;
104                 t->cpu = cpu;
105                 t->pdu_len = len + cgid_len;
106                 if (cgid)
107                         memcpy((void *)t + sizeof(*t), cgid, cgid_len);
108                 memcpy((void *) t + sizeof(*t) + cgid_len, data, len);
109
110                 if (blk_tracer)
111                         trace_buffer_unlock_commit(blk_tr, buffer, event, 0, pc);
112         }
113 }
114
115 /*
116  * Send out a notify for this process, if we haven't done so since a trace
117  * started
118  */
119 static void trace_note_tsk(struct task_struct *tsk)
120 {
121         unsigned long flags;
122         struct blk_trace *bt;
123
124         tsk->btrace_seq = blktrace_seq;
125         spin_lock_irqsave(&running_trace_lock, flags);
126         list_for_each_entry(bt, &running_trace_list, running_list) {
127                 trace_note(bt, tsk->pid, BLK_TN_PROCESS, tsk->comm,
128                            sizeof(tsk->comm), NULL);
129         }
130         spin_unlock_irqrestore(&running_trace_lock, flags);
131 }
132
133 static void trace_note_time(struct blk_trace *bt)
134 {
135         struct timespec64 now;
136         unsigned long flags;
137         u32 words[2];
138
139         /* need to check user space to see if this breaks in y2038 or y2106 */
140         ktime_get_real_ts64(&now);
141         words[0] = (u32)now.tv_sec;
142         words[1] = now.tv_nsec;
143
144         local_irq_save(flags);
145         trace_note(bt, 0, BLK_TN_TIMESTAMP, words, sizeof(words), NULL);
146         local_irq_restore(flags);
147 }
148
149 void __trace_note_message(struct blk_trace *bt, struct blkcg *blkcg,
150         const char *fmt, ...)
151 {
152         int n;
153         va_list args;
154         unsigned long flags;
155         char *buf;
156
157         if (unlikely(bt->trace_state != Blktrace_running &&
158                      !blk_tracer_enabled))
159                 return;
160
161         /*
162          * If the BLK_TC_NOTIFY action mask isn't set, don't send any note
163          * message to the trace.
164          */
165         if (!(bt->act_mask & BLK_TC_NOTIFY))
166                 return;
167
168         local_irq_save(flags);
169         buf = this_cpu_ptr(bt->msg_data);
170         va_start(args, fmt);
171         n = vscnprintf(buf, BLK_TN_MAX_MSG, fmt, args);
172         va_end(args);
173
174         if (!(blk_tracer_flags.val & TRACE_BLK_OPT_CGROUP))
175                 blkcg = NULL;
176 #ifdef CONFIG_BLK_CGROUP
177         trace_note(bt, 0, BLK_TN_MESSAGE, buf, n,
178                 blkcg ? cgroup_get_kernfs_id(blkcg->css.cgroup) : NULL);
179 #else
180         trace_note(bt, 0, BLK_TN_MESSAGE, buf, n, NULL);
181 #endif
182         local_irq_restore(flags);
183 }
184 EXPORT_SYMBOL_GPL(__trace_note_message);
185
186 static int act_log_check(struct blk_trace *bt, u32 what, sector_t sector,
187                          pid_t pid)
188 {
189         if (((bt->act_mask << BLK_TC_SHIFT) & what) == 0)
190                 return 1;
191         if (sector && (sector < bt->start_lba || sector > bt->end_lba))
192                 return 1;
193         if (bt->pid && pid != bt->pid)
194                 return 1;
195
196         return 0;
197 }
198
199 /*
200  * Data direction bit lookup
201  */
202 static const u32 ddir_act[2] = { BLK_TC_ACT(BLK_TC_READ),
203                                  BLK_TC_ACT(BLK_TC_WRITE) };
204
205 #define BLK_TC_RAHEAD           BLK_TC_AHEAD
206 #define BLK_TC_PREFLUSH         BLK_TC_FLUSH
207
208 /* The ilog2() calls fall out because they're constant */
209 #define MASK_TC_BIT(rw, __name) ((rw & REQ_ ## __name) << \
210           (ilog2(BLK_TC_ ## __name) + BLK_TC_SHIFT - __REQ_ ## __name))
211
212 /*
213  * The worker for the various blk_add_trace*() types. Fills out a
214  * blk_io_trace structure and places it in a per-cpu subbuffer.
215  */
216 static void __blk_add_trace(struct blk_trace *bt, sector_t sector, int bytes,
217                      int op, int op_flags, u32 what, int error, int pdu_len,
218                      void *pdu_data, union kernfs_node_id *cgid)
219 {
220         struct task_struct *tsk = current;
221         struct ring_buffer_event *event = NULL;
222         struct ring_buffer *buffer = NULL;
223         struct blk_io_trace *t;
224         unsigned long flags = 0;
225         unsigned long *sequence;
226         pid_t pid;
227         int cpu, pc = 0;
228         bool blk_tracer = blk_tracer_enabled;
229         ssize_t cgid_len = cgid ? sizeof(*cgid) : 0;
230
231         if (unlikely(bt->trace_state != Blktrace_running && !blk_tracer))
232                 return;
233
234         what |= ddir_act[op_is_write(op) ? WRITE : READ];
235         what |= MASK_TC_BIT(op_flags, SYNC);
236         what |= MASK_TC_BIT(op_flags, RAHEAD);
237         what |= MASK_TC_BIT(op_flags, META);
238         what |= MASK_TC_BIT(op_flags, PREFLUSH);
239         what |= MASK_TC_BIT(op_flags, FUA);
240         if (op == REQ_OP_DISCARD || op == REQ_OP_SECURE_ERASE)
241                 what |= BLK_TC_ACT(BLK_TC_DISCARD);
242         if (op == REQ_OP_FLUSH)
243                 what |= BLK_TC_ACT(BLK_TC_FLUSH);
244         if (cgid)
245                 what |= __BLK_TA_CGROUP;
246
247         pid = tsk->pid;
248         if (act_log_check(bt, what, sector, pid))
249                 return;
250         cpu = raw_smp_processor_id();
251
252         if (blk_tracer) {
253                 tracing_record_cmdline(current);
254
255                 buffer = blk_tr->trace_buffer.buffer;
256                 pc = preempt_count();
257                 event = trace_buffer_lock_reserve(buffer, TRACE_BLK,
258                                                   sizeof(*t) + pdu_len + cgid_len,
259                                                   0, pc);
260                 if (!event)
261                         return;
262                 t = ring_buffer_event_data(event);
263                 goto record_it;
264         }
265
266         if (unlikely(tsk->btrace_seq != blktrace_seq))
267                 trace_note_tsk(tsk);
268
269         /*
270          * A word about the locking here - we disable interrupts to reserve
271          * some space in the relay per-cpu buffer, to prevent an irq
272          * from coming in and stepping on our toes.
273          */
274         local_irq_save(flags);
275         t = relay_reserve(bt->rchan, sizeof(*t) + pdu_len + cgid_len);
276         if (t) {
277                 sequence = per_cpu_ptr(bt->sequence, cpu);
278
279                 t->magic = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION;
280                 t->sequence = ++(*sequence);
281                 t->time = ktime_to_ns(ktime_get());
282 record_it:
283                 /*
284                  * These two are not needed in ftrace as they are in the
285                  * generic trace_entry, filled by tracing_generic_entry_update,
286                  * but for the trace_event->bin() synthesizer benefit we do it
287                  * here too.
288                  */
289                 t->cpu = cpu;
290                 t->pid = pid;
291
292                 t->sector = sector;
293                 t->bytes = bytes;
294                 t->action = what;
295                 t->device = bt->dev;
296                 t->error = error;
297                 t->pdu_len = pdu_len + cgid_len;
298
299                 if (cgid_len)
300                         memcpy((void *)t + sizeof(*t), cgid, cgid_len);
301                 if (pdu_len)
302                         memcpy((void *)t + sizeof(*t) + cgid_len, pdu_data, pdu_len);
303
304                 if (blk_tracer) {
305                         trace_buffer_unlock_commit(blk_tr, buffer, event, 0, pc);
306                         return;
307                 }
308         }
309
310         local_irq_restore(flags);
311 }
312
313 static void blk_trace_free(struct blk_trace *bt)
314 {
315         debugfs_remove(bt->msg_file);
316         debugfs_remove(bt->dropped_file);
317         relay_close(bt->rchan);
318         debugfs_remove(bt->dir);
319         free_percpu(bt->sequence);
320         free_percpu(bt->msg_data);
321         kfree(bt);
322 }
323
324 static void get_probe_ref(void)
325 {
326         mutex_lock(&blk_probe_mutex);
327         if (++blk_probes_ref == 1)
328                 blk_register_tracepoints();
329         mutex_unlock(&blk_probe_mutex);
330 }
331
332 static void put_probe_ref(void)
333 {
334         mutex_lock(&blk_probe_mutex);
335         if (!--blk_probes_ref)
336                 blk_unregister_tracepoints();
337         mutex_unlock(&blk_probe_mutex);
338 }
339
340 static void blk_trace_cleanup(struct blk_trace *bt)
341 {
342         synchronize_rcu();
343         blk_trace_free(bt);
344         put_probe_ref();
345 }
346
347 static int __blk_trace_remove(struct request_queue *q)
348 {
349         struct blk_trace *bt;
350
351         bt = xchg(&q->blk_trace, NULL);
352         if (!bt)
353                 return -EINVAL;
354
355         if (bt->trace_state != Blktrace_running)
356                 blk_trace_cleanup(bt);
357
358         return 0;
359 }
360
361 int blk_trace_remove(struct request_queue *q)
362 {
363         int ret;
364
365         mutex_lock(&q->blk_trace_mutex);
366         ret = __blk_trace_remove(q);
367         mutex_unlock(&q->blk_trace_mutex);
368
369         return ret;
370 }
371 EXPORT_SYMBOL_GPL(blk_trace_remove);
372
373 static ssize_t blk_dropped_read(struct file *filp, char __user *buffer,
374                                 size_t count, loff_t *ppos)
375 {
376         struct blk_trace *bt = filp->private_data;
377         char buf[16];
378
379         snprintf(buf, sizeof(buf), "%u\n", atomic_read(&bt->dropped));
380
381         return simple_read_from_buffer(buffer, count, ppos, buf, strlen(buf));
382 }
383
384 static const struct file_operations blk_dropped_fops = {
385         .owner =        THIS_MODULE,
386         .open =         simple_open,
387         .read =         blk_dropped_read,
388         .llseek =       default_llseek,
389 };
390
391 static ssize_t blk_msg_write(struct file *filp, const char __user *buffer,
392                                 size_t count, loff_t *ppos)
393 {
394         char *msg;
395         struct blk_trace *bt;
396
397         if (count >= BLK_TN_MAX_MSG)
398                 return -EINVAL;
399
400         msg = memdup_user_nul(buffer, count);
401         if (IS_ERR(msg))
402                 return PTR_ERR(msg);
403
404         bt = filp->private_data;
405         __trace_note_message(bt, NULL, "%s", msg);
406         kfree(msg);
407
408         return count;
409 }
410
411 static const struct file_operations blk_msg_fops = {
412         .owner =        THIS_MODULE,
413         .open =         simple_open,
414         .write =        blk_msg_write,
415         .llseek =       noop_llseek,
416 };
417
418 /*
419  * Keep track of how many times we encountered a full subbuffer, to aid
420  * the user space app in telling how many lost events there were.
421  */
422 static int blk_subbuf_start_callback(struct rchan_buf *buf, void *subbuf,
423                                      void *prev_subbuf, size_t prev_padding)
424 {
425         struct blk_trace *bt;
426
427         if (!relay_buf_full(buf))
428                 return 1;
429
430         bt = buf->chan->private_data;
431         atomic_inc(&bt->dropped);
432         return 0;
433 }
434
435 static int blk_remove_buf_file_callback(struct dentry *dentry)
436 {
437         debugfs_remove(dentry);
438
439         return 0;
440 }
441
442 static struct dentry *blk_create_buf_file_callback(const char *filename,
443                                                    struct dentry *parent,
444                                                    umode_t mode,
445                                                    struct rchan_buf *buf,
446                                                    int *is_global)
447 {
448         return debugfs_create_file(filename, mode, parent, buf,
449                                         &relay_file_operations);
450 }
451
452 static struct rchan_callbacks blk_relay_callbacks = {
453         .subbuf_start           = blk_subbuf_start_callback,
454         .create_buf_file        = blk_create_buf_file_callback,
455         .remove_buf_file        = blk_remove_buf_file_callback,
456 };
457
458 static void blk_trace_setup_lba(struct blk_trace *bt,
459                                 struct block_device *bdev)
460 {
461         struct hd_struct *part = NULL;
462
463         if (bdev)
464                 part = bdev->bd_part;
465
466         if (part) {
467                 bt->start_lba = part->start_sect;
468                 bt->end_lba = part->start_sect + part->nr_sects;
469         } else {
470                 bt->start_lba = 0;
471                 bt->end_lba = -1ULL;
472         }
473 }
474
475 /*
476  * Setup everything required to start tracing
477  */
478 static int do_blk_trace_setup(struct request_queue *q, char *name, dev_t dev,
479                               struct block_device *bdev,
480                               struct blk_user_trace_setup *buts)
481 {
482         struct blk_trace *bt = NULL;
483         struct dentry *dir = NULL;
484         int ret;
485
486         if (!buts->buf_size || !buts->buf_nr)
487                 return -EINVAL;
488
489         if (!blk_debugfs_root)
490                 return -ENOENT;
491
492         strncpy(buts->name, name, BLKTRACE_BDEV_SIZE);
493         buts->name[BLKTRACE_BDEV_SIZE - 1] = '\0';
494
495         /*
496          * some device names have larger paths - convert the slashes
497          * to underscores for this to work as expected
498          */
499         strreplace(buts->name, '/', '_');
500
501         /*
502          * bdev can be NULL, as with scsi-generic, this is a helpful as
503          * we can be.
504          */
505         if (q->blk_trace) {
506                 pr_warn("Concurrent blktraces are not allowed on %s\n",
507                         buts->name);
508                 return -EBUSY;
509         }
510
511         bt = kzalloc(sizeof(*bt), GFP_KERNEL);
512         if (!bt)
513                 return -ENOMEM;
514
515         ret = -ENOMEM;
516         bt->sequence = alloc_percpu(unsigned long);
517         if (!bt->sequence)
518                 goto err;
519
520         bt->msg_data = __alloc_percpu(BLK_TN_MAX_MSG, __alignof__(char));
521         if (!bt->msg_data)
522                 goto err;
523
524 #ifdef CONFIG_BLK_DEBUG_FS
525         /*
526          * When tracing whole make_request drivers (multiqueue) block devices,
527          * reuse the existing debugfs directory created by the block layer on
528          * init. For request-based block devices, all partitions block devices,
529          * and scsi-generic block devices we create a temporary new debugfs
530          * directory that will be removed once the trace ends.
531          */
532         if (q->mq_ops && bdev && bdev == bdev->bd_contains)
533                 dir = q->debugfs_dir;
534         else
535 #endif
536                 bt->dir = dir = debugfs_create_dir(buts->name, blk_debugfs_root);
537         if (!dir)
538                 goto err;
539
540         /*
541          * As blktrace relies on debugfs for its interface the debugfs directory
542          * is required, contrary to the usual mantra of not checking for debugfs
543          * files or directories.
544          */
545         if (IS_ERR_OR_NULL(dir)) {
546                 pr_warn("debugfs_dir not present for %s so skipping\n",
547                         buts->name);
548                 ret = -ENOENT;
549                 goto err;
550         }
551
552         bt->dev = dev;
553         atomic_set(&bt->dropped, 0);
554         INIT_LIST_HEAD(&bt->running_list);
555
556         ret = -EIO;
557         bt->dropped_file = debugfs_create_file("dropped", 0444, dir, bt,
558                                                &blk_dropped_fops);
559         if (!bt->dropped_file)
560                 goto err;
561
562         bt->msg_file = debugfs_create_file("msg", 0222, dir, bt, &blk_msg_fops);
563         if (!bt->msg_file)
564                 goto err;
565
566         bt->rchan = relay_open("trace", dir, buts->buf_size,
567                                 buts->buf_nr, &blk_relay_callbacks, bt);
568         if (!bt->rchan)
569                 goto err;
570
571         bt->act_mask = buts->act_mask;
572         if (!bt->act_mask)
573                 bt->act_mask = (u16) -1;
574
575         blk_trace_setup_lba(bt, bdev);
576
577         /* overwrite with user settings */
578         if (buts->start_lba)
579                 bt->start_lba = buts->start_lba;
580         if (buts->end_lba)
581                 bt->end_lba = buts->end_lba;
582
583         bt->pid = buts->pid;
584         bt->trace_state = Blktrace_setup;
585
586         ret = -EBUSY;
587         if (cmpxchg(&q->blk_trace, NULL, bt))
588                 goto err;
589
590         get_probe_ref();
591
592         ret = 0;
593 err:
594         if (ret)
595                 blk_trace_free(bt);
596         return ret;
597 }
598
599 static int __blk_trace_setup(struct request_queue *q, char *name, dev_t dev,
600                              struct block_device *bdev, char __user *arg)
601 {
602         struct blk_user_trace_setup buts;
603         int ret;
604
605         ret = copy_from_user(&buts, arg, sizeof(buts));
606         if (ret)
607                 return -EFAULT;
608
609         ret = do_blk_trace_setup(q, name, dev, bdev, &buts);
610         if (ret)
611                 return ret;
612
613         if (copy_to_user(arg, &buts, sizeof(buts))) {
614                 __blk_trace_remove(q);
615                 return -EFAULT;
616         }
617         return 0;
618 }
619
620 int blk_trace_setup(struct request_queue *q, char *name, dev_t dev,
621                     struct block_device *bdev,
622                     char __user *arg)
623 {
624         int ret;
625
626         mutex_lock(&q->blk_trace_mutex);
627         ret = __blk_trace_setup(q, name, dev, bdev, arg);
628         mutex_unlock(&q->blk_trace_mutex);
629
630         return ret;
631 }
632 EXPORT_SYMBOL_GPL(blk_trace_setup);
633
634 #if defined(CONFIG_COMPAT) && defined(CONFIG_X86_64)
635 static int compat_blk_trace_setup(struct request_queue *q, char *name,
636                                   dev_t dev, struct block_device *bdev,
637                                   char __user *arg)
638 {
639         struct blk_user_trace_setup buts;
640         struct compat_blk_user_trace_setup cbuts;
641         int ret;
642
643         if (copy_from_user(&cbuts, arg, sizeof(cbuts)))
644                 return -EFAULT;
645
646         buts = (struct blk_user_trace_setup) {
647                 .act_mask = cbuts.act_mask,
648                 .buf_size = cbuts.buf_size,
649                 .buf_nr = cbuts.buf_nr,
650                 .start_lba = cbuts.start_lba,
651                 .end_lba = cbuts.end_lba,
652                 .pid = cbuts.pid,
653         };
654
655         ret = do_blk_trace_setup(q, name, dev, bdev, &buts);
656         if (ret)
657                 return ret;
658
659         if (copy_to_user(arg, &buts.name, ARRAY_SIZE(buts.name))) {
660                 __blk_trace_remove(q);
661                 return -EFAULT;
662         }
663
664         return 0;
665 }
666 #endif
667
668 static int __blk_trace_startstop(struct request_queue *q, int start)
669 {
670         int ret;
671         struct blk_trace *bt;
672
673         bt = rcu_dereference_protected(q->blk_trace,
674                                        lockdep_is_held(&q->blk_trace_mutex));
675         if (bt == NULL)
676                 return -EINVAL;
677
678         /*
679          * For starting a trace, we can transition from a setup or stopped
680          * trace. For stopping a trace, the state must be running
681          */
682         ret = -EINVAL;
683         if (start) {
684                 if (bt->trace_state == Blktrace_setup ||
685                     bt->trace_state == Blktrace_stopped) {
686                         blktrace_seq++;
687                         smp_mb();
688                         bt->trace_state = Blktrace_running;
689                         spin_lock_irq(&running_trace_lock);
690                         list_add(&bt->running_list, &running_trace_list);
691                         spin_unlock_irq(&running_trace_lock);
692
693                         trace_note_time(bt);
694                         ret = 0;
695                 }
696         } else {
697                 if (bt->trace_state == Blktrace_running) {
698                         bt->trace_state = Blktrace_stopped;
699                         spin_lock_irq(&running_trace_lock);
700                         list_del_init(&bt->running_list);
701                         spin_unlock_irq(&running_trace_lock);
702                         relay_flush(bt->rchan);
703                         ret = 0;
704                 }
705         }
706
707         return ret;
708 }
709
710 int blk_trace_startstop(struct request_queue *q, int start)
711 {
712         int ret;
713
714         mutex_lock(&q->blk_trace_mutex);
715         ret = __blk_trace_startstop(q, start);
716         mutex_unlock(&q->blk_trace_mutex);
717
718         return ret;
719 }
720 EXPORT_SYMBOL_GPL(blk_trace_startstop);
721
722 /*
723  * When reading or writing the blktrace sysfs files, the references to the
724  * opened sysfs or device files should prevent the underlying block device
725  * from being removed. So no further delete protection is really needed.
726  */
727
728 /**
729  * blk_trace_ioctl: - handle the ioctls associated with tracing
730  * @bdev:       the block device
731  * @cmd:        the ioctl cmd
732  * @arg:        the argument data, if any
733  *
734  **/
735 int blk_trace_ioctl(struct block_device *bdev, unsigned cmd, char __user *arg)
736 {
737         struct request_queue *q;
738         int ret, start = 0;
739         char b[BDEVNAME_SIZE];
740
741         q = bdev_get_queue(bdev);
742         if (!q)
743                 return -ENXIO;
744
745         mutex_lock(&q->blk_trace_mutex);
746
747         switch (cmd) {
748         case BLKTRACESETUP:
749                 bdevname(bdev, b);
750                 ret = __blk_trace_setup(q, b, bdev->bd_dev, bdev, arg);
751                 break;
752 #if defined(CONFIG_COMPAT) && defined(CONFIG_X86_64)
753         case BLKTRACESETUP32:
754                 bdevname(bdev, b);
755                 ret = compat_blk_trace_setup(q, b, bdev->bd_dev, bdev, arg);
756                 break;
757 #endif
758         case BLKTRACESTART:
759                 start = 1;
760         case BLKTRACESTOP:
761                 ret = __blk_trace_startstop(q, start);
762                 break;
763         case BLKTRACETEARDOWN:
764                 ret = __blk_trace_remove(q);
765                 break;
766         default:
767                 ret = -ENOTTY;
768                 break;
769         }
770
771         mutex_unlock(&q->blk_trace_mutex);
772         return ret;
773 }
774
775 /**
776  * blk_trace_shutdown: - stop and cleanup trace structures
777  * @q:    the request queue associated with the device
778  *
779  **/
780 void blk_trace_shutdown(struct request_queue *q)
781 {
782         mutex_lock(&q->blk_trace_mutex);
783         if (rcu_dereference_protected(q->blk_trace,
784                                       lockdep_is_held(&q->blk_trace_mutex))) {
785                 __blk_trace_startstop(q, 0);
786                 __blk_trace_remove(q);
787         }
788
789         mutex_unlock(&q->blk_trace_mutex);
790 }
791
792 #ifdef CONFIG_BLK_CGROUP
793 static union kernfs_node_id *
794 blk_trace_bio_get_cgid(struct request_queue *q, struct bio *bio)
795 {
796         struct blk_trace *bt;
797
798         /* We don't use the 'bt' value here except as an optimization... */
799         bt = rcu_dereference_protected(q->blk_trace, 1);
800         if (!bt || !(blk_tracer_flags.val & TRACE_BLK_OPT_CGROUP))
801                 return NULL;
802
803         if (!bio->bi_css)
804                 return NULL;
805         return cgroup_get_kernfs_id(bio->bi_css->cgroup);
806 }
807 #else
808 static union kernfs_node_id *
809 blk_trace_bio_get_cgid(struct request_queue *q, struct bio *bio)
810 {
811         return NULL;
812 }
813 #endif
814
815 static union kernfs_node_id *
816 blk_trace_request_get_cgid(struct request_queue *q, struct request *rq)
817 {
818         if (!rq->bio)
819                 return NULL;
820         /* Use the first bio */
821         return blk_trace_bio_get_cgid(q, rq->bio);
822 }
823
824 /*
825  * blktrace probes
826  */
827
828 /**
829  * blk_add_trace_rq - Add a trace for a request oriented action
830  * @rq:         the source request
831  * @error:      return status to log
832  * @nr_bytes:   number of completed bytes
833  * @what:       the action
834  * @cgid:       the cgroup info
835  *
836  * Description:
837  *     Records an action against a request. Will log the bio offset + size.
838  *
839  **/
840 static void blk_add_trace_rq(struct request *rq, int error,
841                              unsigned int nr_bytes, u32 what,
842                              union kernfs_node_id *cgid)
843 {
844         struct blk_trace *bt;
845
846         rcu_read_lock();
847         bt = rcu_dereference(rq->q->blk_trace);
848         if (likely(!bt)) {
849                 rcu_read_unlock();
850                 return;
851         }
852
853         if (blk_rq_is_passthrough(rq))
854                 what |= BLK_TC_ACT(BLK_TC_PC);
855         else
856                 what |= BLK_TC_ACT(BLK_TC_FS);
857
858         __blk_add_trace(bt, blk_rq_trace_sector(rq), nr_bytes, req_op(rq),
859                         rq->cmd_flags, what, error, 0, NULL, cgid);
860         rcu_read_unlock();
861 }
862
863 static void blk_add_trace_rq_insert(void *ignore,
864                                     struct request_queue *q, struct request *rq)
865 {
866         blk_add_trace_rq(rq, 0, blk_rq_bytes(rq), BLK_TA_INSERT,
867                          blk_trace_request_get_cgid(q, rq));
868 }
869
870 static void blk_add_trace_rq_issue(void *ignore,
871                                    struct request_queue *q, struct request *rq)
872 {
873         blk_add_trace_rq(rq, 0, blk_rq_bytes(rq), BLK_TA_ISSUE,
874                          blk_trace_request_get_cgid(q, rq));
875 }
876
877 static void blk_add_trace_rq_requeue(void *ignore,
878                                      struct request_queue *q,
879                                      struct request *rq)
880 {
881         blk_add_trace_rq(rq, 0, blk_rq_bytes(rq), BLK_TA_REQUEUE,
882                          blk_trace_request_get_cgid(q, rq));
883 }
884
885 static void blk_add_trace_rq_complete(void *ignore, struct request *rq,
886                         int error, unsigned int nr_bytes)
887 {
888         blk_add_trace_rq(rq, error, nr_bytes, BLK_TA_COMPLETE,
889                          blk_trace_request_get_cgid(rq->q, rq));
890 }
891
892 /**
893  * blk_add_trace_bio - Add a trace for a bio oriented action
894  * @q:          queue the io is for
895  * @bio:        the source bio
896  * @what:       the action
897  * @error:      error, if any
898  *
899  * Description:
900  *     Records an action against a bio. Will log the bio offset + size.
901  *
902  **/
903 static void blk_add_trace_bio(struct request_queue *q, struct bio *bio,
904                               u32 what, int error)
905 {
906         struct blk_trace *bt;
907
908         rcu_read_lock();
909         bt = rcu_dereference(q->blk_trace);
910         if (likely(!bt)) {
911                 rcu_read_unlock();
912                 return;
913         }
914
915         __blk_add_trace(bt, bio->bi_iter.bi_sector, bio->bi_iter.bi_size,
916                         bio_op(bio), bio->bi_opf, what, error, 0, NULL,
917                         blk_trace_bio_get_cgid(q, bio));
918         rcu_read_unlock();
919 }
920
921 static void blk_add_trace_bio_bounce(void *ignore,
922                                      struct request_queue *q, struct bio *bio)
923 {
924         blk_add_trace_bio(q, bio, BLK_TA_BOUNCE, 0);
925 }
926
927 static void blk_add_trace_bio_complete(void *ignore,
928                                        struct request_queue *q, struct bio *bio,
929                                        int error)
930 {
931         blk_add_trace_bio(q, bio, BLK_TA_COMPLETE, error);
932 }
933
934 static void blk_add_trace_bio_backmerge(void *ignore,
935                                         struct request_queue *q,
936                                         struct request *rq,
937                                         struct bio *bio)
938 {
939         blk_add_trace_bio(q, bio, BLK_TA_BACKMERGE, 0);
940 }
941
942 static void blk_add_trace_bio_frontmerge(void *ignore,
943                                          struct request_queue *q,
944                                          struct request *rq,
945                                          struct bio *bio)
946 {
947         blk_add_trace_bio(q, bio, BLK_TA_FRONTMERGE, 0);
948 }
949
950 static void blk_add_trace_bio_queue(void *ignore,
951                                     struct request_queue *q, struct bio *bio)
952 {
953         blk_add_trace_bio(q, bio, BLK_TA_QUEUE, 0);
954 }
955
956 static void blk_add_trace_getrq(void *ignore,
957                                 struct request_queue *q,
958                                 struct bio *bio, int rw)
959 {
960         if (bio)
961                 blk_add_trace_bio(q, bio, BLK_TA_GETRQ, 0);
962         else {
963                 struct blk_trace *bt;
964
965                 rcu_read_lock();
966                 bt = rcu_dereference(q->blk_trace);
967                 if (bt)
968                         __blk_add_trace(bt, 0, 0, rw, 0, BLK_TA_GETRQ, 0, 0,
969                                         NULL, NULL);
970                 rcu_read_unlock();
971         }
972 }
973
974
975 static void blk_add_trace_sleeprq(void *ignore,
976                                   struct request_queue *q,
977                                   struct bio *bio, int rw)
978 {
979         if (bio)
980                 blk_add_trace_bio(q, bio, BLK_TA_SLEEPRQ, 0);
981         else {
982                 struct blk_trace *bt;
983
984                 rcu_read_lock();
985                 bt = rcu_dereference(q->blk_trace);
986                 if (bt)
987                         __blk_add_trace(bt, 0, 0, rw, 0, BLK_TA_SLEEPRQ,
988                                         0, 0, NULL, NULL);
989                 rcu_read_unlock();
990         }
991 }
992
993 static void blk_add_trace_plug(void *ignore, struct request_queue *q)
994 {
995         struct blk_trace *bt;
996
997         rcu_read_lock();
998         bt = rcu_dereference(q->blk_trace);
999         if (bt)
1000                 __blk_add_trace(bt, 0, 0, 0, 0, BLK_TA_PLUG, 0, 0, NULL, NULL);
1001         rcu_read_unlock();
1002 }
1003
1004 static void blk_add_trace_unplug(void *ignore, struct request_queue *q,
1005                                     unsigned int depth, bool explicit)
1006 {
1007         struct blk_trace *bt;
1008
1009         rcu_read_lock();
1010         bt = rcu_dereference(q->blk_trace);
1011         if (bt) {
1012                 __be64 rpdu = cpu_to_be64(depth);
1013                 u32 what;
1014
1015                 if (explicit)
1016                         what = BLK_TA_UNPLUG_IO;
1017                 else
1018                         what = BLK_TA_UNPLUG_TIMER;
1019
1020                 __blk_add_trace(bt, 0, 0, 0, 0, what, 0, sizeof(rpdu), &rpdu, NULL);
1021         }
1022         rcu_read_unlock();
1023 }
1024
1025 static void blk_add_trace_split(void *ignore,
1026                                 struct request_queue *q, struct bio *bio,
1027                                 unsigned int pdu)
1028 {
1029         struct blk_trace *bt;
1030
1031         rcu_read_lock();
1032         bt = rcu_dereference(q->blk_trace);
1033         if (bt) {
1034                 __be64 rpdu = cpu_to_be64(pdu);
1035
1036                 __blk_add_trace(bt, bio->bi_iter.bi_sector,
1037                                 bio->bi_iter.bi_size, bio_op(bio), bio->bi_opf,
1038                                 BLK_TA_SPLIT,
1039                                 blk_status_to_errno(bio->bi_status),
1040                                 sizeof(rpdu), &rpdu,
1041                                 blk_trace_bio_get_cgid(q, bio));
1042         }
1043         rcu_read_unlock();
1044 }
1045
1046 /**
1047  * blk_add_trace_bio_remap - Add a trace for a bio-remap operation
1048  * @ignore:     trace callback data parameter (not used)
1049  * @q:          queue the io is for
1050  * @bio:        the source bio
1051  * @dev:        target device
1052  * @from:       source sector
1053  *
1054  * Description:
1055  *     Device mapper or raid target sometimes need to split a bio because
1056  *     it spans a stripe (or similar). Add a trace for that action.
1057  *
1058  **/
1059 static void blk_add_trace_bio_remap(void *ignore,
1060                                     struct request_queue *q, struct bio *bio,
1061                                     dev_t dev, sector_t from)
1062 {
1063         struct blk_trace *bt;
1064         struct blk_io_trace_remap r;
1065
1066         rcu_read_lock();
1067         bt = rcu_dereference(q->blk_trace);
1068         if (likely(!bt)) {
1069                 rcu_read_unlock();
1070                 return;
1071         }
1072
1073         r.device_from = cpu_to_be32(dev);
1074         r.device_to   = cpu_to_be32(bio_dev(bio));
1075         r.sector_from = cpu_to_be64(from);
1076
1077         __blk_add_trace(bt, bio->bi_iter.bi_sector, bio->bi_iter.bi_size,
1078                         bio_op(bio), bio->bi_opf, BLK_TA_REMAP,
1079                         blk_status_to_errno(bio->bi_status),
1080                         sizeof(r), &r, blk_trace_bio_get_cgid(q, bio));
1081         rcu_read_unlock();
1082 }
1083
1084 /**
1085  * blk_add_trace_rq_remap - Add a trace for a request-remap operation
1086  * @ignore:     trace callback data parameter (not used)
1087  * @q:          queue the io is for
1088  * @rq:         the source request
1089  * @dev:        target device
1090  * @from:       source sector
1091  *
1092  * Description:
1093  *     Device mapper remaps request to other devices.
1094  *     Add a trace for that action.
1095  *
1096  **/
1097 static void blk_add_trace_rq_remap(void *ignore,
1098                                    struct request_queue *q,
1099                                    struct request *rq, dev_t dev,
1100                                    sector_t from)
1101 {
1102         struct blk_trace *bt;
1103         struct blk_io_trace_remap r;
1104
1105         rcu_read_lock();
1106         bt = rcu_dereference(q->blk_trace);
1107         if (likely(!bt)) {
1108                 rcu_read_unlock();
1109                 return;
1110         }
1111
1112         r.device_from = cpu_to_be32(dev);
1113         r.device_to   = cpu_to_be32(disk_devt(rq->rq_disk));
1114         r.sector_from = cpu_to_be64(from);
1115
1116         __blk_add_trace(bt, blk_rq_pos(rq), blk_rq_bytes(rq),
1117                         rq_data_dir(rq), 0, BLK_TA_REMAP, 0,
1118                         sizeof(r), &r, blk_trace_request_get_cgid(q, rq));
1119         rcu_read_unlock();
1120 }
1121
1122 /**
1123  * blk_add_driver_data - Add binary message with driver-specific data
1124  * @q:          queue the io is for
1125  * @rq:         io request
1126  * @data:       driver-specific data
1127  * @len:        length of driver-specific data
1128  *
1129  * Description:
1130  *     Some drivers might want to write driver-specific data per request.
1131  *
1132  **/
1133 void blk_add_driver_data(struct request_queue *q,
1134                          struct request *rq,
1135                          void *data, size_t len)
1136 {
1137         struct blk_trace *bt;
1138
1139         rcu_read_lock();
1140         bt = rcu_dereference(q->blk_trace);
1141         if (likely(!bt)) {
1142                 rcu_read_unlock();
1143                 return;
1144         }
1145
1146         __blk_add_trace(bt, blk_rq_trace_sector(rq), blk_rq_bytes(rq), 0, 0,
1147                                 BLK_TA_DRV_DATA, 0, len, data,
1148                                 blk_trace_request_get_cgid(q, rq));
1149         rcu_read_unlock();
1150 }
1151 EXPORT_SYMBOL_GPL(blk_add_driver_data);
1152
1153 static void blk_register_tracepoints(void)
1154 {
1155         int ret;
1156
1157         ret = register_trace_block_rq_insert(blk_add_trace_rq_insert, NULL);
1158         WARN_ON(ret);
1159         ret = register_trace_block_rq_issue(blk_add_trace_rq_issue, NULL);
1160         WARN_ON(ret);
1161         ret = register_trace_block_rq_requeue(blk_add_trace_rq_requeue, NULL);
1162         WARN_ON(ret);
1163         ret = register_trace_block_rq_complete(blk_add_trace_rq_complete, NULL);
1164         WARN_ON(ret);
1165         ret = register_trace_block_bio_bounce(blk_add_trace_bio_bounce, NULL);
1166         WARN_ON(ret);
1167         ret = register_trace_block_bio_complete(blk_add_trace_bio_complete, NULL);
1168         WARN_ON(ret);
1169         ret = register_trace_block_bio_backmerge(blk_add_trace_bio_backmerge, NULL);
1170         WARN_ON(ret);
1171         ret = register_trace_block_bio_frontmerge(blk_add_trace_bio_frontmerge, NULL);
1172         WARN_ON(ret);
1173         ret = register_trace_block_bio_queue(blk_add_trace_bio_queue, NULL);
1174         WARN_ON(ret);
1175         ret = register_trace_block_getrq(blk_add_trace_getrq, NULL);
1176         WARN_ON(ret);
1177         ret = register_trace_block_sleeprq(blk_add_trace_sleeprq, NULL);
1178         WARN_ON(ret);
1179         ret = register_trace_block_plug(blk_add_trace_plug, NULL);
1180         WARN_ON(ret);
1181         ret = register_trace_block_unplug(blk_add_trace_unplug, NULL);
1182         WARN_ON(ret);
1183         ret = register_trace_block_split(blk_add_trace_split, NULL);
1184         WARN_ON(ret);
1185         ret = register_trace_block_bio_remap(blk_add_trace_bio_remap, NULL);
1186         WARN_ON(ret);
1187         ret = register_trace_block_rq_remap(blk_add_trace_rq_remap, NULL);
1188         WARN_ON(ret);
1189 }
1190
1191 static void blk_unregister_tracepoints(void)
1192 {
1193         unregister_trace_block_rq_remap(blk_add_trace_rq_remap, NULL);
1194         unregister_trace_block_bio_remap(blk_add_trace_bio_remap, NULL);
1195         unregister_trace_block_split(blk_add_trace_split, NULL);
1196         unregister_trace_block_unplug(blk_add_trace_unplug, NULL);
1197         unregister_trace_block_plug(blk_add_trace_plug, NULL);
1198         unregister_trace_block_sleeprq(blk_add_trace_sleeprq, NULL);
1199         unregister_trace_block_getrq(blk_add_trace_getrq, NULL);
1200         unregister_trace_block_bio_queue(blk_add_trace_bio_queue, NULL);
1201         unregister_trace_block_bio_frontmerge(blk_add_trace_bio_frontmerge, NULL);
1202         unregister_trace_block_bio_backmerge(blk_add_trace_bio_backmerge, NULL);
1203         unregister_trace_block_bio_complete(blk_add_trace_bio_complete, NULL);
1204         unregister_trace_block_bio_bounce(blk_add_trace_bio_bounce, NULL);
1205         unregister_trace_block_rq_complete(blk_add_trace_rq_complete, NULL);
1206         unregister_trace_block_rq_requeue(blk_add_trace_rq_requeue, NULL);
1207         unregister_trace_block_rq_issue(blk_add_trace_rq_issue, NULL);
1208         unregister_trace_block_rq_insert(blk_add_trace_rq_insert, NULL);
1209
1210         tracepoint_synchronize_unregister();
1211 }
1212
1213 /*
1214  * struct blk_io_tracer formatting routines
1215  */
1216
1217 static void fill_rwbs(char *rwbs, const struct blk_io_trace *t)
1218 {
1219         int i = 0;
1220         int tc = t->action >> BLK_TC_SHIFT;
1221
1222         if ((t->action & ~__BLK_TN_CGROUP) == BLK_TN_MESSAGE) {
1223                 rwbs[i++] = 'N';
1224                 goto out;
1225         }
1226
1227         if (tc & BLK_TC_FLUSH)
1228                 rwbs[i++] = 'F';
1229
1230         if (tc & BLK_TC_DISCARD)
1231                 rwbs[i++] = 'D';
1232         else if (tc & BLK_TC_WRITE)
1233                 rwbs[i++] = 'W';
1234         else if (t->bytes)
1235                 rwbs[i++] = 'R';
1236         else
1237                 rwbs[i++] = 'N';
1238
1239         if (tc & BLK_TC_FUA)
1240                 rwbs[i++] = 'F';
1241         if (tc & BLK_TC_AHEAD)
1242                 rwbs[i++] = 'A';
1243         if (tc & BLK_TC_SYNC)
1244                 rwbs[i++] = 'S';
1245         if (tc & BLK_TC_META)
1246                 rwbs[i++] = 'M';
1247 out:
1248         rwbs[i] = '\0';
1249 }
1250
1251 static inline
1252 const struct blk_io_trace *te_blk_io_trace(const struct trace_entry *ent)
1253 {
1254         return (const struct blk_io_trace *)ent;
1255 }
1256
1257 static inline const void *pdu_start(const struct trace_entry *ent, bool has_cg)
1258 {
1259         return (void *)(te_blk_io_trace(ent) + 1) +
1260                 (has_cg ? sizeof(union kernfs_node_id) : 0);
1261 }
1262
1263 static inline const void *cgid_start(const struct trace_entry *ent)
1264 {
1265         return (void *)(te_blk_io_trace(ent) + 1);
1266 }
1267
1268 static inline int pdu_real_len(const struct trace_entry *ent, bool has_cg)
1269 {
1270         return te_blk_io_trace(ent)->pdu_len -
1271                         (has_cg ? sizeof(union kernfs_node_id) : 0);
1272 }
1273
1274 static inline u32 t_action(const struct trace_entry *ent)
1275 {
1276         return te_blk_io_trace(ent)->action;
1277 }
1278
1279 static inline u32 t_bytes(const struct trace_entry *ent)
1280 {
1281         return te_blk_io_trace(ent)->bytes;
1282 }
1283
1284 static inline u32 t_sec(const struct trace_entry *ent)
1285 {
1286         return te_blk_io_trace(ent)->bytes >> 9;
1287 }
1288
1289 static inline unsigned long long t_sector(const struct trace_entry *ent)
1290 {
1291         return te_blk_io_trace(ent)->sector;
1292 }
1293
1294 static inline __u16 t_error(const struct trace_entry *ent)
1295 {
1296         return te_blk_io_trace(ent)->error;
1297 }
1298
1299 static __u64 get_pdu_int(const struct trace_entry *ent, bool has_cg)
1300 {
1301         const __be64 *val = pdu_start(ent, has_cg);
1302         return be64_to_cpu(*val);
1303 }
1304
1305 typedef void (blk_log_action_t) (struct trace_iterator *iter, const char *act,
1306         bool has_cg);
1307
1308 static void blk_log_action_classic(struct trace_iterator *iter, const char *act,
1309         bool has_cg)
1310 {
1311         char rwbs[RWBS_LEN];
1312         unsigned long long ts  = iter->ts;
1313         unsigned long nsec_rem = do_div(ts, NSEC_PER_SEC);
1314         unsigned secs          = (unsigned long)ts;
1315         const struct blk_io_trace *t = te_blk_io_trace(iter->ent);
1316
1317         fill_rwbs(rwbs, t);
1318
1319         trace_seq_printf(&iter->seq,
1320                          "%3d,%-3d %2d %5d.%09lu %5u %2s %3s ",
1321                          MAJOR(t->device), MINOR(t->device), iter->cpu,
1322                          secs, nsec_rem, iter->ent->pid, act, rwbs);
1323 }
1324
1325 static void blk_log_action(struct trace_iterator *iter, const char *act,
1326         bool has_cg)
1327 {
1328         char rwbs[RWBS_LEN];
1329         const struct blk_io_trace *t = te_blk_io_trace(iter->ent);
1330
1331         fill_rwbs(rwbs, t);
1332         if (has_cg) {
1333                 const union kernfs_node_id *id = cgid_start(iter->ent);
1334
1335                 if (blk_tracer_flags.val & TRACE_BLK_OPT_CGNAME) {
1336                         char blkcg_name_buf[NAME_MAX + 1] = "<...>";
1337
1338                         cgroup_path_from_kernfs_id(id, blkcg_name_buf,
1339                                 sizeof(blkcg_name_buf));
1340                         trace_seq_printf(&iter->seq, "%3d,%-3d %s %2s %3s ",
1341                                  MAJOR(t->device), MINOR(t->device),
1342                                  blkcg_name_buf, act, rwbs);
1343                 } else
1344                         trace_seq_printf(&iter->seq,
1345                                  "%3d,%-3d %x,%-x %2s %3s ",
1346                                  MAJOR(t->device), MINOR(t->device),
1347                                  id->ino, id->generation, act, rwbs);
1348         } else
1349                 trace_seq_printf(&iter->seq, "%3d,%-3d %2s %3s ",
1350                                  MAJOR(t->device), MINOR(t->device), act, rwbs);
1351 }
1352
1353 static void blk_log_dump_pdu(struct trace_seq *s,
1354         const struct trace_entry *ent, bool has_cg)
1355 {
1356         const unsigned char *pdu_buf;
1357         int pdu_len;
1358         int i, end;
1359
1360         pdu_buf = pdu_start(ent, has_cg);
1361         pdu_len = pdu_real_len(ent, has_cg);
1362
1363         if (!pdu_len)
1364                 return;
1365
1366         /* find the last zero that needs to be printed */
1367         for (end = pdu_len - 1; end >= 0; end--)
1368                 if (pdu_buf[end])
1369                         break;
1370         end++;
1371
1372         trace_seq_putc(s, '(');
1373
1374         for (i = 0; i < pdu_len; i++) {
1375
1376                 trace_seq_printf(s, "%s%02x",
1377                                  i == 0 ? "" : " ", pdu_buf[i]);
1378
1379                 /*
1380                  * stop when the rest is just zeroes and indicate so
1381                  * with a ".." appended
1382                  */
1383                 if (i == end && end != pdu_len - 1) {
1384                         trace_seq_puts(s, " ..) ");
1385                         return;
1386                 }
1387         }
1388
1389         trace_seq_puts(s, ") ");
1390 }
1391
1392 static void blk_log_generic(struct trace_seq *s, const struct trace_entry *ent, bool has_cg)
1393 {
1394         char cmd[TASK_COMM_LEN];
1395
1396         trace_find_cmdline(ent->pid, cmd);
1397
1398         if (t_action(ent) & BLK_TC_ACT(BLK_TC_PC)) {
1399                 trace_seq_printf(s, "%u ", t_bytes(ent));
1400                 blk_log_dump_pdu(s, ent, has_cg);
1401                 trace_seq_printf(s, "[%s]\n", cmd);
1402         } else {
1403                 if (t_sec(ent))
1404                         trace_seq_printf(s, "%llu + %u [%s]\n",
1405                                                 t_sector(ent), t_sec(ent), cmd);
1406                 else
1407                         trace_seq_printf(s, "[%s]\n", cmd);
1408         }
1409 }
1410
1411 static void blk_log_with_error(struct trace_seq *s,
1412                               const struct trace_entry *ent, bool has_cg)
1413 {
1414         if (t_action(ent) & BLK_TC_ACT(BLK_TC_PC)) {
1415                 blk_log_dump_pdu(s, ent, has_cg);
1416                 trace_seq_printf(s, "[%d]\n", t_error(ent));
1417         } else {
1418                 if (t_sec(ent))
1419                         trace_seq_printf(s, "%llu + %u [%d]\n",
1420                                          t_sector(ent),
1421                                          t_sec(ent), t_error(ent));
1422                 else
1423                         trace_seq_printf(s, "%llu [%d]\n",
1424                                          t_sector(ent), t_error(ent));
1425         }
1426 }
1427
1428 static void blk_log_remap(struct trace_seq *s, const struct trace_entry *ent, bool has_cg)
1429 {
1430         const struct blk_io_trace_remap *__r = pdu_start(ent, has_cg);
1431
1432         trace_seq_printf(s, "%llu + %u <- (%d,%d) %llu\n",
1433                          t_sector(ent), t_sec(ent),
1434                          MAJOR(be32_to_cpu(__r->device_from)),
1435                          MINOR(be32_to_cpu(__r->device_from)),
1436                          be64_to_cpu(__r->sector_from));
1437 }
1438
1439 static void blk_log_plug(struct trace_seq *s, const struct trace_entry *ent, bool has_cg)
1440 {
1441         char cmd[TASK_COMM_LEN];
1442
1443         trace_find_cmdline(ent->pid, cmd);
1444
1445         trace_seq_printf(s, "[%s]\n", cmd);
1446 }
1447
1448 static void blk_log_unplug(struct trace_seq *s, const struct trace_entry *ent, bool has_cg)
1449 {
1450         char cmd[TASK_COMM_LEN];
1451
1452         trace_find_cmdline(ent->pid, cmd);
1453
1454         trace_seq_printf(s, "[%s] %llu\n", cmd, get_pdu_int(ent, has_cg));
1455 }
1456
1457 static void blk_log_split(struct trace_seq *s, const struct trace_entry *ent, bool has_cg)
1458 {
1459         char cmd[TASK_COMM_LEN];
1460
1461         trace_find_cmdline(ent->pid, cmd);
1462
1463         trace_seq_printf(s, "%llu / %llu [%s]\n", t_sector(ent),
1464                          get_pdu_int(ent, has_cg), cmd);
1465 }
1466
1467 static void blk_log_msg(struct trace_seq *s, const struct trace_entry *ent,
1468                         bool has_cg)
1469 {
1470
1471         trace_seq_putmem(s, pdu_start(ent, has_cg),
1472                 pdu_real_len(ent, has_cg));
1473         trace_seq_putc(s, '\n');
1474 }
1475
1476 /*
1477  * struct tracer operations
1478  */
1479
1480 static void blk_tracer_print_header(struct seq_file *m)
1481 {
1482         if (!(blk_tracer_flags.val & TRACE_BLK_OPT_CLASSIC))
1483                 return;
1484         seq_puts(m, "# DEV   CPU TIMESTAMP     PID ACT FLG\n"
1485                     "#  |     |     |           |   |   |\n");
1486 }
1487
1488 static void blk_tracer_start(struct trace_array *tr)
1489 {
1490         blk_tracer_enabled = true;
1491 }
1492
1493 static int blk_tracer_init(struct trace_array *tr)
1494 {
1495         blk_tr = tr;
1496         blk_tracer_start(tr);
1497         return 0;
1498 }
1499
1500 static void blk_tracer_stop(struct trace_array *tr)
1501 {
1502         blk_tracer_enabled = false;
1503 }
1504
1505 static void blk_tracer_reset(struct trace_array *tr)
1506 {
1507         blk_tracer_stop(tr);
1508 }
1509
1510 static const struct {
1511         const char *act[2];
1512         void       (*print)(struct trace_seq *s, const struct trace_entry *ent,
1513                             bool has_cg);
1514 } what2act[] = {
1515         [__BLK_TA_QUEUE]        = {{  "Q", "queue" },      blk_log_generic },
1516         [__BLK_TA_BACKMERGE]    = {{  "M", "backmerge" },  blk_log_generic },
1517         [__BLK_TA_FRONTMERGE]   = {{  "F", "frontmerge" }, blk_log_generic },
1518         [__BLK_TA_GETRQ]        = {{  "G", "getrq" },      blk_log_generic },
1519         [__BLK_TA_SLEEPRQ]      = {{  "S", "sleeprq" },    blk_log_generic },
1520         [__BLK_TA_REQUEUE]      = {{  "R", "requeue" },    blk_log_with_error },
1521         [__BLK_TA_ISSUE]        = {{  "D", "issue" },      blk_log_generic },
1522         [__BLK_TA_COMPLETE]     = {{  "C", "complete" },   blk_log_with_error },
1523         [__BLK_TA_PLUG]         = {{  "P", "plug" },       blk_log_plug },
1524         [__BLK_TA_UNPLUG_IO]    = {{  "U", "unplug_io" },  blk_log_unplug },
1525         [__BLK_TA_UNPLUG_TIMER] = {{ "UT", "unplug_timer" }, blk_log_unplug },
1526         [__BLK_TA_INSERT]       = {{  "I", "insert" },     blk_log_generic },
1527         [__BLK_TA_SPLIT]        = {{  "X", "split" },      blk_log_split },
1528         [__BLK_TA_BOUNCE]       = {{  "B", "bounce" },     blk_log_generic },
1529         [__BLK_TA_REMAP]        = {{  "A", "remap" },      blk_log_remap },
1530 };
1531
1532 static enum print_line_t print_one_line(struct trace_iterator *iter,
1533                                         bool classic)
1534 {
1535         struct trace_array *tr = iter->tr;
1536         struct trace_seq *s = &iter->seq;
1537         const struct blk_io_trace *t;
1538         u16 what;
1539         bool long_act;
1540         blk_log_action_t *log_action;
1541         bool has_cg;
1542
1543         t          = te_blk_io_trace(iter->ent);
1544         what       = (t->action & ((1 << BLK_TC_SHIFT) - 1)) & ~__BLK_TA_CGROUP;
1545         long_act   = !!(tr->trace_flags & TRACE_ITER_VERBOSE);
1546         log_action = classic ? &blk_log_action_classic : &blk_log_action;
1547         has_cg     = t->action & __BLK_TA_CGROUP;
1548
1549         if ((t->action & ~__BLK_TN_CGROUP) == BLK_TN_MESSAGE) {
1550                 log_action(iter, long_act ? "message" : "m", has_cg);
1551                 blk_log_msg(s, iter->ent, has_cg);
1552                 return trace_handle_return(s);
1553         }
1554
1555         if (unlikely(what == 0 || what >= ARRAY_SIZE(what2act)))
1556                 trace_seq_printf(s, "Unknown action %x\n", what);
1557         else {
1558                 log_action(iter, what2act[what].act[long_act], has_cg);
1559                 what2act[what].print(s, iter->ent, has_cg);
1560         }
1561
1562         return trace_handle_return(s);
1563 }
1564
1565 static enum print_line_t blk_trace_event_print(struct trace_iterator *iter,
1566                                                int flags, struct trace_event *event)
1567 {
1568         return print_one_line(iter, false);
1569 }
1570
1571 static void blk_trace_synthesize_old_trace(struct trace_iterator *iter)
1572 {
1573         struct trace_seq *s = &iter->seq;
1574         struct blk_io_trace *t = (struct blk_io_trace *)iter->ent;
1575         const int offset = offsetof(struct blk_io_trace, sector);
1576         struct blk_io_trace old = {
1577                 .magic    = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION,
1578                 .time     = iter->ts,
1579         };
1580
1581         trace_seq_putmem(s, &old, offset);
1582         trace_seq_putmem(s, &t->sector,
1583                          sizeof(old) - offset + t->pdu_len);
1584 }
1585
1586 static enum print_line_t
1587 blk_trace_event_print_binary(struct trace_iterator *iter, int flags,
1588                              struct trace_event *event)
1589 {
1590         blk_trace_synthesize_old_trace(iter);
1591
1592         return trace_handle_return(&iter->seq);
1593 }
1594
1595 static enum print_line_t blk_tracer_print_line(struct trace_iterator *iter)
1596 {
1597         if (!(blk_tracer_flags.val & TRACE_BLK_OPT_CLASSIC))
1598                 return TRACE_TYPE_UNHANDLED;
1599
1600         return print_one_line(iter, true);
1601 }
1602
1603 static int
1604 blk_tracer_set_flag(struct trace_array *tr, u32 old_flags, u32 bit, int set)
1605 {
1606         /* don't output context-info for blk_classic output */
1607         if (bit == TRACE_BLK_OPT_CLASSIC) {
1608                 if (set)
1609                         tr->trace_flags &= ~TRACE_ITER_CONTEXT_INFO;
1610                 else
1611                         tr->trace_flags |= TRACE_ITER_CONTEXT_INFO;
1612         }
1613         return 0;
1614 }
1615
1616 static struct tracer blk_tracer __read_mostly = {
1617         .name           = "blk",
1618         .init           = blk_tracer_init,
1619         .reset          = blk_tracer_reset,
1620         .start          = blk_tracer_start,
1621         .stop           = blk_tracer_stop,
1622         .print_header   = blk_tracer_print_header,
1623         .print_line     = blk_tracer_print_line,
1624         .flags          = &blk_tracer_flags,
1625         .set_flag       = blk_tracer_set_flag,
1626 };
1627
1628 static struct trace_event_functions trace_blk_event_funcs = {
1629         .trace          = blk_trace_event_print,
1630         .binary         = blk_trace_event_print_binary,
1631 };
1632
1633 static struct trace_event trace_blk_event = {
1634         .type           = TRACE_BLK,
1635         .funcs          = &trace_blk_event_funcs,
1636 };
1637
1638 static int __init init_blk_tracer(void)
1639 {
1640         if (!register_trace_event(&trace_blk_event)) {
1641                 pr_warn("Warning: could not register block events\n");
1642                 return 1;
1643         }
1644
1645         if (register_tracer(&blk_tracer) != 0) {
1646                 pr_warn("Warning: could not register the block tracer\n");
1647                 unregister_trace_event(&trace_blk_event);
1648                 return 1;
1649         }
1650
1651         return 0;
1652 }
1653
1654 device_initcall(init_blk_tracer);
1655
1656 static int blk_trace_remove_queue(struct request_queue *q)
1657 {
1658         struct blk_trace *bt;
1659
1660         bt = xchg(&q->blk_trace, NULL);
1661         if (bt == NULL)
1662                 return -EINVAL;
1663
1664         if (bt->trace_state == Blktrace_running) {
1665                 bt->trace_state = Blktrace_stopped;
1666                 spin_lock_irq(&running_trace_lock);
1667                 list_del_init(&bt->running_list);
1668                 spin_unlock_irq(&running_trace_lock);
1669                 relay_flush(bt->rchan);
1670         }
1671
1672         put_probe_ref();
1673         synchronize_rcu();
1674         blk_trace_free(bt);
1675         return 0;
1676 }
1677
1678 /*
1679  * Setup everything required to start tracing
1680  */
1681 static int blk_trace_setup_queue(struct request_queue *q,
1682                                  struct block_device *bdev)
1683 {
1684         struct blk_trace *bt = NULL;
1685         int ret = -ENOMEM;
1686
1687         bt = kzalloc(sizeof(*bt), GFP_KERNEL);
1688         if (!bt)
1689                 return -ENOMEM;
1690
1691         bt->msg_data = __alloc_percpu(BLK_TN_MAX_MSG, __alignof__(char));
1692         if (!bt->msg_data)
1693                 goto free_bt;
1694
1695         bt->dev = bdev->bd_dev;
1696         bt->act_mask = (u16)-1;
1697
1698         blk_trace_setup_lba(bt, bdev);
1699
1700         ret = -EBUSY;
1701         if (cmpxchg(&q->blk_trace, NULL, bt))
1702                 goto free_bt;
1703
1704         get_probe_ref();
1705         return 0;
1706
1707 free_bt:
1708         blk_trace_free(bt);
1709         return ret;
1710 }
1711
1712 /*
1713  * sysfs interface to enable and configure tracing
1714  */
1715
1716 static ssize_t sysfs_blk_trace_attr_show(struct device *dev,
1717                                          struct device_attribute *attr,
1718                                          char *buf);
1719 static ssize_t sysfs_blk_trace_attr_store(struct device *dev,
1720                                           struct device_attribute *attr,
1721                                           const char *buf, size_t count);
1722 #define BLK_TRACE_DEVICE_ATTR(_name) \
1723         DEVICE_ATTR(_name, S_IRUGO | S_IWUSR, \
1724                     sysfs_blk_trace_attr_show, \
1725                     sysfs_blk_trace_attr_store)
1726
1727 static BLK_TRACE_DEVICE_ATTR(enable);
1728 static BLK_TRACE_DEVICE_ATTR(act_mask);
1729 static BLK_TRACE_DEVICE_ATTR(pid);
1730 static BLK_TRACE_DEVICE_ATTR(start_lba);
1731 static BLK_TRACE_DEVICE_ATTR(end_lba);
1732
1733 static struct attribute *blk_trace_attrs[] = {
1734         &dev_attr_enable.attr,
1735         &dev_attr_act_mask.attr,
1736         &dev_attr_pid.attr,
1737         &dev_attr_start_lba.attr,
1738         &dev_attr_end_lba.attr,
1739         NULL
1740 };
1741
1742 struct attribute_group blk_trace_attr_group = {
1743         .name  = "trace",
1744         .attrs = blk_trace_attrs,
1745 };
1746
1747 static const struct {
1748         int mask;
1749         const char *str;
1750 } mask_maps[] = {
1751         { BLK_TC_READ,          "read"          },
1752         { BLK_TC_WRITE,         "write"         },
1753         { BLK_TC_FLUSH,         "flush"         },
1754         { BLK_TC_SYNC,          "sync"          },
1755         { BLK_TC_QUEUE,         "queue"         },
1756         { BLK_TC_REQUEUE,       "requeue"       },
1757         { BLK_TC_ISSUE,         "issue"         },
1758         { BLK_TC_COMPLETE,      "complete"      },
1759         { BLK_TC_FS,            "fs"            },
1760         { BLK_TC_PC,            "pc"            },
1761         { BLK_TC_NOTIFY,        "notify"        },
1762         { BLK_TC_AHEAD,         "ahead"         },
1763         { BLK_TC_META,          "meta"          },
1764         { BLK_TC_DISCARD,       "discard"       },
1765         { BLK_TC_DRV_DATA,      "drv_data"      },
1766         { BLK_TC_FUA,           "fua"           },
1767 };
1768
1769 static int blk_trace_str2mask(const char *str)
1770 {
1771         int i;
1772         int mask = 0;
1773         char *buf, *s, *token;
1774
1775         buf = kstrdup(str, GFP_KERNEL);
1776         if (buf == NULL)
1777                 return -ENOMEM;
1778         s = strstrip(buf);
1779
1780         while (1) {
1781                 token = strsep(&s, ",");
1782                 if (token == NULL)
1783                         break;
1784
1785                 if (*token == '\0')
1786                         continue;
1787
1788                 for (i = 0; i < ARRAY_SIZE(mask_maps); i++) {
1789                         if (strcasecmp(token, mask_maps[i].str) == 0) {
1790                                 mask |= mask_maps[i].mask;
1791                                 break;
1792                         }
1793                 }
1794                 if (i == ARRAY_SIZE(mask_maps)) {
1795                         mask = -EINVAL;
1796                         break;
1797                 }
1798         }
1799         kfree(buf);
1800
1801         return mask;
1802 }
1803
1804 static ssize_t blk_trace_mask2str(char *buf, int mask)
1805 {
1806         int i;
1807         char *p = buf;
1808
1809         for (i = 0; i < ARRAY_SIZE(mask_maps); i++) {
1810                 if (mask & mask_maps[i].mask) {
1811                         p += sprintf(p, "%s%s",
1812                                     (p == buf) ? "" : ",", mask_maps[i].str);
1813                 }
1814         }
1815         *p++ = '\n';
1816
1817         return p - buf;
1818 }
1819
1820 static struct request_queue *blk_trace_get_queue(struct block_device *bdev)
1821 {
1822         if (bdev->bd_disk == NULL)
1823                 return NULL;
1824
1825         return bdev_get_queue(bdev);
1826 }
1827
1828 static ssize_t sysfs_blk_trace_attr_show(struct device *dev,
1829                                          struct device_attribute *attr,
1830                                          char *buf)
1831 {
1832         struct hd_struct *p = dev_to_part(dev);
1833         struct request_queue *q;
1834         struct block_device *bdev;
1835         struct blk_trace *bt;
1836         ssize_t ret = -ENXIO;
1837
1838         bdev = bdget(part_devt(p));
1839         if (bdev == NULL)
1840                 goto out;
1841
1842         q = blk_trace_get_queue(bdev);
1843         if (q == NULL)
1844                 goto out_bdput;
1845
1846         mutex_lock(&q->blk_trace_mutex);
1847
1848         bt = rcu_dereference_protected(q->blk_trace,
1849                                        lockdep_is_held(&q->blk_trace_mutex));
1850         if (attr == &dev_attr_enable) {
1851                 ret = sprintf(buf, "%u\n", !!bt);
1852                 goto out_unlock_bdev;
1853         }
1854
1855         if (bt == NULL)
1856                 ret = sprintf(buf, "disabled\n");
1857         else if (attr == &dev_attr_act_mask)
1858                 ret = blk_trace_mask2str(buf, bt->act_mask);
1859         else if (attr == &dev_attr_pid)
1860                 ret = sprintf(buf, "%u\n", bt->pid);
1861         else if (attr == &dev_attr_start_lba)
1862                 ret = sprintf(buf, "%llu\n", bt->start_lba);
1863         else if (attr == &dev_attr_end_lba)
1864                 ret = sprintf(buf, "%llu\n", bt->end_lba);
1865
1866 out_unlock_bdev:
1867         mutex_unlock(&q->blk_trace_mutex);
1868 out_bdput:
1869         bdput(bdev);
1870 out:
1871         return ret;
1872 }
1873
1874 static ssize_t sysfs_blk_trace_attr_store(struct device *dev,
1875                                           struct device_attribute *attr,
1876                                           const char *buf, size_t count)
1877 {
1878         struct block_device *bdev;
1879         struct request_queue *q;
1880         struct hd_struct *p;
1881         struct blk_trace *bt;
1882         u64 value;
1883         ssize_t ret = -EINVAL;
1884
1885         if (count == 0)
1886                 goto out;
1887
1888         if (attr == &dev_attr_act_mask) {
1889                 if (kstrtoull(buf, 0, &value)) {
1890                         /* Assume it is a list of trace category names */
1891                         ret = blk_trace_str2mask(buf);
1892                         if (ret < 0)
1893                                 goto out;
1894                         value = ret;
1895                 }
1896         } else if (kstrtoull(buf, 0, &value))
1897                 goto out;
1898
1899         ret = -ENXIO;
1900
1901         p = dev_to_part(dev);
1902         bdev = bdget(part_devt(p));
1903         if (bdev == NULL)
1904                 goto out;
1905
1906         q = blk_trace_get_queue(bdev);
1907         if (q == NULL)
1908                 goto out_bdput;
1909
1910         mutex_lock(&q->blk_trace_mutex);
1911
1912         bt = rcu_dereference_protected(q->blk_trace,
1913                                        lockdep_is_held(&q->blk_trace_mutex));
1914         if (attr == &dev_attr_enable) {
1915                 if (!!value == !!bt) {
1916                         ret = 0;
1917                         goto out_unlock_bdev;
1918                 }
1919                 if (value)
1920                         ret = blk_trace_setup_queue(q, bdev);
1921                 else
1922                         ret = blk_trace_remove_queue(q);
1923                 goto out_unlock_bdev;
1924         }
1925
1926         ret = 0;
1927         if (bt == NULL) {
1928                 ret = blk_trace_setup_queue(q, bdev);
1929                 bt = rcu_dereference_protected(q->blk_trace,
1930                                 lockdep_is_held(&q->blk_trace_mutex));
1931         }
1932
1933         if (ret == 0) {
1934                 if (attr == &dev_attr_act_mask)
1935                         bt->act_mask = value;
1936                 else if (attr == &dev_attr_pid)
1937                         bt->pid = value;
1938                 else if (attr == &dev_attr_start_lba)
1939                         bt->start_lba = value;
1940                 else if (attr == &dev_attr_end_lba)
1941                         bt->end_lba = value;
1942         }
1943
1944 out_unlock_bdev:
1945         mutex_unlock(&q->blk_trace_mutex);
1946 out_bdput:
1947         bdput(bdev);
1948 out:
1949         return ret ? ret : count;
1950 }
1951
1952 int blk_trace_init_sysfs(struct device *dev)
1953 {
1954         return sysfs_create_group(&dev->kobj, &blk_trace_attr_group);
1955 }
1956
1957 void blk_trace_remove_sysfs(struct device *dev)
1958 {
1959         sysfs_remove_group(&dev->kobj, &blk_trace_attr_group);
1960 }
1961
1962 #endif /* CONFIG_BLK_DEV_IO_TRACE */
1963
1964 #ifdef CONFIG_EVENT_TRACING
1965
1966 void blk_fill_rwbs(char *rwbs, unsigned int op, int bytes)
1967 {
1968         int i = 0;
1969
1970         if (op & REQ_PREFLUSH)
1971                 rwbs[i++] = 'F';
1972
1973         switch (op & REQ_OP_MASK) {
1974         case REQ_OP_WRITE:
1975         case REQ_OP_WRITE_SAME:
1976                 rwbs[i++] = 'W';
1977                 break;
1978         case REQ_OP_DISCARD:
1979                 rwbs[i++] = 'D';
1980                 break;
1981         case REQ_OP_SECURE_ERASE:
1982                 rwbs[i++] = 'D';
1983                 rwbs[i++] = 'E';
1984                 break;
1985         case REQ_OP_FLUSH:
1986                 rwbs[i++] = 'F';
1987                 break;
1988         case REQ_OP_READ:
1989                 rwbs[i++] = 'R';
1990                 break;
1991         default:
1992                 rwbs[i++] = 'N';
1993         }
1994
1995         if (op & REQ_FUA)
1996                 rwbs[i++] = 'F';
1997         if (op & REQ_RAHEAD)
1998                 rwbs[i++] = 'A';
1999         if (op & REQ_SYNC)
2000                 rwbs[i++] = 'S';
2001         if (op & REQ_META)
2002                 rwbs[i++] = 'M';
2003
2004         rwbs[i] = '\0';
2005 }
2006 EXPORT_SYMBOL_GPL(blk_fill_rwbs);
2007
2008 #endif /* CONFIG_EVENT_TRACING */
2009