~percona-dev/percona-server/5.1.57-fix_bug_784378

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
# name       : slow_extended.patch
# introduced : 11 or before
# maintainer : Oleg
#
#!!! notice !!!
# Any small change to this file in the main branch
# should be done or reviewed by the maintainer!
diff -ruN a/include/mysql/plugin.h b/include/mysql/plugin.h
--- a/include/mysql/plugin.h	2010-11-29 13:38:00.000000000 +0300
+++ b/include/mysql/plugin.h	2010-12-24 13:57:45.000000000 +0300
@@ -694,6 +694,17 @@
 /* Increments the row counter, see THD::row_count */
 void thd_inc_row_count(MYSQL_THD thd);
 
+void increment_thd_innodb_stats(MYSQL_THD thd,
+                    unsigned long long trx_id,
+                    long io_reads,
+                    long long io_read,
+                    long io_reads_wait_timer,
+                    long lock_que_wait_timer,
+                    long que_wait_timer,
+                    long page_access);
+unsigned long thd_log_slow_verbosity(const MYSQL_THD thd);
+int thd_opt_slow_log();
+#define EXTENDED_SLOWLOG
 /**
   Create a temporary file.
 
diff -ruN a/include/mysql/plugin.h.pp b/include/mysql/plugin.h.pp
--- a/include/mysql/plugin.h.pp	2010-11-29 13:38:05.000000000 +0300
+++ b/include/mysql/plugin.h.pp	2010-12-24 13:57:45.000000000 +0300
@@ -122,6 +122,16 @@
 char *thd_security_context(void* thd, char *buffer, unsigned int length,
                            unsigned int max_query_len);
 void thd_inc_row_count(void* thd);
+void increment_thd_innodb_stats(void* thd,
+                    unsigned long long trx_id,
+                    long io_reads,
+                    long long io_read,
+                    long io_reads_wait_timer,
+                    long lock_que_wait_timer,
+                    long que_wait_timer,
+                    long page_access);
+unsigned long thd_log_slow_verbosity(const void* thd);
+int thd_opt_slow_log();
 int mysql_tmpfile(const char *prefix);
 int thd_killed(const void* thd);
 unsigned long thd_get_thread_id(const void* thd);
diff -ruN /dev/null b/patch_info/slow_extended.info
--- /dev/null	1970-01-01 00:00:00.000000000 +0000
+++ b/patch_info/slow_extended.info	2010-12-24 13:57:45.000000000 +0300
@@ -0,0 +1,24 @@
+File=slow_extended.patch
+Name=Extended statistics in slow.log (not InnoDB part)
+Version=1.3
+Author=Percona <info@percona.com>
+License=GPL
+Comment=
+Changelog
+2008-11-26
+YK: Fix inefficient determination of trx, Make not to call useless gettimeofday when don't use slow log. Make log_slow_queries dynamic (bool).
+
+2008-11-07
+VT: Moved log_slow_rate_limit in SHOW VARIABLE into right place
+
+2008-11
+Arjen Lentz: Fixups (backward compatibility) by Arjen Lentz <arjen@openquery.com.au>
+
+2010-07
+1) Fix overflow of query time and lock time (Bug 600360) (slow_extended_fix_overflow.patch merged)
+2) Control global slow feature merged (control_global_slow.patch merged)
+3) Microseconds in slow query log merged (microseconds_in_slow_query_log.patch merged)
+4) Now use_global_long_query_time and use_global_log_slow_control are synonims. Add value "all" for use_global_log_slow_control (contol-global_slow-2.patch merged)
+5) Fix innodb_stats on replication (Bug 600684)
+6) Change variable types (system/command-line)
+
diff -ruN a/scripts/mysqldumpslow.sh b/scripts/mysqldumpslow.sh
--- a/scripts/mysqldumpslow.sh	2010-11-29 13:38:13.000000000 +0300
+++ b/scripts/mysqldumpslow.sh	2010-12-24 13:57:45.000000000 +0300
@@ -101,8 +101,8 @@
     s/^#? Time: \d{6}\s+\d+:\d+:\d+.*\n//;
     my ($user,$host) = s/^#? User\@Host:\s+(\S+)\s+\@\s+(\S+).*\n// ? ($1,$2) : ('','');
 
-    s/^# Query_time: ([0-9.]+)\s+Lock_time: ([0-9.]+)\s+Rows_sent: ([0-9.]+).*\n//;
-    my ($t, $l, $r) = ($1, $2, $3);
+    s/^# Query_time: (\d+(\.\d+)?)  Lock_time: (\d+(\.\d+)?)  Rows_sent: (\d+(\.\d+)?).*\n//;
+    my ($t, $l, $r)= ($1, $3, $5);
     $t -= $l unless $opt{l};
 
     # remove fluff that mysqld writes to log when it (re)starts:
diff -ruN a/sql/event_scheduler.cc b/sql/event_scheduler.cc
--- a/sql/event_scheduler.cc	2010-11-29 13:38:10.000000000 +0300
+++ b/sql/event_scheduler.cc	2010-12-24 13:57:45.000000000 +0300
@@ -193,6 +193,7 @@
   thd->client_capabilities|= CLIENT_MULTI_RESULTS;
   pthread_mutex_lock(&LOCK_thread_count);
   thd->thread_id= thd->variables.pseudo_thread_id= thread_id++;
+  thd->write_to_slow_log= TRUE;
   pthread_mutex_unlock(&LOCK_thread_count);
 
   /*
diff -ruN a/sql/filesort.cc b/sql/filesort.cc
--- a/sql/filesort.cc	2010-11-29 13:38:10.000000000 +0300
+++ b/sql/filesort.cc	2010-12-24 13:57:45.000000000 +0300
@@ -190,6 +190,7 @@
   {
     status_var_increment(thd->status_var.filesort_scan_count);
   }
+  thd->query_plan_flags|= QPLAN_FILESORT;
 #ifdef CAN_TRUST_RANGE
   if (select && select->quick && select->quick->records > 0L)
   {
@@ -255,6 +256,7 @@
   }
   else
   {
+    thd->query_plan_flags|= QPLAN_FILESORT_DISK;
     if (table_sort.buffpek && table_sort.buffpek_len < maxbuffer)
     {
       x_free(table_sort.buffpek);
@@ -1203,6 +1205,7 @@
   DBUG_ENTER("merge_buffers");
 
   status_var_increment(current_thd->status_var.filesort_merge_passes);
+  current_thd->query_plan_fsort_passes++;
   if (param->not_killable)
   {
     killed= &not_killable;
diff -ruN a/sql/log.cc b/sql/log.cc
--- a/sql/log.cc	2010-11-29 13:37:59.000000000 +0300
+++ b/sql/log.cc	2010-12-24 14:18:38.000000000 +0300
@@ -524,11 +524,13 @@
 */
 
 bool Log_to_csv_event_handler::
-  log_slow(THD *thd, time_t current_time, time_t query_start_arg,
+  log_slow(THD *thd, ulonglong current_utime, time_t query_start_arg,
            const char *user_host, uint user_host_len,
            ulonglong query_utime, ulonglong lock_utime, bool is_command,
            const char *sql_text, uint sql_text_len)
 {
+  time_t current_time= my_time_possible_from_micro(current_utime);
+
   TABLE_LIST table_list;
   TABLE *table;
   bool result= TRUE;
@@ -754,14 +756,14 @@
 /** Wrapper around MYSQL_LOG::write() for slow log. */
 
 bool Log_to_file_event_handler::
-  log_slow(THD *thd, time_t current_time, time_t query_start_arg,
+  log_slow(THD *thd, ulonglong current_utime, time_t query_start_arg,
            const char *user_host, uint user_host_len,
            ulonglong query_utime, ulonglong lock_utime, bool is_command,
            const char *sql_text, uint sql_text_len)
 {
   Silence_log_table_errors error_handler;
   thd->push_internal_handler(&error_handler);
-  bool retval= mysql_slow_log.write(thd, current_time, query_start_arg,
+  bool retval= mysql_slow_log.write(thd, current_utime, query_start_arg,
                                     user_host, user_host_len,
                                     query_utime, lock_utime, is_command,
                                     sql_text, sql_text_len);
@@ -987,7 +989,7 @@
     /* fill in user_host value: the format is "%s[%s] @ %s [%s]" */
     user_host_len= (strxnmov(user_host_buff, MAX_USER_HOST_SIZE,
                              sctx->priv_user ? sctx->priv_user : "", "[",
-                             sctx->user ? sctx->user : "", "] @ ",
+                             sctx->user ? sctx->user : (thd->slave_thread ? "SQL_SLAVE" : ""), "] @ ",
                              sctx->host ? sctx->host : "", " [",
                              sctx->ip ? sctx->ip : "", "]", NullS) -
                     user_host_buff);
@@ -995,8 +997,22 @@
     current_time= my_time_possible_from_micro(current_utime);
     if (thd->start_utime)
     {
-      query_utime= (current_utime - thd->start_utime);
-      lock_utime=  (thd->utime_after_lock - thd->start_utime);
+      if(current_utime < thd->start_utime)
+      {
+        query_utime= 0;
+      }
+      else
+      {
+        query_utime= (current_utime - thd->start_utime);
+      }
+      if(thd->utime_after_lock < thd->start_utime)
+      {
+        lock_utime= 0;
+      }
+      else
+      {
+        lock_utime= (thd->utime_after_lock - thd->start_utime);
+      }
     }
     else
     {
@@ -1010,8 +1026,21 @@
       query_length= command_name[thd->command].length;
     }
 
+    if (!query_length)
+    {
+      thd->sent_row_count= thd->examined_row_count= 0;
+      thd->row_count= 0;
+      thd->orig_row_count= 0;
+      thd->bytes_sent_old= thd->status_var.bytes_sent;
+      thd->tmp_tables_used= thd->tmp_tables_disk_used= 0;
+      thd->tmp_tables_size= 0;
+      thd->innodb_was_used= FALSE;
+      thd->query_plan_flags= QPLAN_NONE;
+      thd->query_plan_fsort_passes= 0;
+    }
+
     for (current_handler= slow_log_handler_list; *current_handler ;)
-      error= (*current_handler++)->log_slow(thd, current_time, thd->start_time,
+      error= (*current_handler++)->log_slow(thd, current_utime, thd->start_time,
                                             user_host_buff, user_host_len,
                                             query_utime, lock_utime, is_command,
                                             query, query_length) || error;
@@ -2282,12 +2311,13 @@
     TRUE - error occured
 */
 
-bool MYSQL_QUERY_LOG::write(THD *thd, time_t current_time,
+bool MYSQL_QUERY_LOG::write(THD *thd, ulonglong current_utime,
                             time_t query_start_arg, const char *user_host,
                             uint user_host_len, ulonglong query_utime,
                             ulonglong lock_utime, bool is_command,
                             const char *sql_text, uint sql_text_len)
 {
+  time_t current_time= my_time_possible_from_micro(current_utime);
   bool error= 0;
   DBUG_ENTER("MYSQL_QUERY_LOG::write");
 
@@ -2309,17 +2339,28 @@
 
     if (!(specialflag & SPECIAL_SHORT_LOG_FORMAT))
     {
-      if (current_time != last_time)
+      if (opt_log_slow_timestamp_every || current_time != last_time)
       {
         last_time= current_time;
         struct tm start;
         localtime_r(&current_time, &start);
-
-        buff_len= my_snprintf(buff, sizeof buff,
-                              "# Time: %02d%02d%02d %2d:%02d:%02d\n",
-                              start.tm_year % 100, start.tm_mon + 1,
-                              start.tm_mday, start.tm_hour,
-                              start.tm_min, start.tm_sec);
+	if(opt_slow_query_log_microseconds_timestamp)
+	{
+	  ulonglong microsecond = current_utime % (1000 * 1000);
+	  buff_len= snprintf(buff, sizeof buff,
+	    "# Time: %02d%02d%02d %2d:%02d:%02d.%010lld\n",
+            start.tm_year % 100, start.tm_mon + 1,
+	    start.tm_mday, start.tm_hour,
+	    start.tm_min, start.tm_sec,microsecond);
+	}
+	else
+	{
+	  buff_len= my_snprintf(buff, sizeof buff,
+	    "# Time: %02d%02d%02d %2d:%02d:%02d\n",
+            start.tm_year % 100, start.tm_mon + 1,
+	    start.tm_mday, start.tm_hour,
+	    start.tm_min, start.tm_sec);
+	}
 
         /* Note that my_b_write() assumes it knows the length for this */
         if (my_b_write(&log_file, (uchar*) buff, buff_len))
@@ -2337,12 +2378,64 @@
     sprintf(query_time_buff, "%.6f", ulonglong2double(query_utime)/1000000.0);
     sprintf(lock_time_buff,  "%.6f", ulonglong2double(lock_utime)/1000000.0);
     if (my_b_printf(&log_file,
-                    "# Query_time: %s  Lock_time: %s"
-                    " Rows_sent: %lu  Rows_examined: %lu\n",
+                    "# Thread_id: %lu  Schema: %s  Last_errno: %u  Killed: %u\n" \
+                    "# Query_time: %s  Lock_time: %s  Rows_sent: %lu  Rows_examined: %lu  Rows_affected: %lu  Rows_read: %lu\n"
+                    "# Bytes_sent: %lu  Tmp_tables: %lu  Tmp_disk_tables: %lu  Tmp_table_sizes: %lu\n",
+                    (ulong) thd->thread_id, (thd->db ? thd->db : ""),
+                    thd->last_errno, (uint) thd->killed,
                     query_time_buff, lock_time_buff,
                     (ulong) thd->sent_row_count,
-                    (ulong) thd->examined_row_count) == (uint) -1)
+                    (ulong) thd->examined_row_count,
+                    ((long) thd->row_count_func > 0 ) ? (ulong) thd->row_count_func : 0,
+                    thd->row_count - thd->orig_row_count + 1,
+                    (ulong) (thd->status_var.bytes_sent - thd->bytes_sent_old),
+                    (ulong) thd->tmp_tables_used,
+                    (ulong) thd->tmp_tables_disk_used,
+                    (ulong) thd->tmp_tables_size) == (uint) -1)
       tmp_errno= errno;
+    if (thd->innodb_was_used)
+    {
+      char buf[20];
+      snprintf(buf, 20, "%llX", thd->innodb_trx_id);
+      if (my_b_printf(&log_file,
+                    "# InnoDB_trx_id: %s\n", buf) == (uint) -1)
+        tmp_errno=errno;
+    }
+    if ((thd->variables.log_slow_verbosity & SLOG_V_QUERY_PLAN) &&
+         my_b_printf(&log_file,
+                    "# QC_Hit: %s  Full_scan: %s  Full_join: %s  Tmp_table: %s  Tmp_table_on_disk: %s\n" \
+                    "# Filesort: %s  Filesort_on_disk: %s  Merge_passes: %lu\n",
+                    ((thd->query_plan_flags & QPLAN_QC) ? "Yes" : "No"),
+                    ((thd->query_plan_flags & QPLAN_FULL_SCAN) ? "Yes" : "No"),
+                    ((thd->query_plan_flags & QPLAN_FULL_JOIN) ? "Yes" : "No"),
+                    ((thd->query_plan_flags & QPLAN_TMP_TABLE) ? "Yes" : "No"),
+                    ((thd->query_plan_flags & QPLAN_TMP_DISK) ? "Yes" : "No"),
+                    ((thd->query_plan_flags & QPLAN_FILESORT) ? "Yes" : "No"),
+                    ((thd->query_plan_flags & QPLAN_FILESORT_DISK) ? "Yes" : "No"),
+                    thd->query_plan_fsort_passes) == (uint) -1)
+      tmp_errno=errno;
+    if ((thd->variables.log_slow_verbosity & SLOG_V_INNODB) && thd->innodb_was_used)
+    {
+      char buf[3][20];
+      snprintf(buf[0], 20, "%.6f", thd->innodb_io_reads_wait_timer / 1000000.0);
+      snprintf(buf[1], 20, "%.6f", thd->innodb_lock_que_wait_timer / 1000000.0);
+      snprintf(buf[2], 20, "%.6f", thd->innodb_innodb_que_wait_timer / 1000000.0);
+      if (my_b_printf(&log_file,
+                      "#   InnoDB_IO_r_ops: %lu  InnoDB_IO_r_bytes: %lu  InnoDB_IO_r_wait: %s\n" \
+                      "#   InnoDB_rec_lock_wait: %s  InnoDB_queue_wait: %s\n" \
+                      "#   InnoDB_pages_distinct: %lu\n",
+                      (ulong) thd->innodb_io_reads,
+                      (ulong) thd->innodb_io_read,
+                      buf[0], buf[1], buf[2],
+                      (ulong) thd->innodb_page_access) == (uint) -1)
+        tmp_errno= errno;
+    } 
+    else
+    {
+      if ((thd->variables.log_slow_verbosity & SLOG_V_INNODB) &&
+          my_b_printf(&log_file,"# No InnoDB statistics available for this query\n") == (uint) -1)
+        tmp_errno= errno;
+    }
     if (thd->db && strcmp(thd->db, db))
     {						// Database changed
       if (my_b_printf(&log_file,"use %s;\n",thd->db) == (uint) -1)
diff -ruN a/sql/log.h b/sql/log.h
--- a/sql/log.h	2010-11-29 13:38:00.000000000 +0300
+++ b/sql/log.h	2010-12-24 13:57:45.000000000 +0300
@@ -211,7 +211,7 @@
              uint user_host_len, int thread_id,
              const char *command_type, uint command_type_len,
              const char *sql_text, uint sql_text_len);
-  bool write(THD *thd, time_t current_time, time_t query_start_arg,
+  bool write(THD *thd, ulonglong current_utime, time_t query_start_arg,
              const char *user_host, uint user_host_len,
              ulonglong query_utime, ulonglong lock_utime, bool is_command,
              const char *sql_text, uint sql_text_len);
@@ -425,7 +425,7 @@
   virtual bool init()= 0;
   virtual void cleanup()= 0;
 
-  virtual bool log_slow(THD *thd, time_t current_time,
+  virtual bool log_slow(THD *thd, ulonglong current_utime,
                         time_t query_start_arg, const char *user_host,
                         uint user_host_len, ulonglong query_utime,
                         ulonglong lock_utime, bool is_command,
@@ -454,7 +454,7 @@
   virtual bool init();
   virtual void cleanup();
 
-  virtual bool log_slow(THD *thd, time_t current_time,
+  virtual bool log_slow(THD *thd, ulonglong current_utime,
                         time_t query_start_arg, const char *user_host,
                         uint user_host_len, ulonglong query_utime,
                         ulonglong lock_utime, bool is_command,
@@ -486,7 +486,7 @@
   virtual bool init();
   virtual void cleanup();
 
-  virtual bool log_slow(THD *thd, time_t current_time,
+  virtual bool log_slow(THD *thd, ulonglong current_utime,
                         time_t query_start_arg, const char *user_host,
                         uint user_host_len, ulonglong query_utime,
                         ulonglong lock_utime, bool is_command,
diff -ruN a/sql/log_event.cc b/sql/log_event.cc
--- a/sql/log_event.cc	2010-11-29 13:37:59.000000000 +0300
+++ b/sql/log_event.cc	2010-12-24 13:57:45.000000000 +0300
@@ -3090,6 +3090,7 @@
   LEX_STRING new_db;
   int expected_error,actual_error= 0;
   HA_CREATE_INFO db_options;
+  bool process_log_slow_statement= false;
 
   /*
     Colleagues: please never free(thd->catalog) in MySQL. This would
@@ -3271,19 +3272,7 @@
       /* Execute the query (note that we bypass dispatch_command()) */
       const char* found_semicolon= NULL;
       mysql_parse(thd, thd->query(), thd->query_length(), &found_semicolon);
-      log_slow_statement(thd);
-
-      /*
-        Resetting the enable_slow_log thd variable.
-
-        We need to reset it back to the opt_log_slow_slave_statements
-        value after the statement execution (and slow logging
-        is done). It might have changed if the statement was an
-        admin statement (in which case, down in mysql_parse execution
-        thd->enable_slow_log is set to the value of
-        opt_log_slow_admin_statements).
-      */
-      thd->enable_slow_log= opt_log_slow_slave_statements;
+      process_log_slow_statement= true;
     }
     else
     {
@@ -3428,11 +3417,27 @@
     don't suffer from these assignments to 0 as DROP TEMPORARY
     TABLE uses the db.table syntax.
   */
+  close_thread_tables(thd);      
+  if(process_log_slow_statement)
+  {
+      log_slow_statement(thd);
+
+      /*
+        Resetting the enable_slow_log thd variable.
+
+        We need to reset it back to the opt_log_slow_slave_statements
+        value after the statement execution (and slow logging
+        is done). It might have changed if the statement was an
+        admin statement (in which case, down in mysql_parse execution
+        thd->enable_slow_log is set to the value of
+        opt_log_slow_admin_statements).
+      */
+      thd->enable_slow_log= opt_log_slow_slave_statements;
+  }
   thd->catalog= 0;
   thd->set_db(NULL, 0);                 /* will free the current database */
   thd->set_query(NULL, 0);
   DBUG_PRINT("info", ("end: query= 0"));
-  close_thread_tables(thd);      
   /*
     As a disk space optimization, future masters will not log an event for
     LAST_INSERT_ID() if that function returned 0 (and thus they will be able
diff -ruN a/sql/mysql_priv.h b/sql/mysql_priv.h
--- a/sql/mysql_priv.h	2010-12-24 13:57:33.000000000 +0300
+++ b/sql/mysql_priv.h	2010-12-24 13:57:45.000000000 +0300
@@ -638,6 +638,106 @@
 
 #define STRING_BUFFER_USUAL_SIZE 80
 
+/* Slow log */
+
+struct msl_opts
+{
+  ulong val;
+  const char *name;
+};
+
+/* use global log slow control */
+#define SLOG_UG_NONE                        (1UL << 0)
+#define SLOG_UG_LOG_SLOW_FILTER             (1UL << 1)
+#define SLOG_UG_LOG_SLOW_RATE_LIMIT         (1UL << 2)
+#define SLOG_UG_LOG_SLOW_VERBOSITY          (1UL << 3)
+#define SLOG_UG_LONG_QUERY_TIME             (1UL << 4)
+#define SLOG_UG_MIN_EXAMINED_ROW_LIMIT      (1UL << 5)
+#define SLOG_UG_ALL                         SLOG_UG_LOG_SLOW_FILTER | SLOG_UG_LOG_SLOW_RATE_LIMIT | SLOG_UG_LOG_SLOW_VERBOSITY | SLOG_UG_LONG_QUERY_TIME | SLOG_UG_MIN_EXAMINED_ROW_LIMIT
+/* ... */
+#define SLOG_UG_INVALID                     1##UL << 31
+
+static const struct msl_opts slog_use_global[]=
+  {
+    /* Basic flags */
+    { SLOG_UG_NONE                      , "none" },
+    { SLOG_UG_LOG_SLOW_FILTER           , "log_slow_filter" },
+    { SLOG_UG_LOG_SLOW_RATE_LIMIT       , "log_slow_rate_limit" },
+    { SLOG_UG_LOG_SLOW_VERBOSITY        , "log_slow_verbosity" },
+    { SLOG_UG_LONG_QUERY_TIME           , "long_query_time" },
+    { SLOG_UG_MIN_EXAMINED_ROW_LIMIT    , "min_examined_row_limit" },
+    /* ... */
+    { 0, "" },
+    /* Complex flags */
+    { SLOG_UG_ALL                       , "all" },
+    /* ... */
+    { SLOG_UG_INVALID                   , (char*)0 }
+  };
+
+#define SLOG_V_MICROTIME      1 << 0
+#define SLOG_V_QUERY_PLAN     1 << 1
+#define SLOG_V_INNODB         1 << 2
+/* ... */
+#define SLOG_V_INVALID        1##UL << 31
+#define SLOG_V_NONE           SLOG_V_MICROTIME
+
+static const struct msl_opts slog_verb[]= 
+{
+  /* Basic flags */
+
+  { SLOG_V_MICROTIME, "microtime" },
+  { SLOG_V_QUERY_PLAN, "query_plan" },
+  { SLOG_V_INNODB, "innodb" },
+
+  /* End of baisc flags */
+
+  { 0, "" },
+
+  /* Complex flags */
+
+  { SLOG_V_MICROTIME, "minimal" },
+  { SLOG_V_MICROTIME|SLOG_V_QUERY_PLAN, "standard" },
+  { SLOG_V_MICROTIME|SLOG_V_QUERY_PLAN|SLOG_V_INNODB, "full" },
+
+  /* End of complex flags */
+
+  { SLOG_V_INVALID, (char *)0 }
+};
+
+#define QPLAN_NONE            0
+#define QPLAN_QC              1 << 0
+#define QPLAN_QC_NO           1 << 1
+#define QPLAN_FULL_SCAN       1 << 2
+#define QPLAN_FULL_JOIN       1 << 3
+#define QPLAN_TMP_TABLE       1 << 4
+#define QPLAN_TMP_DISK        1 << 5
+#define QPLAN_FILESORT        1 << 6
+#define QPLAN_FILESORT_DISK   1 << 7
+/* ... */
+#define QPLAN_MAX             1 << 31
+
+#define SLOG_F_QC_NO          QPLAN_QC_NO
+#define SLOG_F_FULL_SCAN      QPLAN_FULL_SCAN
+#define SLOG_F_FULL_JOIN      QPLAN_FULL_JOIN
+#define SLOG_F_TMP_TABLE      QPLAN_TMP_TABLE
+#define SLOG_F_TMP_DISK       QPLAN_TMP_DISK
+#define SLOG_F_FILESORT       QPLAN_FILESORT
+#define SLOG_F_FILESORT_DISK  QPLAN_FILESORT_DISK
+#define SLOG_F_INVALID        1##UL << 31
+#define SLOG_F_NONE           0
+
+static const struct msl_opts slog_filter[]= 
+{
+  { SLOG_F_QC_NO,         "qc_miss" },
+  { SLOG_F_FULL_SCAN,     "full_scan" },
+  { SLOG_F_FULL_JOIN,     "full_join" },
+  { SLOG_F_TMP_TABLE,     "tmp_table" },
+  { SLOG_F_TMP_DISK,      "tmp_table_on_disk" },
+  { SLOG_F_FILESORT,      "filesort" },
+  { SLOG_F_FILESORT_DISK, "filesort_on_disk" },
+  { SLOG_F_INVALID,       (char *)0 }
+};
+
 /*
   Some defines for exit codes for ::is_equal class functions.
 */
@@ -2002,6 +2102,10 @@
 extern my_bool opt_secure_auth;
 extern char* opt_secure_file_priv;
 extern my_bool opt_log_slow_admin_statements, opt_log_slow_slave_statements;
+extern my_bool opt_log_slow_sp_statements;
+extern my_bool opt_log_slow_timestamp_every;
+extern my_bool opt_use_global_long_query_time;
+extern my_bool opt_slow_query_log_microseconds_timestamp;
 extern my_bool sp_automatic_privileges, opt_noacl;
 extern my_bool opt_old_style_user_limits, trust_function_creators;
 extern uint opt_crash_binlog_innodb;
diff -ruN a/sql/mysqld.cc b/sql/mysqld.cc
--- a/sql/mysqld.cc	2010-12-24 13:57:33.000000000 +0300
+++ b/sql/mysqld.cc	2010-12-24 13:57:45.000000000 +0300
@@ -520,6 +520,10 @@
 char* opt_secure_file_priv= 0;
 my_bool opt_log_slow_admin_statements= 0;
 my_bool opt_log_slow_slave_statements= 0;
+my_bool opt_log_slow_sp_statements= 0;
+my_bool opt_log_slow_timestamp_every= 0;
+my_bool opt_use_global_long_query_time= 0;
+my_bool opt_slow_query_log_microseconds_timestamp= 0;
 my_bool lower_case_file_system= 0;
 my_bool opt_large_pages= 0;
 my_bool opt_myisam_use_mmap= 0;
@@ -5798,6 +5802,11 @@
   OPT_SECURE_FILE_PRIV,
   OPT_MIN_EXAMINED_ROW_LIMIT,
   OPT_LOG_SLOW_SLAVE_STATEMENTS,
+  OPT_LOG_SLOW_RATE_LIMIT,
+  OPT_LOG_SLOW_VERBOSITY,
+  OPT_LOG_SLOW_FILTER,
+  OPT_LOG_SLOW_SP_STATEMENTS,
+  OPT_LOG_SLOW_TIMESTAMP_EVERY,
 #if defined(ENABLED_DEBUG_SYNC)
   OPT_DEBUG_SYNC_TIMEOUT,
 #endif /* defined(ENABLED_DEBUG_SYNC) */
@@ -5805,6 +5814,9 @@
   OPT_SLAVE_EXEC_MODE,
   OPT_GENERAL_LOG_FILE,
   OPT_SLOW_QUERY_LOG_FILE,
+  OPT_USE_GLOBAL_LONG_QUERY_TIME,
+  OPT_USE_GLOBAL_LOG_SLOW_CONTROL,
+  OPT_SLOW_QUERY_LOG_MICROSECONDS_TIMESTAMP,
   OPT_IGNORE_BUILTIN_INNODB,
   OPT_BINLOG_DIRECT_NON_TRANS_UPDATE,
   OPT_DEFAULT_CHARACTER_SET_OLD,
@@ -6825,6 +6837,36 @@
    "microsecond precision.",
    &long_query_time, &long_query_time, 0, GET_DOUBLE,
    REQUIRED_ARG, 10, 0, LONG_TIMEOUT, 0, 0, 0},
+  {"log_slow_filter", OPT_LOG_SLOW_FILTER,
+    "Log only the queries that followed certain execution plan. Multiple flags allowed in a comma-separated string. [qc_miss, full_scan, full_join, tmp_table, tmp_table_on_disk, filesort, filesort_on_disk]",
+    0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, SLOG_F_NONE, 0, 0},
+  {"log_slow_rate_limit", OPT_LOG_SLOW_RATE_LIMIT,
+    "Rate limit statement writes to slow log to only those from every (1/log_slow_rate_limit) session.",
+    (uchar**) &global_system_variables.log_slow_rate_limit,
+    (uchar**) &max_system_variables.log_slow_rate_limit, 0, GET_ULONG,
+    REQUIRED_ARG, 1, 1, LONG_MAX, 0, 1L, 0},
+  {"log_slow_verbosity", OPT_LOG_SLOW_VERBOSITY,
+    "Choose how verbose the messages to your slow log will be. Multiple flags allowed in a comma-separated string. [microtime, query_plan, innodb]",
+    0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, SLOG_V_MICROTIME, 0, 0},
+  {"log_slow_sp_statements", OPT_LOG_SLOW_SP_STATEMENTS,
+   "Log slow statements executed by stored procedure to the slow log if it is open.",
+   (uchar**) &opt_log_slow_sp_statements, (uchar**) &opt_log_slow_sp_statements,
+   0, GET_BOOL, OPT_ARG, 1, 0, 1, 0, 1, 0},
+  {"log_slow_timestamp_every", OPT_LOG_SLOW_TIMESTAMP_EVERY,
+   "Timestamp is printed for all records of the slow log even if they are same time.",
+   (uchar**) &opt_log_slow_timestamp_every, (uchar**) &opt_log_slow_timestamp_every,
+   0, GET_BOOL, OPT_ARG, 0, 0, 1, 0, 1, 0},
+  {"use_global_log_slow_control", OPT_USE_GLOBAL_LOG_SLOW_CONTROL,
+    "Choose flags, wich always use the global variables. Multiple flags allowed in a comma-separated string. [none, log_slow_filter, log_slow_rate_limit, log_slow_verbosity, long_query_time, min_examined_row_limit, all]",
+   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, SLOG_UG_NONE, 0, 0},
+  {"use_global_long_query_time", OPT_USE_GLOBAL_LONG_QUERY_TIME,
+   "Control always use global long_query_time or local long_query_time.",
+   (uchar**) &opt_use_global_long_query_time, (uchar**) &opt_use_global_long_query_time,
+   0, GET_BOOL, OPT_ARG, 0, 0, 1, 0, 1, 0},
+  {"slow_query_log_microseconds_timestamp", OPT_SLOW_QUERY_LOG_MICROSECONDS_TIMESTAMP,
+   "Use microsecond time's precision in slow query log",
+   (uchar**) &opt_slow_query_log_microseconds_timestamp, (uchar**) &opt_slow_query_log_microseconds_timestamp,
+   0, GET_BOOL, OPT_ARG, 0, 0, 1, 0, 1, 0},
   {"lower_case_table_names", OPT_LOWER_CASE_TABLE_NAMES,
    "If set to 1, table names are stored in lowercase on disk and table names "
    "will be case-insensitive.  Should be set to 2 if you are using a case-"
@@ -7982,6 +8024,10 @@
   global_system_variables.old_passwords= 0;
   global_system_variables.old_alter_table= 0;
   global_system_variables.binlog_format= BINLOG_FORMAT_UNSPEC;
+
+  global_system_variables.log_slow_verbosity= SLOG_V_MICROTIME;
+  global_system_variables.use_global_log_slow_control= SLOG_UG_NONE;
+  global_system_variables.log_slow_filter= SLOG_F_NONE;
   /*
     Default behavior for 4.1 and 5.0 is to treat NULL values as unequal
     when collecting index statistics for MyISAM tables.
@@ -8483,6 +8529,44 @@
   case OPT_BOOTSTRAP:
     opt_noacl=opt_bootstrap=1;
     break;
+  case OPT_LOG_SLOW_FILTER:
+    if ((global_system_variables.log_slow_filter= 
+          msl_flag_resolve_by_name(slog_filter, argument,
+                                   SLOG_F_NONE, SLOG_F_INVALID)) == SLOG_F_INVALID)
+    {
+      fprintf(stderr,"Invalid argument in log_slow_filter: %s\n", argument);
+      exit(1);
+    }
+    break;
+  case OPT_LOG_SLOW_VERBOSITY:
+    if ((global_system_variables.log_slow_verbosity= 
+         msl_flag_resolve_by_name(slog_verb, argument,
+                                  SLOG_V_NONE, SLOG_V_INVALID)) == SLOG_V_INVALID)
+    {
+      fprintf(stderr,"Invalid argument in log_slow_verbosity: %s\n", argument);
+      exit(1);
+    }
+    break;
+  case OPT_USE_GLOBAL_LONG_QUERY_TIME:
+    use_global_long_query_time_update(opt_use_global_long_query_time);
+    break;
+  case OPT_USE_GLOBAL_LOG_SLOW_CONTROL:
+    {
+      ulong &v= global_system_variables.use_global_log_slow_control;
+      v= msl_flag_resolve_by_name(slog_use_global, argument, SLOG_UG_NONE, SLOG_UG_INVALID);
+      if (v != SLOG_UG_NONE)
+      {
+        v&= ~SLOG_UG_NONE;
+      }
+      if (v == SLOG_UG_INVALID)
+      {
+        fprintf(stderr,"Invalid argument in use_global_log_slow_control: %s\n", argument);
+        exit(1);
+      }
+      use_global_long_query_time_update
+        (global_system_variables.use_global_log_slow_control & SLOG_UG_LONG_QUERY_TIME);
+      break;
+    }
   case OPT_SERVER_ID:
     server_id_supplied = 1;
     break;
diff -ruN a/sql/set_var.cc b/sql/set_var.cc
--- a/sql/set_var.cc	2010-11-29 13:37:59.000000000 +0300
+++ b/sql/set_var.cc	2010-12-24 13:57:45.000000000 +0300
@@ -162,6 +162,74 @@
 
 static sys_var_chain vars = { NULL, NULL };
 
+void use_global_long_query_time_update(bool enable)
+{
+  ulong &log_slow_control= global_system_variables.use_global_log_slow_control;
+  opt_use_global_long_query_time= enable;
+  if (enable)
+    log_slow_control|= SLOG_UG_LONG_QUERY_TIME;
+  else
+    log_slow_control&= ~SLOG_UG_LONG_QUERY_TIME;
+  log_slow_control&= ~SLOG_UG_NONE;
+  if (log_slow_control == 0)
+    log_slow_control= SLOG_UG_NONE;
+}
+
+class sys_var_use_global_long_query_time : public sys_var_bool_ptr
+{
+public:
+  sys_var_use_global_long_query_time()
+    :sys_var_bool_ptr(&vars,"use_global_long_query_time",&opt_use_global_long_query_time)
+  {
+    chain_sys_var(&vars);
+  }
+  virtual bool update(THD *thd, set_var *var)
+  {
+    bool result = sys_var_bool_ptr::update(thd,var);
+    sync();
+    return result;
+  }
+  virtual void set_default(THD *thd, enum_var_type type)
+  {
+    sys_var_bool_ptr::set_default(thd,type);
+    sync();
+  }
+private:
+  void sync()
+  {
+    use_global_long_query_time_update(opt_use_global_long_query_time);    
+  }
+};
+class sys_var_use_global_log_slow_control : public sys_var_thd_msl_flag_correct_none
+{
+ public:
+  sys_var_use_global_log_slow_control() : sys_var_thd_msl_flag_correct_none(
+								 &vars
+								 ,"use_global_log_slow_control"
+								 ,&SV::use_global_log_slow_control
+								 ,SLOG_UG_NONE,SLOG_UG_NONE,SLOG_UG_INVALID
+								 ,slog_use_global)
+    {
+    }
+  virtual bool update(THD *thd, set_var *var)
+  {
+    bool result = sys_var_thd_msl_flag_correct_none::update(thd,var);
+    sync();
+    return result;
+  }
+  virtual void set_default(THD *thd, enum_var_type type)
+  {
+    sys_var_thd_msl_flag_correct_none::set_default(thd,type);
+    sync();
+  }
+private:
+  void sync()
+  {
+    ulong const &variable= global_system_variables.use_global_log_slow_control;
+    use_global_long_query_time_update((variable & SLOG_UG_LONG_QUERY_TIME));
+  }
+};
+
 static sys_var_thd_ulong
 sys_auto_increment_increment(&vars, "auto_increment_increment",
                              &SV::auto_increment_increment, NULL, NULL,
@@ -901,6 +969,30 @@
                                       QUERY_LOG_GENERAL);
 static sys_var_log_state sys_var_slow_query_log(&vars, "slow_query_log", &opt_slow_log,
                                          QUERY_LOG_SLOW);
+static sys_var_thd_ulong      sys_log_slow_rate_limit(&vars, "log_slow_rate_limit",
+                                            &SV::log_slow_rate_limit);
+static sys_var_thd_msl_flag   sys_log_slow_filter(&vars, "log_slow_filter",
+                                      &SV::log_slow_filter,
+                                       SLOG_F_NONE,
+                                       SLOG_F_NONE,
+                                       SLOG_F_INVALID,
+                                       slog_filter);
+static sys_var_thd_msl_flag   sys_log_slow_verbosity(&vars, "log_slow_verbosity",
+                                      &SV::log_slow_verbosity,
+                                       SLOG_V_NONE,
+                                       SLOG_V_MICROTIME,
+                                       SLOG_V_INVALID,
+                                       slog_verb);
+static sys_var_use_global_log_slow_control sys_use_global_log_slow_control;
+static sys_var_bool_ptr       sys_log_slow_slave_statements(&vars, "log_slow_slave_statements",
+                                                            &opt_log_slow_slave_statements);
+static sys_var_bool_ptr       sys_log_slow_sp_statements(&vars, "log_slow_sp_statements",
+                                                         &opt_log_slow_sp_statements);
+static sys_var_bool_ptr       sys_log_slow_timestamp_every(&vars, "log_slow_timestamp_every",
+                                                           &opt_log_slow_timestamp_every);
+static sys_var_use_global_long_query_time sys_use_global_long_query_time;
+static sys_var_bool_ptr       sys_slow_query_log_microseconds_timestamp(&vars, "slow_query_log_microseconds_timestamp",
+                                                       &opt_slow_query_log_microseconds_timestamp);
 /* Synonym of "slow_query_log" for consistency with SHOW VARIABLES output */
 static sys_var_log_state sys_var_log_slow(&vars, "log_slow_queries",
                                           &opt_slow_log, QUERY_LOG_SLOW);
@@ -3711,6 +3803,203 @@
 #endif
 }
 
+/* Slow log stuff */
+
+ulong msl_option_resolve_by_name(const struct msl_opts *opts, const char *name, ulong len)
+{
+  ulong i;
+  
+  for (i=0; opts[i].name; i++)
+  {
+    if (!my_strnncoll(&my_charset_latin1,
+                      (const uchar *)name, len,
+                      (const uchar *)opts[i].name, strlen(opts[i].name)))
+      return opts[i].val;
+  }
+  return opts[i].val;
+}
+
+ulong msl_flag_resolve_by_name(const struct msl_opts *opts, const char *names_list, 
+                               const ulong none_val, const ulong invalid_val)
+{
+  const char *p, *e;
+  ulong val= none_val;
+  
+  if (!*names_list)
+    return val;
+  
+  for (p= e= names_list; ; e++)
+  {
+    ulong i;
+    
+    if (*e != ',' && *e)
+      continue;
+    for (i=0; opts[i].name; i++)
+    {
+      if (!my_strnncoll(&my_charset_latin1,
+                        (const uchar *)p, e - p,
+                        (const uchar *)opts[i].name, strlen(opts[i].name)))
+      {
+        val= val | opts[i].val;
+        break;
+      }
+    }
+    if (opts[i].val == invalid_val)
+      return invalid_val;
+    if (!*e)
+      break;
+    p= e + 1;
+  }
+  return val;
+}
+
+const char *msl_option_get_name(const struct msl_opts *opts, ulong val)
+{
+  for (ulong i=0; opts[i].name && opts[i].name[0]; i++)
+  {
+    if (opts[i].val == val)
+      return opts[i].name;
+  }
+  return "*INVALID*";
+}
+
+char *msl_flag_get_name(const struct msl_opts *opts, char *buf, ulong val)
+{
+  uint offset= 0;
+  
+  *buf= '\0';
+  for (ulong i=0; opts[i].name && opts[i].name[0]; i++)
+  {
+    if (opts[i].val & val)
+      offset+= snprintf(buf+offset, STRING_BUFFER_USUAL_SIZE - offset - 1,
+                        "%s%s", (offset ? "," : ""), opts[i].name);
+  }
+  return buf;
+}
+
+/****************************************************************************
+ Functions to handle log_slow_verbosity
+****************************************************************************/
+
+/* Based upon sys_var::check_enum() */
+
+bool sys_var_thd_msl_option::check(THD *thd, set_var *var)
+{
+  char buff[STRING_BUFFER_USUAL_SIZE];
+  String str(buff, sizeof(buff), &my_charset_latin1), *res;
+
+  if (var->value->result_type() == STRING_RESULT)
+  {
+    ulong verb= this->invalid_val;
+    if (!(res=var->value->val_str(&str)) ||
+             (var->save_result.ulong_value=
+          (ulong) (verb= msl_option_resolve_by_name(this->opts, res->ptr(), res->length()))) == this->invalid_val)
+      goto err;
+    return 0;
+  }
+
+err:
+  my_error(ER_WRONG_ARGUMENTS, MYF(0), var->var->name);
+  return 1;
+}
+
+uchar *sys_var_thd_msl_option::value_ptr(THD *thd, enum_var_type type,
+                                       LEX_STRING *base)
+{
+  ulong val;
+  val= ((type == OPT_GLOBAL) ? global_system_variables.*offset :
+        thd->variables.*offset);
+  const char *verbosity= msl_option_get_name(this->opts, val);
+  return (uchar *) verbosity;
+}
+
+
+void sys_var_thd_msl_option::set_default(THD *thd, enum_var_type type)
+{
+  if (type == OPT_GLOBAL)
+    global_system_variables.*offset= (ulong) this->default_val;
+  else
+    thd->variables.*offset= (ulong) (global_system_variables.*offset);
+}
+
+
+bool sys_var_thd_msl_option::update(THD *thd, set_var *var)
+{
+  if (var->type == OPT_GLOBAL)
+    global_system_variables.*offset= var->save_result.ulong_value;
+  else
+    thd->variables.*offset= var->save_result.ulong_value;
+  return 0;
+}
+
+/****************************************************************************
+ Functions to handle log_slow_filter
+****************************************************************************/
+  
+/* Based upon sys_var::check_enum() */
+
+bool sys_var_thd_msl_flag::check(THD *thd, set_var *var)
+{
+  char buff[2 * STRING_BUFFER_USUAL_SIZE];
+  String str(buff, sizeof(buff), &my_charset_latin1), *res;
+
+  if (var->value->result_type() == STRING_RESULT)
+  {
+    ulong filter= this->none_val;
+    if (!(res=var->value->val_str(&str)) ||
+        (var->save_result.ulong_value=
+          (ulong) (filter= msl_flag_resolve_by_name(this->flags, res->ptr(), this->none_val, 
+                                                    this->invalid_val))) == this->invalid_val)
+      goto err;
+    return 0;
+  }
+
+err:
+  my_error(ER_WRONG_ARGUMENTS, MYF(0), var->var->name);
+  return 1;
+}
+
+uchar *sys_var_thd_msl_flag::value_ptr(THD *thd, enum_var_type type,
+                                       LEX_STRING *base)
+{
+  ulong val;
+  val= ((type == OPT_GLOBAL) ? global_system_variables.*offset :
+        thd->variables.*offset);
+  msl_flag_get_name(this->flags, this->flags_string, val);
+  return (uchar *) this->flags_string;
+}
+
+
+void sys_var_thd_msl_flag::set_default(THD *thd, enum_var_type type)
+{
+  if (type == OPT_GLOBAL)
+    global_system_variables.*offset= (ulong) this->default_val;
+  else
+    thd->variables.*offset= (ulong) (global_system_variables.*offset);
+}
+
+
+bool sys_var_thd_msl_flag::update(THD *thd, set_var *var)
+{
+  if (var->type == OPT_GLOBAL)
+    global_system_variables.*offset= var->save_result.ulong_value;
+  else
+    thd->variables.*offset= var->save_result.ulong_value;
+  return 0;
+}
+bool sys_var_thd_msl_flag_correct_none::update(THD *thd, set_var *var)
+{
+  ulong result = var->save_result.ulong_value;
+  if (result != none_val)
+    result = result & (~none_val);
+  if (var->type == OPT_GLOBAL)
+    global_system_variables.*offset = result;
+  else
+    thd->variables.*offset = result;
+  return 0;
+}
+
+
 /****************************************************************************
  Functions to handle table_type
 ****************************************************************************/
diff -ruN a/sql/set_var.h b/sql/set_var.h
--- a/sql/set_var.h	2010-11-29 13:38:17.000000000 +0300
+++ b/sql/set_var.h	2010-12-24 13:57:45.000000000 +0300
@@ -569,6 +569,82 @@
 };
 
 
+extern void use_global_long_query_time_update(bool enable);
+
+class sys_var_thd_msl_option :public sys_var_thd
+{
+protected:
+  ulong SV::*offset;
+  const ulong none_val;
+  const ulong default_val;
+  const ulong invalid_val;
+  const struct msl_opts *opts;
+public:
+  sys_var_thd_msl_option(sys_var_chain *chain, const char *name_arg, ulong SV::*offset_arg,
+                         const ulong none_val_arg,
+                         const ulong default_val_arg,
+                         const ulong invalid_val_arg,
+                         const struct msl_opts *opts_arg)
+    :sys_var_thd(name_arg), offset(offset_arg), none_val(none_val_arg),
+     default_val(default_val_arg), invalid_val(invalid_val_arg), 
+     opts(opts_arg)
+  { chain_sys_var(chain); }
+  bool check(THD *thd, set_var *var);
+  SHOW_TYPE show_type() { return SHOW_CHAR; }
+  bool check_update_type(Item_result type)
+  {
+    return type != STRING_RESULT;              /* Only accept strings */
+  }
+  void set_default(THD *thd, enum_var_type type);
+  bool update(THD *thd, set_var *var);
+  uchar *value_ptr(THD *thd, enum_var_type type, LEX_STRING *base);
+};
+
+
+class sys_var_thd_msl_flag :public sys_var_thd
+{
+protected:
+  char flags_string[2 * STRING_BUFFER_USUAL_SIZE];
+  ulong SV::*offset;
+  const ulong none_val;
+  const ulong default_val;
+  const ulong invalid_val;
+  const struct msl_opts *flags;
+public:
+  sys_var_thd_msl_flag(sys_var_chain *chain, const char *name_arg, ulong SV::*offset_arg, 
+                       const ulong none_val_arg, 
+                       const ulong default_val_arg, 
+                       const ulong invalid_val_arg,
+                       const struct msl_opts *flags_arg)
+    :sys_var_thd(name_arg), offset(offset_arg), none_val(none_val_arg),
+     default_val(default_val_arg), invalid_val(invalid_val_arg), 
+     flags(flags_arg)
+  { chain_sys_var(chain); }
+  bool check(THD *thd, set_var *var);
+  SHOW_TYPE show_type() { return SHOW_CHAR; }
+  bool check_update_type(Item_result type)
+  {
+    return type != STRING_RESULT;              /* Only accept strings */
+  }
+  void set_default(THD *thd, enum_var_type type);
+  bool update(THD *thd, set_var *var);
+  uchar *value_ptr(THD *thd, enum_var_type type, LEX_STRING *base);
+};
+
+class sys_var_thd_msl_flag_correct_none : public sys_var_thd_msl_flag
+{
+ public:
+  sys_var_thd_msl_flag_correct_none(sys_var_chain *chain, const char *name_arg, ulong SV::*offset_arg,
+				    const ulong none_val_arg,
+				    const ulong default_val_arg,
+				    const ulong invalid_val_arg,
+				    const struct msl_opts *flags_arg)
+    : sys_var_thd_msl_flag(chain,name_arg,offset_arg,none_val_arg,default_val_arg,invalid_val_arg,flags_arg)
+    {
+    }
+  virtual bool update(THD *thd, set_var *var);
+};
+
 class sys_var_thd_storage_engine :public sys_var_thd
 {
 protected:
@@ -1470,3 +1546,10 @@
 bool process_key_caches(process_key_cache_t func);
 void delete_elements(I_List<NAMED_LIST> *list,
 		     void (*free_element)(const char*, uchar*));
+
+/* Slow log functions */
+ulong msl_option_resolve_by_name(const struct msl_opts *opts, const char *name, ulong len);
+ulong msl_flag_resolve_by_name(const struct msl_opts *opts, const char *names_list, 
+                               const ulong none_val, const ulong invalid_val);
+const char *msl_option_get_name(const struct msl_opts *opts, ulong val);
+char *msl_flag_get_name(const struct msl_opts *opts, char *buf, ulong val);
diff -ruN a/sql/slave.cc b/sql/slave.cc
--- a/sql/slave.cc	2010-11-29 13:38:02.000000000 +0300
+++ b/sql/slave.cc	2010-12-24 13:57:45.000000000 +0300
@@ -1834,6 +1834,7 @@
     + MAX_LOG_EVENT_HEADER;  /* note, incr over the global not session var */
   thd->slave_thread = 1;
   thd->enable_slow_log= opt_log_slow_slave_statements;
+  thd->write_to_slow_log= opt_log_slow_slave_statements;
   set_slave_thread_options(thd);
   thd->client_capabilities = CLIENT_LOCAL_FILES;
   pthread_mutex_lock(&LOCK_thread_count);
diff -ruN a/sql/sp_head.cc b/sql/sp_head.cc
--- a/sql/sp_head.cc	2010-12-24 13:57:33.000000000 +0300
+++ b/sql/sp_head.cc	2010-12-24 13:57:45.000000000 +0300
@@ -1987,7 +1987,7 @@
     DBUG_PRINT("info",(" %.*s: eval args done", (int) m_name.length, 
                        m_name.str));
   }
-  if (!(m_flags & LOG_SLOW_STATEMENTS) && thd->enable_slow_log)
+  if (!(m_flags & LOG_SLOW_STATEMENTS || opt_log_slow_sp_statements) && thd->enable_slow_log)
   {
     DBUG_PRINT("info", ("Disabling slow log for the execution"));
     save_enable_slow_log= true;
diff -ruN a/sql/sql_cache.cc b/sql/sql_cache.cc
--- a/sql/sql_cache.cc	2010-11-29 13:37:59.000000000 +0300
+++ b/sql/sql_cache.cc	2010-12-24 13:57:45.000000000 +0300
@@ -1704,6 +1704,7 @@
 
   thd->limit_found_rows = query->found_rows();
   thd->status_var.last_query_cost= 0.0;
+  thd->query_plan_flags|= QPLAN_QC;
   if (!thd->main_da.is_set())
     thd->main_da.disable_status();
 
@@ -1713,6 +1714,7 @@
 err_unlock:
   unlock();
 err:
+  thd->query_plan_flags|= QPLAN_QC_NO;
   DBUG_RETURN(0);				// Query was not cached
 }
 
diff -ruN a/sql/sql_class.cc b/sql/sql_class.cc
--- a/sql/sql_class.cc	2010-11-29 13:37:59.000000000 +0300
+++ b/sql/sql_class.cc	2010-12-24 13:57:45.000000000 +0300
@@ -341,6 +341,37 @@
   thd->row_count++;
 }
 
+extern "C"
+void increment_thd_innodb_stats(THD* thd,
+                    unsigned long long trx_id,
+                    long io_reads,
+                    long long  io_read,
+                    long      io_reads_wait_timer,
+                    long      lock_que_wait_timer,
+                    long      que_wait_timer,
+                    long      page_access)
+{
+  thd->innodb_was_used = TRUE;
+  thd->innodb_trx_id = trx_id;
+  thd->innodb_io_reads += io_reads;
+  thd->innodb_io_read += io_read;
+  thd->innodb_io_reads_wait_timer += io_reads_wait_timer;
+  thd->innodb_lock_que_wait_timer += lock_que_wait_timer;
+  thd->innodb_innodb_que_wait_timer += que_wait_timer;
+  thd->innodb_page_access += page_access;
+}
+
+extern "C"
+unsigned long thd_log_slow_verbosity(const THD *thd)
+{
+  return (unsigned long) thd->variables.log_slow_verbosity;
+}
+
+extern "C"
+int thd_opt_slow_log()
+{
+  return (int) opt_slow_log;
+}
 
 /**
   Dumps a text description of a thread, its security context
@@ -761,6 +792,8 @@
 bool THD::handle_error(uint sql_errno, const char *message,
                        MYSQL_ERROR::enum_warning_level level)
 {
+  last_errno = sql_errno;
+
   for (Internal_error_handler *error_handler= m_internal_handler;
        error_handler;
        error_handler= error_handler->m_prev_internal_handler)
@@ -3177,6 +3210,12 @@
     first_successful_insert_id_in_prev_stmt;
   backup->first_successful_insert_id_in_cur_stmt= 
     first_successful_insert_id_in_cur_stmt;
+  backup->innodb_io_reads= innodb_io_reads;
+  backup->innodb_io_read= innodb_io_read;
+  backup->innodb_io_reads_wait_timer= innodb_io_reads_wait_timer;
+  backup->innodb_lock_que_wait_timer= innodb_lock_que_wait_timer;
+  backup->innodb_innodb_que_wait_timer= innodb_innodb_que_wait_timer;
+  backup->innodb_page_access= innodb_page_access;
 
   if ((!lex->requires_prelocking() || is_update_query(lex->sql_command)) &&
       !current_stmt_binlog_row_based)
@@ -3196,6 +3235,14 @@
   cuted_fields= 0;
   transaction.savepoints= 0;
   first_successful_insert_id_in_cur_stmt= 0;
+  last_errno= 0;
+  innodb_trx_id= 0;
+  innodb_io_reads= 0;
+  innodb_io_read= 0;
+  innodb_io_reads_wait_timer= 0;
+  innodb_lock_que_wait_timer= 0;
+  innodb_innodb_que_wait_timer= 0;
+  innodb_page_access= 0;
 }
 
 
@@ -3258,6 +3305,12 @@
   */
   examined_row_count+= backup->examined_row_count;
   cuted_fields+=       backup->cuted_fields;
+  innodb_io_reads+= backup->innodb_io_reads;
+  innodb_io_read+= backup->innodb_io_read;
+  innodb_io_reads_wait_timer+= backup->innodb_io_reads_wait_timer;
+  innodb_lock_que_wait_timer+= backup->innodb_lock_que_wait_timer;
+  innodb_innodb_que_wait_timer+= backup->innodb_innodb_que_wait_timer;
+  innodb_page_access+= backup->innodb_page_access;
   DBUG_VOID_RETURN;
 }
 
diff -ruN a/sql/sql_class.h b/sql/sql_class.h
--- a/sql/sql_class.h	2010-11-29 13:37:59.000000000 +0300
+++ b/sql/sql_class.h	2010-12-24 14:06:52.000000000 +0300
@@ -402,6 +402,18 @@
   DATE_TIME_FORMAT *datetime_format;
   DATE_TIME_FORMAT *time_format;
   my_bool sysdate_is_now;
+
+  ulong log_slow_rate_limit;
+  ulong log_slow_filter;
+  ulong log_slow_verbosity;
+  ulong use_global_log_slow_control;
+
+  ulong      innodb_io_reads;
+  ulonglong  innodb_io_read;
+  ulong      innodb_io_reads_wait_timer;
+  ulong      innodb_lock_que_wait_timer;
+  ulong      innodb_innodb_que_wait_timer;
+  ulong      innodb_page_access;
 };
 
 
@@ -998,6 +1010,14 @@
   uint in_sub_stmt;
   bool enable_slow_log;
   bool last_insert_id_used;
+
+  ulong      innodb_io_reads;
+  ulonglong  innodb_io_read;
+  ulong      innodb_io_reads_wait_timer;
+  ulong      innodb_lock_que_wait_timer;
+  ulong      innodb_innodb_que_wait_timer;
+  ulong      innodb_page_access;
+
   SAVEPOINT *savepoints;
   enum enum_check_fields count_cuted_fields;
 };
@@ -1425,6 +1445,26 @@
   thr_lock_type update_lock_default;
   Delayed_insert *di;
 
+  bool       write_to_slow_log;
+
+  ulonglong  bytes_sent_old;
+  ulong      tmp_tables_used;
+  ulong      tmp_tables_disk_used;
+  ulonglong  tmp_tables_size;
+  bool       innodb_was_used;
+  ulonglong  innodb_trx_id;
+  ulong      innodb_io_reads;
+  ulonglong  innodb_io_read;
+  ulong      innodb_io_reads_wait_timer;
+  ulong      innodb_lock_que_wait_timer;
+  ulong      innodb_innodb_que_wait_timer;
+  ulong      innodb_page_access;
+
+  ulong      query_plan_flags;
+  ulong      query_plan_fsort_passes;
+
+  uint       last_errno;
+
   /* <> 0 if we are inside of trigger or stored function. */
   uint in_sub_stmt;
   /* TRUE when the current top has SQL_LOG_BIN ON */
@@ -1777,6 +1817,11 @@
     create_sort_index(); may differ from examined_row_count.
   */
   ulong      row_count;
+  /*
+    Original row_count value at the start of query execution
+    (used by the slow_extended patch).
+  */
+  ulong      orig_row_count;
   pthread_t  real_id;                           /* For debugging */
   my_thread_id  thread_id;
   uint	     tmp_table, global_read_lock;
diff -ruN a/sql/sql_connect.cc b/sql/sql_connect.cc
--- a/sql/sql_connect.cc	2010-11-29 13:38:17.000000000 +0300
+++ b/sql/sql_connect.cc	2010-12-24 13:57:45.000000000 +0300
@@ -1290,6 +1290,15 @@
 
     prepare_new_connection_state(thd);
 
+    /* 
+      If rate limiting of slow log writes is enabled, decide whether to log this 
+      new thread's queries or not. Uses extremely simple algorithm. :) 
+    */ 
+    thd->write_to_slow_log= FALSE; 
+    if (thd->variables.log_slow_rate_limit <= 1 ||  
+        (thd->thread_id % thd->variables.log_slow_rate_limit) == 0) 
+         thd->write_to_slow_log= TRUE; 
+
     while (!net->error && net->vio != 0 &&
            !(thd->killed == THD::KILL_CONNECTION))
     {
diff -ruN a/sql/sql_parse.cc b/sql/sql_parse.cc
--- a/sql/sql_parse.cc	2010-12-24 13:57:33.000000000 +0300
+++ b/sql/sql_parse.cc	2010-12-24 14:06:17.000000000 +0300
@@ -1699,7 +1699,10 @@
   free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
   DBUG_RETURN(error);
 }
-
+#define SLOG_UG_SETUP(session,value,flag,global) do {   \
+  if(value & flag) \
+    session = global; \
+  } while(false);
 
 void log_slow_statement(THD *thd)
 {
@@ -1713,6 +1716,40 @@
   if (unlikely(thd->in_sub_stmt))
     DBUG_VOID_RETURN;                           // Don't set time for sub stmt
 
+  /* Follow the slow log filter configuration. */
+  if (thd->variables.log_slow_filter != SLOG_F_NONE &&
+      (!(thd->variables.log_slow_filter & thd->query_plan_flags) ||
+       ((thd->variables.log_slow_filter & SLOG_F_QC_NO) &&
+        (thd->query_plan_flags & QPLAN_QC))))
+    DBUG_VOID_RETURN;
+
+  /*
+    Low long_query_time value most likely means user is debugging stuff and even
+    though some thread's queries are not supposed to be logged b/c of the rate
+    limit, if one of them takes long enough (>= 1 second) it will be sensible
+    to make an exception and write to slow log anyway.
+  */
+
+  ulonglong end_utime_of_query= thd->current_utime();
+
+  /* use_global_log_slow_control */
+  {
+    system_variables const &g= global_system_variables; // global                                                           
+    system_variables       &s= thd->variables;          // session                                                          
+    ulong const            &value= g.use_global_log_slow_control;
+    SLOG_UG_SETUP(s.log_slow_filter,           value, SLOG_UG_LOG_SLOW_FILTER,             g.log_slow_filter);
+    SLOG_UG_SETUP(s.log_slow_rate_limit,       value, SLOG_UG_LOG_SLOW_RATE_LIMIT,         g.log_slow_rate_limit);
+    SLOG_UG_SETUP(s.log_slow_verbosity,        value, SLOG_UG_LOG_SLOW_VERBOSITY,          g.log_slow_verbosity);
+    SLOG_UG_SETUP(s.long_query_time,           value, SLOG_UG_LONG_QUERY_TIME,             g.long_query_time);
+    SLOG_UG_SETUP(s.min_examined_row_limit,    value, SLOG_UG_MIN_EXAMINED_ROW_LIMIT,      g.min_examined_row_limit);
+  }
+
+  /* Do not log this thread's queries due to rate limiting. */
+  if (thd->write_to_slow_log != TRUE
+      && (thd->variables.long_query_time >= 1000000
+          || (ulong) (end_utime_of_query - thd->utime_after_lock) < 1000000))
+    DBUG_VOID_RETURN;
+
   /*
     Do not log administrative statements unless the appropriate option is
     set.
@@ -2099,6 +2136,9 @@
     context.resolve_in_table_list_only(select_lex->
                                        table_list.first);
 
+  /* Save the original row_count value for extended stats in slow query log */
+  thd->orig_row_count= thd->row_count;
+
   /*
     Reset warning count for each query that uses tables
     A better approach would be to reset this for any commands
@@ -5828,6 +5868,21 @@
   thd->rand_used= 0;
   thd->sent_row_count= thd->examined_row_count= 0;
 
+  thd->bytes_sent_old= thd->status_var.bytes_sent;
+  thd->tmp_tables_used= thd->tmp_tables_disk_used= 0;
+  thd->tmp_tables_size= 0;
+  thd->innodb_was_used= FALSE;
+  thd->innodb_trx_id= 0;
+  thd->innodb_io_reads= 0;
+  thd->innodb_io_read= 0;
+  thd->innodb_io_reads_wait_timer= 0;
+  thd->innodb_lock_que_wait_timer= 0;
+  thd->innodb_innodb_que_wait_timer= 0;
+  thd->innodb_page_access= 0;
+  thd->query_plan_flags= QPLAN_NONE;
+  thd->query_plan_fsort_passes= 0;
+  thd->last_errno= 0;
+
   /*
     Because we come here only for start of top-statements, binlog format is
     constant inside a complex statement (using stored functions) etc.
diff -ruN a/sql/sql_select.cc b/sql/sql_select.cc
--- a/sql/sql_select.cc	2010-11-29 13:38:01.000000000 +0300
+++ b/sql/sql_select.cc	2010-12-24 13:57:45.000000000 +0300
@@ -6794,7 +6794,10 @@
 	  {
 	    join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
 	    if (statistics)
+            {
 	      status_var_increment(join->thd->status_var.select_scan_count);
+              join->thd->query_plan_flags|= QPLAN_FULL_SCAN;
+            }
 	  }
 	}
 	else
@@ -6808,7 +6811,10 @@
 	  {
 	    join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
 	    if (statistics)
+            {
 	      status_var_increment(join->thd->status_var.select_full_join_count);
+              join->thd->query_plan_flags|= QPLAN_FULL_JOIN;
+            }
 	  }
 	}
 	if (!table->no_keyread)
@@ -10012,6 +10018,7 @@
               (ulong) rows_limit,test(group)));
 
   status_var_increment(thd->status_var.created_tmp_tables);
+  thd->query_plan_flags|= QPLAN_TMP_TABLE;
 
   if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
     temp_pool_slot = bitmap_lock_set_next(&temp_pool);
@@ -10893,6 +10900,7 @@
     goto err;
   }
   status_var_increment(table->in_use->status_var.created_tmp_disk_tables);
+  table->in_use->query_plan_flags|= QPLAN_TMP_DISK;
   share->db_record_offset= 1;
   DBUG_RETURN(0);
  err:
@@ -10911,6 +10919,14 @@
   save_proc_info=thd->proc_info;
   thd_proc_info(thd, "removing tmp table");
 
+  thd->tmp_tables_used++;
+  if (entry->file)
+  {
+    thd->tmp_tables_size += entry->file->stats.data_file_length;
+    if (entry->file->ht->db_type != DB_TYPE_HEAP)
+      thd->tmp_tables_disk_used++;
+  }
+
   // Release latches since this can take a long time
   ha_release_temporary_latches(thd);
 
diff -ruN a/sql/sql_show.cc b/sql/sql_show.cc
--- a/sql/sql_show.cc	2010-12-24 13:57:33.000000000 +0300
+++ b/sql/sql_show.cc	2010-12-24 13:57:46.000000000 +0300
@@ -1971,8 +1971,17 @@
         table->field[4]->store(command_name[tmp->command].str,
                                command_name[tmp->command].length, cs);
       /* MYSQL_TIME */
-      table->field[5]->store((longlong)(tmp->start_time ?
-                                      now - tmp->start_time : 0), FALSE);
+      longlong value_in_time_column= 0;
+      if(tmp->start_time)
+      {
+        value_in_time_column = (now - tmp->start_time);
+        if(value_in_time_column > now)
+        {
+          value_in_time_column= 0;
+        }
+      }
+      table->field[5]->store(value_in_time_column, FALSE);
+
       /* STATE */
 #ifndef EMBEDDED_LIBRARY
       val= (char*) (tmp->locked ? "Locked" :