blktrace: fix memory leak when freeing struct blk_io_trace
[linux-2.6.git] / kernel / trace / blktrace.c
1 /*
2  * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, write to the Free Software
15  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
16  *
17  */
18 #include <linux/kernel.h>
19 #include <linux/blkdev.h>
20 #include <linux/blktrace_api.h>
21 #include <linux/percpu.h>
22 #include <linux/init.h>
23 #include <linux/mutex.h>
24 #include <linux/debugfs.h>
25 #include <linux/time.h>
26 #include <trace/block.h>
27 #include <linux/uaccess.h>
28 #include "trace_output.h"
29
30 static unsigned int blktrace_seq __read_mostly = 1;
31
32 static struct trace_array *blk_tr;
33 static bool blk_tracer_enabled __read_mostly;
34
35 /* Select an alternative, minimalistic output than the original one */
36 #define TRACE_BLK_OPT_CLASSIC   0x1
37
38 static struct tracer_opt blk_tracer_opts[] = {
39         /* Default disable the minimalistic output */
40         { TRACER_OPT(blk_classic, TRACE_BLK_OPT_CLASSIC) },
41         { }
42 };
43
44 static struct tracer_flags blk_tracer_flags = {
45         .val  = 0,
46         .opts = blk_tracer_opts,
47 };
48
49 /* Global reference count of probes */
50 static atomic_t blk_probes_ref = ATOMIC_INIT(0);
51
52 static void blk_register_tracepoints(void);
53 static void blk_unregister_tracepoints(void);
54
55 /*
56  * Send out a notify message.
57  */
58 static void trace_note(struct blk_trace *bt, pid_t pid, int action,
59                        const void *data, size_t len)
60 {
61         struct blk_io_trace *t;
62
63         if (!bt->rchan)
64                 return;
65
66         t = relay_reserve(bt->rchan, sizeof(*t) + len);
67         if (t) {
68                 const int cpu = smp_processor_id();
69
70                 t->magic = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION;
71                 t->time = ktime_to_ns(ktime_get());
72                 t->device = bt->dev;
73                 t->action = action;
74                 t->pid = pid;
75                 t->cpu = cpu;
76                 t->pdu_len = len;
77                 memcpy((void *) t + sizeof(*t), data, len);
78         }
79 }
80
81 /*
82  * Send out a notify for this process, if we haven't done so since a trace
83  * started
84  */
85 static void trace_note_tsk(struct blk_trace *bt, struct task_struct *tsk)
86 {
87         tsk->btrace_seq = blktrace_seq;
88         trace_note(bt, tsk->pid, BLK_TN_PROCESS, tsk->comm, sizeof(tsk->comm));
89 }
90
91 static void trace_note_time(struct blk_trace *bt)
92 {
93         struct timespec now;
94         unsigned long flags;
95         u32 words[2];
96
97         getnstimeofday(&now);
98         words[0] = now.tv_sec;
99         words[1] = now.tv_nsec;
100
101         local_irq_save(flags);
102         trace_note(bt, 0, BLK_TN_TIMESTAMP, words, sizeof(words));
103         local_irq_restore(flags);
104 }
105
106 void __trace_note_message(struct blk_trace *bt, const char *fmt, ...)
107 {
108         int n;
109         va_list args;
110         unsigned long flags;
111         char *buf;
112
113         if (blk_tracer_enabled) {
114                 va_start(args, fmt);
115                 ftrace_vprintk(fmt, args);
116                 va_end(args);
117                 return;
118         }
119
120         if (!bt->msg_data)
121                 return;
122
123         local_irq_save(flags);
124         buf = per_cpu_ptr(bt->msg_data, smp_processor_id());
125         va_start(args, fmt);
126         n = vscnprintf(buf, BLK_TN_MAX_MSG, fmt, args);
127         va_end(args);
128
129         trace_note(bt, 0, BLK_TN_MESSAGE, buf, n);
130         local_irq_restore(flags);
131 }
132 EXPORT_SYMBOL_GPL(__trace_note_message);
133
134 static int act_log_check(struct blk_trace *bt, u32 what, sector_t sector,
135                          pid_t pid)
136 {
137         if (((bt->act_mask << BLK_TC_SHIFT) & what) == 0)
138                 return 1;
139         if (sector < bt->start_lba || sector > bt->end_lba)
140                 return 1;
141         if (bt->pid && pid != bt->pid)
142                 return 1;
143
144         return 0;
145 }
146
147 /*
148  * Data direction bit lookup
149  */
150 static const u32 ddir_act[2] = { BLK_TC_ACT(BLK_TC_READ),
151                                  BLK_TC_ACT(BLK_TC_WRITE) };
152
153 /* The ilog2() calls fall out because they're constant */
154 #define MASK_TC_BIT(rw, __name) ((rw & (1 << BIO_RW_ ## __name)) << \
155           (ilog2(BLK_TC_ ## __name) + BLK_TC_SHIFT - BIO_RW_ ## __name))
156
157 /*
158  * The worker for the various blk_add_trace*() types. Fills out a
159  * blk_io_trace structure and places it in a per-cpu subbuffer.
160  */
161 static void __blk_add_trace(struct blk_trace *bt, sector_t sector, int bytes,
162                      int rw, u32 what, int error, int pdu_len, void *pdu_data)
163 {
164         struct task_struct *tsk = current;
165         struct ring_buffer_event *event = NULL;
166         struct blk_io_trace *t;
167         unsigned long flags = 0;
168         unsigned long *sequence;
169         pid_t pid;
170         int cpu, pc = 0;
171
172         if (unlikely(bt->trace_state != Blktrace_running &&
173                      !blk_tracer_enabled))
174                 return;
175
176         what |= ddir_act[rw & WRITE];
177         what |= MASK_TC_BIT(rw, BARRIER);
178         what |= MASK_TC_BIT(rw, SYNCIO);
179         what |= MASK_TC_BIT(rw, AHEAD);
180         what |= MASK_TC_BIT(rw, META);
181         what |= MASK_TC_BIT(rw, DISCARD);
182
183         pid = tsk->pid;
184         if (unlikely(act_log_check(bt, what, sector, pid)))
185                 return;
186         cpu = raw_smp_processor_id();
187
188         if (blk_tracer_enabled) {
189                 tracing_record_cmdline(current);
190
191                 pc = preempt_count();
192                 event = trace_buffer_lock_reserve(blk_tr, TRACE_BLK,
193                                                   sizeof(*t) + pdu_len,
194                                                   0, pc);
195                 if (!event)
196                         return;
197                 t = ring_buffer_event_data(event);
198                 goto record_it;
199         }
200
201         /*
202          * A word about the locking here - we disable interrupts to reserve
203          * some space in the relay per-cpu buffer, to prevent an irq
204          * from coming in and stepping on our toes.
205          */
206         local_irq_save(flags);
207
208         if (unlikely(tsk->btrace_seq != blktrace_seq))
209                 trace_note_tsk(bt, tsk);
210
211         t = relay_reserve(bt->rchan, sizeof(*t) + pdu_len);
212         if (t) {
213                 sequence = per_cpu_ptr(bt->sequence, cpu);
214
215                 t->magic = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION;
216                 t->sequence = ++(*sequence);
217                 t->time = ktime_to_ns(ktime_get());
218 record_it:
219                 /*
220                  * These two are not needed in ftrace as they are in the
221                  * generic trace_entry, filled by tracing_generic_entry_update,
222                  * but for the trace_event->bin() synthesizer benefit we do it
223                  * here too.
224                  */
225                 t->cpu = cpu;
226                 t->pid = pid;
227
228                 t->sector = sector;
229                 t->bytes = bytes;
230                 t->action = what;
231                 t->device = bt->dev;
232                 t->error = error;
233                 t->pdu_len = pdu_len;
234
235                 if (pdu_len)
236                         memcpy((void *) t + sizeof(*t), pdu_data, pdu_len);
237
238                 if (blk_tracer_enabled) {
239                         trace_buffer_unlock_commit(blk_tr, event, 0, pc);
240                         return;
241                 }
242         }
243
244         local_irq_restore(flags);
245 }
246
247 static struct dentry *blk_tree_root;
248 static DEFINE_MUTEX(blk_tree_mutex);
249
250 static void blk_trace_free(struct blk_trace *bt)
251 {
252         debugfs_remove(bt->msg_file);
253         debugfs_remove(bt->dropped_file);
254         relay_close(bt->rchan);
255         free_percpu(bt->sequence);
256         free_percpu(bt->msg_data);
257         kfree(bt);
258 }
259
260 static void blk_trace_cleanup(struct blk_trace *bt)
261 {
262         blk_trace_free(bt);
263         if (atomic_dec_and_test(&blk_probes_ref))
264                 blk_unregister_tracepoints();
265 }
266
267 int blk_trace_remove(struct request_queue *q)
268 {
269         struct blk_trace *bt;
270
271         bt = xchg(&q->blk_trace, NULL);
272         if (!bt)
273                 return -EINVAL;
274
275         if (bt->trace_state != Blktrace_running)
276                 blk_trace_cleanup(bt);
277
278         return 0;
279 }
280 EXPORT_SYMBOL_GPL(blk_trace_remove);
281
282 static int blk_dropped_open(struct inode *inode, struct file *filp)
283 {
284         filp->private_data = inode->i_private;
285
286         return 0;
287 }
288
289 static ssize_t blk_dropped_read(struct file *filp, char __user *buffer,
290                                 size_t count, loff_t *ppos)
291 {
292         struct blk_trace *bt = filp->private_data;
293         char buf[16];
294
295         snprintf(buf, sizeof(buf), "%u\n", atomic_read(&bt->dropped));
296
297         return simple_read_from_buffer(buffer, count, ppos, buf, strlen(buf));
298 }
299
300 static const struct file_operations blk_dropped_fops = {
301         .owner =        THIS_MODULE,
302         .open =         blk_dropped_open,
303         .read =         blk_dropped_read,
304 };
305
306 static int blk_msg_open(struct inode *inode, struct file *filp)
307 {
308         filp->private_data = inode->i_private;
309
310         return 0;
311 }
312
313 static ssize_t blk_msg_write(struct file *filp, const char __user *buffer,
314                                 size_t count, loff_t *ppos)
315 {
316         char *msg;
317         struct blk_trace *bt;
318
319         if (count > BLK_TN_MAX_MSG)
320                 return -EINVAL;
321
322         msg = kmalloc(count, GFP_KERNEL);
323         if (msg == NULL)
324                 return -ENOMEM;
325
326         if (copy_from_user(msg, buffer, count)) {
327                 kfree(msg);
328                 return -EFAULT;
329         }
330
331         bt = filp->private_data;
332         __trace_note_message(bt, "%s", msg);
333         kfree(msg);
334
335         return count;
336 }
337
338 static const struct file_operations blk_msg_fops = {
339         .owner =        THIS_MODULE,
340         .open =         blk_msg_open,
341         .write =        blk_msg_write,
342 };
343
344 /*
345  * Keep track of how many times we encountered a full subbuffer, to aid
346  * the user space app in telling how many lost events there were.
347  */
348 static int blk_subbuf_start_callback(struct rchan_buf *buf, void *subbuf,
349                                      void *prev_subbuf, size_t prev_padding)
350 {
351         struct blk_trace *bt;
352
353         if (!relay_buf_full(buf))
354                 return 1;
355
356         bt = buf->chan->private_data;
357         atomic_inc(&bt->dropped);
358         return 0;
359 }
360
361 static int blk_remove_buf_file_callback(struct dentry *dentry)
362 {
363         struct dentry *parent = dentry->d_parent;
364         debugfs_remove(dentry);
365
366         /*
367         * this will fail for all but the last file, but that is ok. what we
368         * care about is the top level buts->name directory going away, when
369         * the last trace file is gone. Then we don't have to rmdir() that
370         * manually on trace stop, so it nicely solves the issue with
371         * force killing of running traces.
372         */
373
374         debugfs_remove(parent);
375         return 0;
376 }
377
378 static struct dentry *blk_create_buf_file_callback(const char *filename,
379                                                    struct dentry *parent,
380                                                    int mode,
381                                                    struct rchan_buf *buf,
382                                                    int *is_global)
383 {
384         return debugfs_create_file(filename, mode, parent, buf,
385                                         &relay_file_operations);
386 }
387
388 static struct rchan_callbacks blk_relay_callbacks = {
389         .subbuf_start           = blk_subbuf_start_callback,
390         .create_buf_file        = blk_create_buf_file_callback,
391         .remove_buf_file        = blk_remove_buf_file_callback,
392 };
393
394 /*
395  * Setup everything required to start tracing
396  */
397 int do_blk_trace_setup(struct request_queue *q, char *name, dev_t dev,
398                         struct blk_user_trace_setup *buts)
399 {
400         struct blk_trace *old_bt, *bt = NULL;
401         struct dentry *dir = NULL;
402         int ret, i;
403
404         if (!buts->buf_size || !buts->buf_nr)
405                 return -EINVAL;
406
407         strncpy(buts->name, name, BLKTRACE_BDEV_SIZE);
408         buts->name[BLKTRACE_BDEV_SIZE - 1] = '\0';
409
410         /*
411          * some device names have larger paths - convert the slashes
412          * to underscores for this to work as expected
413          */
414         for (i = 0; i < strlen(buts->name); i++)
415                 if (buts->name[i] == '/')
416                         buts->name[i] = '_';
417
418         bt = kzalloc(sizeof(*bt), GFP_KERNEL);
419         if (!bt)
420                 return -ENOMEM;
421
422         ret = -ENOMEM;
423         bt->sequence = alloc_percpu(unsigned long);
424         if (!bt->sequence)
425                 goto err;
426
427         bt->msg_data = __alloc_percpu(BLK_TN_MAX_MSG, __alignof__(char));
428         if (!bt->msg_data)
429                 goto err;
430
431         ret = -ENOENT;
432
433         mutex_lock(&blk_tree_mutex);
434         if (!blk_tree_root) {
435                 blk_tree_root = debugfs_create_dir("block", NULL);
436                 if (!blk_tree_root) {
437                         mutex_unlock(&blk_tree_mutex);
438                         goto err;
439                 }
440         }
441         mutex_unlock(&blk_tree_mutex);
442
443         dir = debugfs_create_dir(buts->name, blk_tree_root);
444
445         if (!dir)
446                 goto err;
447
448         bt->dir = dir;
449         bt->dev = dev;
450         atomic_set(&bt->dropped, 0);
451
452         ret = -EIO;
453         bt->dropped_file = debugfs_create_file("dropped", 0444, dir, bt,
454                                                &blk_dropped_fops);
455         if (!bt->dropped_file)
456                 goto err;
457
458         bt->msg_file = debugfs_create_file("msg", 0222, dir, bt, &blk_msg_fops);
459         if (!bt->msg_file)
460                 goto err;
461
462         bt->rchan = relay_open("trace", dir, buts->buf_size,
463                                 buts->buf_nr, &blk_relay_callbacks, bt);
464         if (!bt->rchan)
465                 goto err;
466
467         bt->act_mask = buts->act_mask;
468         if (!bt->act_mask)
469                 bt->act_mask = (u16) -1;
470
471         bt->start_lba = buts->start_lba;
472         bt->end_lba = buts->end_lba;
473         if (!bt->end_lba)
474                 bt->end_lba = -1ULL;
475
476         bt->pid = buts->pid;
477         bt->trace_state = Blktrace_setup;
478
479         ret = -EBUSY;
480         old_bt = xchg(&q->blk_trace, bt);
481         if (old_bt) {
482                 (void) xchg(&q->blk_trace, old_bt);
483                 goto err;
484         }
485
486         if (atomic_inc_return(&blk_probes_ref) == 1)
487                 blk_register_tracepoints();
488
489         return 0;
490 err:
491         blk_trace_free(bt);
492         return ret;
493 }
494
495 int blk_trace_setup(struct request_queue *q, char *name, dev_t dev,
496                     char __user *arg)
497 {
498         struct blk_user_trace_setup buts;
499         int ret;
500
501         ret = copy_from_user(&buts, arg, sizeof(buts));
502         if (ret)
503                 return -EFAULT;
504
505         ret = do_blk_trace_setup(q, name, dev, &buts);
506         if (ret)
507                 return ret;
508
509         if (copy_to_user(arg, &buts, sizeof(buts)))
510                 return -EFAULT;
511
512         return 0;
513 }
514 EXPORT_SYMBOL_GPL(blk_trace_setup);
515
516 int blk_trace_startstop(struct request_queue *q, int start)
517 {
518         int ret;
519         struct blk_trace *bt = q->blk_trace;
520
521         if (bt == NULL)
522                 return -EINVAL;
523
524         /*
525          * For starting a trace, we can transition from a setup or stopped
526          * trace. For stopping a trace, the state must be running
527          */
528         ret = -EINVAL;
529         if (start) {
530                 if (bt->trace_state == Blktrace_setup ||
531                     bt->trace_state == Blktrace_stopped) {
532                         blktrace_seq++;
533                         smp_mb();
534                         bt->trace_state = Blktrace_running;
535
536                         trace_note_time(bt);
537                         ret = 0;
538                 }
539         } else {
540                 if (bt->trace_state == Blktrace_running) {
541                         bt->trace_state = Blktrace_stopped;
542                         relay_flush(bt->rchan);
543                         ret = 0;
544                 }
545         }
546
547         return ret;
548 }
549 EXPORT_SYMBOL_GPL(blk_trace_startstop);
550
551 /**
552  * blk_trace_ioctl: - handle the ioctls associated with tracing
553  * @bdev:       the block device
554  * @cmd:        the ioctl cmd
555  * @arg:        the argument data, if any
556  *
557  **/
558 int blk_trace_ioctl(struct block_device *bdev, unsigned cmd, char __user *arg)
559 {
560         struct request_queue *q;
561         int ret, start = 0;
562         char b[BDEVNAME_SIZE];
563
564         q = bdev_get_queue(bdev);
565         if (!q)
566                 return -ENXIO;
567
568         mutex_lock(&bdev->bd_mutex);
569
570         switch (cmd) {
571         case BLKTRACESETUP:
572                 bdevname(bdev, b);
573                 ret = blk_trace_setup(q, b, bdev->bd_dev, arg);
574                 break;
575         case BLKTRACESTART:
576                 start = 1;
577         case BLKTRACESTOP:
578                 ret = blk_trace_startstop(q, start);
579                 break;
580         case BLKTRACETEARDOWN:
581                 ret = blk_trace_remove(q);
582                 break;
583         default:
584                 ret = -ENOTTY;
585                 break;
586         }
587
588         mutex_unlock(&bdev->bd_mutex);
589         return ret;
590 }
591
592 /**
593  * blk_trace_shutdown: - stop and cleanup trace structures
594  * @q:    the request queue associated with the device
595  *
596  **/
597 void blk_trace_shutdown(struct request_queue *q)
598 {
599         if (q->blk_trace) {
600                 blk_trace_startstop(q, 0);
601                 blk_trace_remove(q);
602         }
603 }
604
605 /*
606  * blktrace probes
607  */
608
609 /**
610  * blk_add_trace_rq - Add a trace for a request oriented action
611  * @q:          queue the io is for
612  * @rq:         the source request
613  * @what:       the action
614  *
615  * Description:
616  *     Records an action against a request. Will log the bio offset + size.
617  *
618  **/
619 static void blk_add_trace_rq(struct request_queue *q, struct request *rq,
620                                     u32 what)
621 {
622         struct blk_trace *bt = q->blk_trace;
623         int rw = rq->cmd_flags & 0x03;
624
625         if (likely(!bt))
626                 return;
627
628         if (blk_discard_rq(rq))
629                 rw |= (1 << BIO_RW_DISCARD);
630
631         if (blk_pc_request(rq)) {
632                 what |= BLK_TC_ACT(BLK_TC_PC);
633                 __blk_add_trace(bt, 0, rq->data_len, rw, what, rq->errors,
634                                 sizeof(rq->cmd), rq->cmd);
635         } else  {
636                 what |= BLK_TC_ACT(BLK_TC_FS);
637                 __blk_add_trace(bt, rq->hard_sector, rq->hard_nr_sectors << 9,
638                                 rw, what, rq->errors, 0, NULL);
639         }
640 }
641
642 static void blk_add_trace_rq_abort(struct request_queue *q, struct request *rq)
643 {
644         blk_add_trace_rq(q, rq, BLK_TA_ABORT);
645 }
646
647 static void blk_add_trace_rq_insert(struct request_queue *q, struct request *rq)
648 {
649         blk_add_trace_rq(q, rq, BLK_TA_INSERT);
650 }
651
652 static void blk_add_trace_rq_issue(struct request_queue *q, struct request *rq)
653 {
654         blk_add_trace_rq(q, rq, BLK_TA_ISSUE);
655 }
656
657 static void blk_add_trace_rq_requeue(struct request_queue *q,
658                                      struct request *rq)
659 {
660         blk_add_trace_rq(q, rq, BLK_TA_REQUEUE);
661 }
662
663 static void blk_add_trace_rq_complete(struct request_queue *q,
664                                       struct request *rq)
665 {
666         blk_add_trace_rq(q, rq, BLK_TA_COMPLETE);
667 }
668
669 /**
670  * blk_add_trace_bio - Add a trace for a bio oriented action
671  * @q:          queue the io is for
672  * @bio:        the source bio
673  * @what:       the action
674  *
675  * Description:
676  *     Records an action against a bio. Will log the bio offset + size.
677  *
678  **/
679 static void blk_add_trace_bio(struct request_queue *q, struct bio *bio,
680                                      u32 what)
681 {
682         struct blk_trace *bt = q->blk_trace;
683
684         if (likely(!bt))
685                 return;
686
687         __blk_add_trace(bt, bio->bi_sector, bio->bi_size, bio->bi_rw, what,
688                         !bio_flagged(bio, BIO_UPTODATE), 0, NULL);
689 }
690
691 static void blk_add_trace_bio_bounce(struct request_queue *q, struct bio *bio)
692 {
693         blk_add_trace_bio(q, bio, BLK_TA_BOUNCE);
694 }
695
696 static void blk_add_trace_bio_complete(struct request_queue *q, struct bio *bio)
697 {
698         blk_add_trace_bio(q, bio, BLK_TA_COMPLETE);
699 }
700
701 static void blk_add_trace_bio_backmerge(struct request_queue *q,
702                                         struct bio *bio)
703 {
704         blk_add_trace_bio(q, bio, BLK_TA_BACKMERGE);
705 }
706
707 static void blk_add_trace_bio_frontmerge(struct request_queue *q,
708                                          struct bio *bio)
709 {
710         blk_add_trace_bio(q, bio, BLK_TA_FRONTMERGE);
711 }
712
713 static void blk_add_trace_bio_queue(struct request_queue *q, struct bio *bio)
714 {
715         blk_add_trace_bio(q, bio, BLK_TA_QUEUE);
716 }
717
718 static void blk_add_trace_getrq(struct request_queue *q,
719                                 struct bio *bio, int rw)
720 {
721         if (bio)
722                 blk_add_trace_bio(q, bio, BLK_TA_GETRQ);
723         else {
724                 struct blk_trace *bt = q->blk_trace;
725
726                 if (bt)
727                         __blk_add_trace(bt, 0, 0, rw, BLK_TA_GETRQ, 0, 0, NULL);
728         }
729 }
730
731
732 static void blk_add_trace_sleeprq(struct request_queue *q,
733                                   struct bio *bio, int rw)
734 {
735         if (bio)
736                 blk_add_trace_bio(q, bio, BLK_TA_SLEEPRQ);
737         else {
738                 struct blk_trace *bt = q->blk_trace;
739
740                 if (bt)
741                         __blk_add_trace(bt, 0, 0, rw, BLK_TA_SLEEPRQ,
742                                         0, 0, NULL);
743         }
744 }
745
746 static void blk_add_trace_plug(struct request_queue *q)
747 {
748         struct blk_trace *bt = q->blk_trace;
749
750         if (bt)
751                 __blk_add_trace(bt, 0, 0, 0, BLK_TA_PLUG, 0, 0, NULL);
752 }
753
754 static void blk_add_trace_unplug_io(struct request_queue *q)
755 {
756         struct blk_trace *bt = q->blk_trace;
757
758         if (bt) {
759                 unsigned int pdu = q->rq.count[READ] + q->rq.count[WRITE];
760                 __be64 rpdu = cpu_to_be64(pdu);
761
762                 __blk_add_trace(bt, 0, 0, 0, BLK_TA_UNPLUG_IO, 0,
763                                 sizeof(rpdu), &rpdu);
764         }
765 }
766
767 static void blk_add_trace_unplug_timer(struct request_queue *q)
768 {
769         struct blk_trace *bt = q->blk_trace;
770
771         if (bt) {
772                 unsigned int pdu = q->rq.count[READ] + q->rq.count[WRITE];
773                 __be64 rpdu = cpu_to_be64(pdu);
774
775                 __blk_add_trace(bt, 0, 0, 0, BLK_TA_UNPLUG_TIMER, 0,
776                                 sizeof(rpdu), &rpdu);
777         }
778 }
779
780 static void blk_add_trace_split(struct request_queue *q, struct bio *bio,
781                                 unsigned int pdu)
782 {
783         struct blk_trace *bt = q->blk_trace;
784
785         if (bt) {
786                 __be64 rpdu = cpu_to_be64(pdu);
787
788                 __blk_add_trace(bt, bio->bi_sector, bio->bi_size, bio->bi_rw,
789                                 BLK_TA_SPLIT, !bio_flagged(bio, BIO_UPTODATE),
790                                 sizeof(rpdu), &rpdu);
791         }
792 }
793
794 /**
795  * blk_add_trace_remap - Add a trace for a remap operation
796  * @q:          queue the io is for
797  * @bio:        the source bio
798  * @dev:        target device
799  * @from:       source sector
800  * @to:         target sector
801  *
802  * Description:
803  *     Device mapper or raid target sometimes need to split a bio because
804  *     it spans a stripe (or similar). Add a trace for that action.
805  *
806  **/
807 static void blk_add_trace_remap(struct request_queue *q, struct bio *bio,
808                                        dev_t dev, sector_t from, sector_t to)
809 {
810         struct blk_trace *bt = q->blk_trace;
811         struct blk_io_trace_remap r;
812
813         if (likely(!bt))
814                 return;
815
816         r.device = cpu_to_be32(dev);
817         r.device_from = cpu_to_be32(bio->bi_bdev->bd_dev);
818         r.sector = cpu_to_be64(to);
819
820         __blk_add_trace(bt, from, bio->bi_size, bio->bi_rw, BLK_TA_REMAP,
821                         !bio_flagged(bio, BIO_UPTODATE), sizeof(r), &r);
822 }
823
824 /**
825  * blk_add_driver_data - Add binary message with driver-specific data
826  * @q:          queue the io is for
827  * @rq:         io request
828  * @data:       driver-specific data
829  * @len:        length of driver-specific data
830  *
831  * Description:
832  *     Some drivers might want to write driver-specific data per request.
833  *
834  **/
835 void blk_add_driver_data(struct request_queue *q,
836                          struct request *rq,
837                          void *data, size_t len)
838 {
839         struct blk_trace *bt = q->blk_trace;
840
841         if (likely(!bt))
842                 return;
843
844         if (blk_pc_request(rq))
845                 __blk_add_trace(bt, 0, rq->data_len, 0, BLK_TA_DRV_DATA,
846                                 rq->errors, len, data);
847         else
848                 __blk_add_trace(bt, rq->hard_sector, rq->hard_nr_sectors << 9,
849                                 0, BLK_TA_DRV_DATA, rq->errors, len, data);
850 }
851 EXPORT_SYMBOL_GPL(blk_add_driver_data);
852
853 static void blk_register_tracepoints(void)
854 {
855         int ret;
856
857         ret = register_trace_block_rq_abort(blk_add_trace_rq_abort);
858         WARN_ON(ret);
859         ret = register_trace_block_rq_insert(blk_add_trace_rq_insert);
860         WARN_ON(ret);
861         ret = register_trace_block_rq_issue(blk_add_trace_rq_issue);
862         WARN_ON(ret);
863         ret = register_trace_block_rq_requeue(blk_add_trace_rq_requeue);
864         WARN_ON(ret);
865         ret = register_trace_block_rq_complete(blk_add_trace_rq_complete);
866         WARN_ON(ret);
867         ret = register_trace_block_bio_bounce(blk_add_trace_bio_bounce);
868         WARN_ON(ret);
869         ret = register_trace_block_bio_complete(blk_add_trace_bio_complete);
870         WARN_ON(ret);
871         ret = register_trace_block_bio_backmerge(blk_add_trace_bio_backmerge);
872         WARN_ON(ret);
873         ret = register_trace_block_bio_frontmerge(blk_add_trace_bio_frontmerge);
874         WARN_ON(ret);
875         ret = register_trace_block_bio_queue(blk_add_trace_bio_queue);
876         WARN_ON(ret);
877         ret = register_trace_block_getrq(blk_add_trace_getrq);
878         WARN_ON(ret);
879         ret = register_trace_block_sleeprq(blk_add_trace_sleeprq);
880         WARN_ON(ret);
881         ret = register_trace_block_plug(blk_add_trace_plug);
882         WARN_ON(ret);
883         ret = register_trace_block_unplug_timer(blk_add_trace_unplug_timer);
884         WARN_ON(ret);
885         ret = register_trace_block_unplug_io(blk_add_trace_unplug_io);
886         WARN_ON(ret);
887         ret = register_trace_block_split(blk_add_trace_split);
888         WARN_ON(ret);
889         ret = register_trace_block_remap(blk_add_trace_remap);
890         WARN_ON(ret);
891 }
892
893 static void blk_unregister_tracepoints(void)
894 {
895         unregister_trace_block_remap(blk_add_trace_remap);
896         unregister_trace_block_split(blk_add_trace_split);
897         unregister_trace_block_unplug_io(blk_add_trace_unplug_io);
898         unregister_trace_block_unplug_timer(blk_add_trace_unplug_timer);
899         unregister_trace_block_plug(blk_add_trace_plug);
900         unregister_trace_block_sleeprq(blk_add_trace_sleeprq);
901         unregister_trace_block_getrq(blk_add_trace_getrq);
902         unregister_trace_block_bio_queue(blk_add_trace_bio_queue);
903         unregister_trace_block_bio_frontmerge(blk_add_trace_bio_frontmerge);
904         unregister_trace_block_bio_backmerge(blk_add_trace_bio_backmerge);
905         unregister_trace_block_bio_complete(blk_add_trace_bio_complete);
906         unregister_trace_block_bio_bounce(blk_add_trace_bio_bounce);
907         unregister_trace_block_rq_complete(blk_add_trace_rq_complete);
908         unregister_trace_block_rq_requeue(blk_add_trace_rq_requeue);
909         unregister_trace_block_rq_issue(blk_add_trace_rq_issue);
910         unregister_trace_block_rq_insert(blk_add_trace_rq_insert);
911         unregister_trace_block_rq_abort(blk_add_trace_rq_abort);
912
913         tracepoint_synchronize_unregister();
914 }
915
916 /*
917  * struct blk_io_tracer formatting routines
918  */
919
920 static void fill_rwbs(char *rwbs, const struct blk_io_trace *t)
921 {
922         int i = 0;
923         int tc = t->action >> BLK_TC_SHIFT;
924
925         if (tc & BLK_TC_DISCARD)
926                 rwbs[i++] = 'D';
927         else if (tc & BLK_TC_WRITE)
928                 rwbs[i++] = 'W';
929         else if (t->bytes)
930                 rwbs[i++] = 'R';
931         else
932                 rwbs[i++] = 'N';
933
934         if (tc & BLK_TC_AHEAD)
935                 rwbs[i++] = 'A';
936         if (tc & BLK_TC_BARRIER)
937                 rwbs[i++] = 'B';
938         if (tc & BLK_TC_SYNC)
939                 rwbs[i++] = 'S';
940         if (tc & BLK_TC_META)
941                 rwbs[i++] = 'M';
942
943         rwbs[i] = '\0';
944 }
945
946 static inline
947 const struct blk_io_trace *te_blk_io_trace(const struct trace_entry *ent)
948 {
949         return (const struct blk_io_trace *)ent;
950 }
951
952 static inline const void *pdu_start(const struct trace_entry *ent)
953 {
954         return te_blk_io_trace(ent) + 1;
955 }
956
957 static inline u32 t_sec(const struct trace_entry *ent)
958 {
959         return te_blk_io_trace(ent)->bytes >> 9;
960 }
961
962 static inline unsigned long long t_sector(const struct trace_entry *ent)
963 {
964         return te_blk_io_trace(ent)->sector;
965 }
966
967 static inline __u16 t_error(const struct trace_entry *ent)
968 {
969         return te_blk_io_trace(ent)->error;
970 }
971
972 static __u64 get_pdu_int(const struct trace_entry *ent)
973 {
974         const __u64 *val = pdu_start(ent);
975         return be64_to_cpu(*val);
976 }
977
978 static void get_pdu_remap(const struct trace_entry *ent,
979                           struct blk_io_trace_remap *r)
980 {
981         const struct blk_io_trace_remap *__r = pdu_start(ent);
982         __u64 sector = __r->sector;
983
984         r->device = be32_to_cpu(__r->device);
985         r->device_from = be32_to_cpu(__r->device_from);
986         r->sector = be64_to_cpu(sector);
987 }
988
989 static int blk_log_action_iter(struct trace_iterator *iter, const char *act)
990 {
991         char rwbs[6];
992         unsigned long long ts  = iter->ts;
993         unsigned long nsec_rem = do_div(ts, NSEC_PER_SEC);
994         unsigned secs          = (unsigned long)ts;
995         const struct trace_entry *ent = iter->ent;
996         const struct blk_io_trace *t = (const struct blk_io_trace *)ent;
997
998         fill_rwbs(rwbs, t);
999
1000         return trace_seq_printf(&iter->seq,
1001                                 "%3d,%-3d %2d %5d.%09lu %5u %2s %3s ",
1002                                 MAJOR(t->device), MINOR(t->device), iter->cpu,
1003                                 secs, nsec_rem, ent->pid, act, rwbs);
1004 }
1005
1006 static int blk_log_action_seq(struct trace_seq *s, const struct blk_io_trace *t,
1007                               const char *act)
1008 {
1009         char rwbs[6];
1010         fill_rwbs(rwbs, t);
1011         return trace_seq_printf(s, "%3d,%-3d %2s %3s ",
1012                                 MAJOR(t->device), MINOR(t->device), act, rwbs);
1013 }
1014
1015 static int blk_log_generic(struct trace_seq *s, const struct trace_entry *ent)
1016 {
1017         char cmd[TASK_COMM_LEN];
1018
1019         trace_find_cmdline(ent->pid, cmd);
1020
1021         if (t_sec(ent))
1022                 return trace_seq_printf(s, "%llu + %u [%s]\n",
1023                                         t_sector(ent), t_sec(ent), cmd);
1024         return trace_seq_printf(s, "[%s]\n", cmd);
1025 }
1026
1027 static int blk_log_with_error(struct trace_seq *s,
1028                               const struct trace_entry *ent)
1029 {
1030         if (t_sec(ent))
1031                 return trace_seq_printf(s, "%llu + %u [%d]\n", t_sector(ent),
1032                                         t_sec(ent), t_error(ent));
1033         return trace_seq_printf(s, "%llu [%d]\n", t_sector(ent), t_error(ent));
1034 }
1035
1036 static int blk_log_remap(struct trace_seq *s, const struct trace_entry *ent)
1037 {
1038         struct blk_io_trace_remap r = { .device = 0, };
1039
1040         get_pdu_remap(ent, &r);
1041         return trace_seq_printf(s, "%llu + %u <- (%d,%d) %llu\n",
1042                                t_sector(ent),
1043                                t_sec(ent), MAJOR(r.device), MINOR(r.device),
1044                                (unsigned long long)r.sector);
1045 }
1046
1047 static int blk_log_plug(struct trace_seq *s, const struct trace_entry *ent)
1048 {
1049         char cmd[TASK_COMM_LEN];
1050
1051         trace_find_cmdline(ent->pid, cmd);
1052
1053         return trace_seq_printf(s, "[%s]\n", cmd);
1054 }
1055
1056 static int blk_log_unplug(struct trace_seq *s, const struct trace_entry *ent)
1057 {
1058         char cmd[TASK_COMM_LEN];
1059
1060         trace_find_cmdline(ent->pid, cmd);
1061
1062         return trace_seq_printf(s, "[%s] %llu\n", cmd, get_pdu_int(ent));
1063 }
1064
1065 static int blk_log_split(struct trace_seq *s, const struct trace_entry *ent)
1066 {
1067         char cmd[TASK_COMM_LEN];
1068
1069         trace_find_cmdline(ent->pid, cmd);
1070
1071         return trace_seq_printf(s, "%llu / %llu [%s]\n", t_sector(ent),
1072                                 get_pdu_int(ent), cmd);
1073 }
1074
1075 /*
1076  * struct tracer operations
1077  */
1078
1079 static void blk_tracer_print_header(struct seq_file *m)
1080 {
1081         if (!(blk_tracer_flags.val & TRACE_BLK_OPT_CLASSIC))
1082                 return;
1083         seq_puts(m, "# DEV   CPU TIMESTAMP     PID ACT FLG\n"
1084                     "#  |     |     |           |   |   |\n");
1085 }
1086
1087 static void blk_tracer_start(struct trace_array *tr)
1088 {
1089         blk_tracer_enabled = true;
1090         trace_flags &= ~TRACE_ITER_CONTEXT_INFO;
1091 }
1092
1093 static int blk_tracer_init(struct trace_array *tr)
1094 {
1095         blk_tr = tr;
1096         blk_tracer_start(tr);
1097         return 0;
1098 }
1099
1100 static void blk_tracer_stop(struct trace_array *tr)
1101 {
1102         blk_tracer_enabled = false;
1103         trace_flags |= TRACE_ITER_CONTEXT_INFO;
1104 }
1105
1106 static void blk_tracer_reset(struct trace_array *tr)
1107 {
1108         blk_tracer_stop(tr);
1109 }
1110
1111 static const struct {
1112         const char *act[2];
1113         int        (*print)(struct trace_seq *s, const struct trace_entry *ent);
1114 } what2act[] = {
1115         [__BLK_TA_QUEUE]        = {{  "Q", "queue" },      blk_log_generic },
1116         [__BLK_TA_BACKMERGE]    = {{  "M", "backmerge" },  blk_log_generic },
1117         [__BLK_TA_FRONTMERGE]   = {{  "F", "frontmerge" }, blk_log_generic },
1118         [__BLK_TA_GETRQ]        = {{  "G", "getrq" },      blk_log_generic },
1119         [__BLK_TA_SLEEPRQ]      = {{  "S", "sleeprq" },    blk_log_generic },
1120         [__BLK_TA_REQUEUE]      = {{  "R", "requeue" },    blk_log_with_error },
1121         [__BLK_TA_ISSUE]        = {{  "D", "issue" },      blk_log_generic },
1122         [__BLK_TA_COMPLETE]     = {{  "C", "complete" },   blk_log_with_error },
1123         [__BLK_TA_PLUG]         = {{  "P", "plug" },       blk_log_plug },
1124         [__BLK_TA_UNPLUG_IO]    = {{  "U", "unplug_io" },  blk_log_unplug },
1125         [__BLK_TA_UNPLUG_TIMER] = {{ "UT", "unplug_timer" }, blk_log_unplug },
1126         [__BLK_TA_INSERT]       = {{  "I", "insert" },     blk_log_generic },
1127         [__BLK_TA_SPLIT]        = {{  "X", "split" },      blk_log_split },
1128         [__BLK_TA_BOUNCE]       = {{  "B", "bounce" },     blk_log_generic },
1129         [__BLK_TA_REMAP]        = {{  "A", "remap" },      blk_log_remap },
1130 };
1131
1132 static enum print_line_t blk_trace_event_print(struct trace_iterator *iter,
1133                                                int flags)
1134 {
1135         struct trace_seq *s = &iter->seq;
1136         const struct blk_io_trace *t = (struct blk_io_trace *)iter->ent;
1137         const u16 what = t->action & ((1 << BLK_TC_SHIFT) - 1);
1138         int ret;
1139
1140         if (!trace_print_context(iter))
1141                 return TRACE_TYPE_PARTIAL_LINE;
1142
1143         if (unlikely(what == 0 || what >= ARRAY_SIZE(what2act)))
1144                 ret = trace_seq_printf(s, "Bad pc action %x\n", what);
1145         else {
1146                 const bool long_act = !!(trace_flags & TRACE_ITER_VERBOSE);
1147                 ret = blk_log_action_seq(s, t, what2act[what].act[long_act]);
1148                 if (ret)
1149                         ret = what2act[what].print(s, iter->ent);
1150         }
1151
1152         return ret ? TRACE_TYPE_HANDLED : TRACE_TYPE_PARTIAL_LINE;
1153 }
1154
1155 static int blk_trace_synthesize_old_trace(struct trace_iterator *iter)
1156 {
1157         struct trace_seq *s = &iter->seq;
1158         struct blk_io_trace *t = (struct blk_io_trace *)iter->ent;
1159         const int offset = offsetof(struct blk_io_trace, sector);
1160         struct blk_io_trace old = {
1161                 .magic    = BLK_IO_TRACE_MAGIC | BLK_IO_TRACE_VERSION,
1162                 .time     = iter->ts,
1163         };
1164
1165         if (!trace_seq_putmem(s, &old, offset))
1166                 return 0;
1167         return trace_seq_putmem(s, &t->sector,
1168                                 sizeof(old) - offset + t->pdu_len);
1169 }
1170
1171 static enum print_line_t
1172 blk_trace_event_print_binary(struct trace_iterator *iter, int flags)
1173 {
1174         return blk_trace_synthesize_old_trace(iter) ?
1175                         TRACE_TYPE_HANDLED : TRACE_TYPE_PARTIAL_LINE;
1176 }
1177
1178 static enum print_line_t blk_tracer_print_line(struct trace_iterator *iter)
1179 {
1180         const struct blk_io_trace *t;
1181         u16 what;
1182         int ret;
1183
1184         if (!(blk_tracer_flags.val & TRACE_BLK_OPT_CLASSIC))
1185                 return TRACE_TYPE_UNHANDLED;
1186
1187         t = (const struct blk_io_trace *)iter->ent;
1188         what = t->action & ((1 << BLK_TC_SHIFT) - 1);
1189
1190         if (unlikely(what == 0 || what >= ARRAY_SIZE(what2act)))
1191                 ret = trace_seq_printf(&iter->seq, "Bad pc action %x\n", what);
1192         else {
1193                 const bool long_act = !!(trace_flags & TRACE_ITER_VERBOSE);
1194                 ret = blk_log_action_iter(iter, what2act[what].act[long_act]);
1195                 if (ret)
1196                         ret = what2act[what].print(&iter->seq, iter->ent);
1197         }
1198
1199         return ret ? TRACE_TYPE_HANDLED : TRACE_TYPE_PARTIAL_LINE;
1200 }
1201
1202 static struct tracer blk_tracer __read_mostly = {
1203         .name           = "blk",
1204         .init           = blk_tracer_init,
1205         .reset          = blk_tracer_reset,
1206         .start          = blk_tracer_start,
1207         .stop           = blk_tracer_stop,
1208         .print_header   = blk_tracer_print_header,
1209         .print_line     = blk_tracer_print_line,
1210         .flags          = &blk_tracer_flags,
1211 };
1212
1213 static struct trace_event trace_blk_event = {
1214         .type           = TRACE_BLK,
1215         .trace          = blk_trace_event_print,
1216         .binary         = blk_trace_event_print_binary,
1217 };
1218
1219 static int __init init_blk_tracer(void)
1220 {
1221         if (!register_ftrace_event(&trace_blk_event)) {
1222                 pr_warning("Warning: could not register block events\n");
1223                 return 1;
1224         }
1225
1226         if (register_tracer(&blk_tracer) != 0) {
1227                 pr_warning("Warning: could not register the block tracer\n");
1228                 unregister_ftrace_event(&trace_blk_event);
1229                 return 1;
1230         }
1231
1232         return 0;
1233 }
1234
1235 device_initcall(init_blk_tracer);
1236
1237 static int blk_trace_remove_queue(struct request_queue *q)
1238 {
1239         struct blk_trace *bt;
1240
1241         bt = xchg(&q->blk_trace, NULL);
1242         if (bt == NULL)
1243                 return -EINVAL;
1244
1245         if (atomic_dec_and_test(&blk_probes_ref))
1246                 blk_unregister_tracepoints();
1247
1248         blk_trace_free(bt);
1249         return 0;
1250 }
1251
1252 /*
1253  * Setup everything required to start tracing
1254  */
1255 static int blk_trace_setup_queue(struct request_queue *q, dev_t dev)
1256 {
1257         struct blk_trace *old_bt, *bt = NULL;
1258
1259         bt = kzalloc(sizeof(*bt), GFP_KERNEL);
1260         if (!bt)
1261                 return -ENOMEM;
1262
1263         bt->dev = dev;
1264         bt->act_mask = (u16)-1;
1265         bt->end_lba = -1ULL;
1266
1267         old_bt = xchg(&q->blk_trace, bt);
1268         if (old_bt != NULL) {
1269                 (void)xchg(&q->blk_trace, old_bt);
1270                 kfree(bt);
1271                 return -EBUSY;
1272         }
1273
1274         if (atomic_inc_return(&blk_probes_ref) == 1)
1275                 blk_register_tracepoints();
1276
1277         return 0;
1278 }
1279
1280 /*
1281  * sysfs interface to enable and configure tracing
1282  */
1283
1284 static ssize_t sysfs_blk_trace_attr_show(struct device *dev,
1285                                          struct device_attribute *attr,
1286                                          char *buf);
1287 static ssize_t sysfs_blk_trace_attr_store(struct device *dev,
1288                                           struct device_attribute *attr,
1289                                           const char *buf, size_t count);
1290 #define BLK_TRACE_DEVICE_ATTR(_name) \
1291         DEVICE_ATTR(_name, S_IRUGO | S_IWUSR, \
1292                     sysfs_blk_trace_attr_show, \
1293                     sysfs_blk_trace_attr_store)
1294
1295 static BLK_TRACE_DEVICE_ATTR(enable);
1296 static BLK_TRACE_DEVICE_ATTR(act_mask);
1297 static BLK_TRACE_DEVICE_ATTR(pid);
1298 static BLK_TRACE_DEVICE_ATTR(start_lba);
1299 static BLK_TRACE_DEVICE_ATTR(end_lba);
1300
1301 static struct attribute *blk_trace_attrs[] = {
1302         &dev_attr_enable.attr,
1303         &dev_attr_act_mask.attr,
1304         &dev_attr_pid.attr,
1305         &dev_attr_start_lba.attr,
1306         &dev_attr_end_lba.attr,
1307         NULL
1308 };
1309
1310 struct attribute_group blk_trace_attr_group = {
1311         .name  = "trace",
1312         .attrs = blk_trace_attrs,
1313 };
1314
1315 static const struct {
1316         int mask;
1317         const char *str;
1318 } mask_maps[] = {
1319         { BLK_TC_READ,          "read"          },
1320         { BLK_TC_WRITE,         "write"         },
1321         { BLK_TC_BARRIER,       "barrier"       },
1322         { BLK_TC_SYNC,          "sync"          },
1323         { BLK_TC_QUEUE,         "queue"         },
1324         { BLK_TC_REQUEUE,       "requeue"       },
1325         { BLK_TC_ISSUE,         "issue"         },
1326         { BLK_TC_COMPLETE,      "complete"      },
1327         { BLK_TC_FS,            "fs"            },
1328         { BLK_TC_PC,            "pc"            },
1329         { BLK_TC_AHEAD,         "ahead"         },
1330         { BLK_TC_META,          "meta"          },
1331         { BLK_TC_DISCARD,       "discard"       },
1332         { BLK_TC_DRV_DATA,      "drv_data"      },
1333 };
1334
1335 static int blk_trace_str2mask(const char *str)
1336 {
1337         int i;
1338         int mask = 0;
1339         char *s, *token;
1340
1341         s = kstrdup(str, GFP_KERNEL);
1342         if (s == NULL)
1343                 return -ENOMEM;
1344         s = strstrip(s);
1345
1346         while (1) {
1347                 token = strsep(&s, ",");
1348                 if (token == NULL)
1349                         break;
1350
1351                 if (*token == '\0')
1352                         continue;
1353
1354                 for (i = 0; i < ARRAY_SIZE(mask_maps); i++) {
1355                         if (strcasecmp(token, mask_maps[i].str) == 0) {
1356                                 mask |= mask_maps[i].mask;
1357                                 break;
1358                         }
1359                 }
1360                 if (i == ARRAY_SIZE(mask_maps)) {
1361                         mask = -EINVAL;
1362                         break;
1363                 }
1364         }
1365         kfree(s);
1366
1367         return mask;
1368 }
1369
1370 static ssize_t blk_trace_mask2str(char *buf, int mask)
1371 {
1372         int i;
1373         char *p = buf;
1374
1375         for (i = 0; i < ARRAY_SIZE(mask_maps); i++) {
1376                 if (mask & mask_maps[i].mask) {
1377                         p += sprintf(p, "%s%s",
1378                                     (p == buf) ? "" : ",", mask_maps[i].str);
1379                 }
1380         }
1381         *p++ = '\n';
1382
1383         return p - buf;
1384 }
1385
1386 static struct request_queue *blk_trace_get_queue(struct block_device *bdev)
1387 {
1388         if (bdev->bd_disk == NULL)
1389                 return NULL;
1390
1391         return bdev_get_queue(bdev);
1392 }
1393
1394 static ssize_t sysfs_blk_trace_attr_show(struct device *dev,
1395                                          struct device_attribute *attr,
1396                                          char *buf)
1397 {
1398         struct hd_struct *p = dev_to_part(dev);
1399         struct request_queue *q;
1400         struct block_device *bdev;
1401         ssize_t ret = -ENXIO;
1402
1403         lock_kernel();
1404         bdev = bdget(part_devt(p));
1405         if (bdev == NULL)
1406                 goto out_unlock_kernel;
1407
1408         q = blk_trace_get_queue(bdev);
1409         if (q == NULL)
1410                 goto out_bdput;
1411
1412         mutex_lock(&bdev->bd_mutex);
1413
1414         if (attr == &dev_attr_enable) {
1415                 ret = sprintf(buf, "%u\n", !!q->blk_trace);
1416                 goto out_unlock_bdev;
1417         }
1418
1419         if (q->blk_trace == NULL)
1420                 ret = sprintf(buf, "disabled\n");
1421         else if (attr == &dev_attr_act_mask)
1422                 ret = blk_trace_mask2str(buf, q->blk_trace->act_mask);
1423         else if (attr == &dev_attr_pid)
1424                 ret = sprintf(buf, "%u\n", q->blk_trace->pid);
1425         else if (attr == &dev_attr_start_lba)
1426                 ret = sprintf(buf, "%llu\n", q->blk_trace->start_lba);
1427         else if (attr == &dev_attr_end_lba)
1428                 ret = sprintf(buf, "%llu\n", q->blk_trace->end_lba);
1429
1430 out_unlock_bdev:
1431         mutex_unlock(&bdev->bd_mutex);
1432 out_bdput:
1433         bdput(bdev);
1434 out_unlock_kernel:
1435         unlock_kernel();
1436         return ret;
1437 }
1438
1439 static ssize_t sysfs_blk_trace_attr_store(struct device *dev,
1440                                           struct device_attribute *attr,
1441                                           const char *buf, size_t count)
1442 {
1443         struct block_device *bdev;
1444         struct request_queue *q;
1445         struct hd_struct *p;
1446         u64 value;
1447         ssize_t ret = -EINVAL;
1448
1449         if (count == 0)
1450                 goto out;
1451
1452         if (attr == &dev_attr_act_mask) {
1453                 if (sscanf(buf, "%llx", &value) != 1) {
1454                         /* Assume it is a list of trace category names */
1455                         ret = blk_trace_str2mask(buf);
1456                         if (ret < 0)
1457                                 goto out;
1458                         value = ret;
1459                 }
1460         } else if (sscanf(buf, "%llu", &value) != 1)
1461                 goto out;
1462
1463         ret = -ENXIO;
1464
1465         lock_kernel();
1466         p = dev_to_part(dev);
1467         bdev = bdget(part_devt(p));
1468         if (bdev == NULL)
1469                 goto out_unlock_kernel;
1470
1471         q = blk_trace_get_queue(bdev);
1472         if (q == NULL)
1473                 goto out_bdput;
1474
1475         mutex_lock(&bdev->bd_mutex);
1476
1477         if (attr == &dev_attr_enable) {
1478                 if (value)
1479                         ret = blk_trace_setup_queue(q, bdev->bd_dev);
1480                 else
1481                         ret = blk_trace_remove_queue(q);
1482                 goto out_unlock_bdev;
1483         }
1484
1485         ret = 0;
1486         if (q->blk_trace == NULL)
1487                 ret = blk_trace_setup_queue(q, bdev->bd_dev);
1488
1489         if (ret == 0) {
1490                 if (attr == &dev_attr_act_mask)
1491                         q->blk_trace->act_mask = value;
1492                 else if (attr == &dev_attr_pid)
1493                         q->blk_trace->pid = value;
1494                 else if (attr == &dev_attr_start_lba)
1495                         q->blk_trace->start_lba = value;
1496                 else if (attr == &dev_attr_end_lba)
1497                         q->blk_trace->end_lba = value;
1498         }
1499
1500 out_unlock_bdev:
1501         mutex_unlock(&bdev->bd_mutex);
1502 out_bdput:
1503         bdput(bdev);
1504 out_unlock_kernel:
1505         unlock_kernel();
1506 out:
1507         return ret ? ret : count;
1508 }
1509