checkpatch: fix false positive on empty block comment lines
[linux-2.6-microblaze.git] / scripts / checkpatch.pl
1 #!/usr/bin/env perl
2 # SPDX-License-Identifier: GPL-2.0
3 #
4 # (c) 2001, Dave Jones. (the file handling bit)
5 # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6 # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7 # (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8 # (c) 2010-2018 Joe Perches <joe@perches.com>
9
10 use strict;
11 use warnings;
12 use POSIX;
13 use File::Basename;
14 use Cwd 'abs_path';
15 use Term::ANSIColor qw(:constants);
16 use Encode qw(decode encode);
17
18 my $P = $0;
19 my $D = dirname(abs_path($P));
20
21 my $V = '0.32';
22
23 use Getopt::Long qw(:config no_auto_abbrev);
24
25 my $quiet = 0;
26 my $tree = 1;
27 my $chk_signoff = 1;
28 my $chk_patch = 1;
29 my $tst_only;
30 my $emacs = 0;
31 my $terse = 0;
32 my $showfile = 0;
33 my $file = 0;
34 my $git = 0;
35 my %git_commits = ();
36 my $check = 0;
37 my $check_orig = 0;
38 my $summary = 1;
39 my $mailback = 0;
40 my $summary_file = 0;
41 my $show_types = 0;
42 my $list_types = 0;
43 my $fix = 0;
44 my $fix_inplace = 0;
45 my $root;
46 my %debug;
47 my %camelcase = ();
48 my %use_type = ();
49 my @use = ();
50 my %ignore_type = ();
51 my @ignore = ();
52 my $help = 0;
53 my $configuration_file = ".checkpatch.conf";
54 my $max_line_length = 100;
55 my $ignore_perl_version = 0;
56 my $minimum_perl_version = 5.10.0;
57 my $min_conf_desc_length = 4;
58 my $spelling_file = "$D/spelling.txt";
59 my $codespell = 0;
60 my $codespellfile = "/usr/share/codespell/dictionary.txt";
61 my $conststructsfile = "$D/const_structs.checkpatch";
62 my $typedefsfile;
63 my $color = "auto";
64 my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
65 # git output parsing needs US English output, so first set backtick child process LANGUAGE
66 my $git_command ='export LANGUAGE=en_US.UTF-8; git';
67 my $tabsize = 8;
68 my ${CONFIG_} = "CONFIG_";
69
70 sub help {
71         my ($exitcode) = @_;
72
73         print << "EOM";
74 Usage: $P [OPTION]... [FILE]...
75 Version: $V
76
77 Options:
78   -q, --quiet                quiet
79   --no-tree                  run without a kernel tree
80   --no-signoff               do not check for 'Signed-off-by' line
81   --patch                    treat FILE as patchfile (default)
82   --emacs                    emacs compile window format
83   --terse                    one line per report
84   --showfile                 emit diffed file position, not input file position
85   -g, --git                  treat FILE as a single commit or git revision range
86                              single git commit with:
87                                <rev>
88                                <rev>^
89                                <rev>~n
90                              multiple git commits with:
91                                <rev1>..<rev2>
92                                <rev1>...<rev2>
93                                <rev>-<count>
94                              git merges are ignored
95   -f, --file                 treat FILE as regular source file
96   --subjective, --strict     enable more subjective tests
97   --list-types               list the possible message types
98   --types TYPE(,TYPE2...)    show only these comma separated message types
99   --ignore TYPE(,TYPE2...)   ignore various comma separated message types
100   --show-types               show the specific message type in the output
101   --max-line-length=n        set the maximum line length, (default $max_line_length)
102                              if exceeded, warn on patches
103                              requires --strict for use with --file
104   --min-conf-desc-length=n   set the min description length, if shorter, warn
105   --tab-size=n               set the number of spaces for tab (default $tabsize)
106   --root=PATH                PATH to the kernel tree root
107   --no-summary               suppress the per-file summary
108   --mailback                 only produce a report in case of warnings/errors
109   --summary-file             include the filename in summary
110   --debug KEY=[0|1]          turn on/off debugging of KEY, where KEY is one of
111                              'values', 'possible', 'type', and 'attr' (default
112                              is all off)
113   --test-only=WORD           report only warnings/errors containing WORD
114                              literally
115   --fix                      EXPERIMENTAL - may create horrible results
116                              If correctable single-line errors exist, create
117                              "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
118                              with potential errors corrected to the preferred
119                              checkpatch style
120   --fix-inplace              EXPERIMENTAL - may create horrible results
121                              Is the same as --fix, but overwrites the input
122                              file.  It's your fault if there's no backup or git
123   --ignore-perl-version      override checking of perl version.  expect
124                              runtime errors.
125   --codespell                Use the codespell dictionary for spelling/typos
126                              (default:/usr/share/codespell/dictionary.txt)
127   --codespellfile            Use this codespell dictionary
128   --typedefsfile             Read additional types from this file
129   --color[=WHEN]             Use colors 'always', 'never', or only when output
130                              is a terminal ('auto'). Default is 'auto'.
131   --kconfig-prefix=WORD      use WORD as a prefix for Kconfig symbols (default
132                              ${CONFIG_})
133   -h, --help, --version      display this help and exit
134
135 When FILE is - read standard input.
136 EOM
137
138         exit($exitcode);
139 }
140
141 sub uniq {
142         my %seen;
143         return grep { !$seen{$_}++ } @_;
144 }
145
146 sub list_types {
147         my ($exitcode) = @_;
148
149         my $count = 0;
150
151         local $/ = undef;
152
153         open(my $script, '<', abs_path($P)) or
154             die "$P: Can't read '$P' $!\n";
155
156         my $text = <$script>;
157         close($script);
158
159         my @types = ();
160         # Also catch when type or level is passed through a variable
161         for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
162                 push (@types, $_);
163         }
164         @types = sort(uniq(@types));
165         print("#\tMessage type\n\n");
166         foreach my $type (@types) {
167                 print(++$count . "\t" . $type . "\n");
168         }
169
170         exit($exitcode);
171 }
172
173 my $conf = which_conf($configuration_file);
174 if (-f $conf) {
175         my @conf_args;
176         open(my $conffile, '<', "$conf")
177             or warn "$P: Can't find a readable $configuration_file file $!\n";
178
179         while (<$conffile>) {
180                 my $line = $_;
181
182                 $line =~ s/\s*\n?$//g;
183                 $line =~ s/^\s*//g;
184                 $line =~ s/\s+/ /g;
185
186                 next if ($line =~ m/^\s*#/);
187                 next if ($line =~ m/^\s*$/);
188
189                 my @words = split(" ", $line);
190                 foreach my $word (@words) {
191                         last if ($word =~ m/^#/);
192                         push (@conf_args, $word);
193                 }
194         }
195         close($conffile);
196         unshift(@ARGV, @conf_args) if @conf_args;
197 }
198
199 # Perl's Getopt::Long allows options to take optional arguments after a space.
200 # Prevent --color by itself from consuming other arguments
201 foreach (@ARGV) {
202         if ($_ eq "--color" || $_ eq "-color") {
203                 $_ = "--color=$color";
204         }
205 }
206
207 GetOptions(
208         'q|quiet+'      => \$quiet,
209         'tree!'         => \$tree,
210         'signoff!'      => \$chk_signoff,
211         'patch!'        => \$chk_patch,
212         'emacs!'        => \$emacs,
213         'terse!'        => \$terse,
214         'showfile!'     => \$showfile,
215         'f|file!'       => \$file,
216         'g|git!'        => \$git,
217         'subjective!'   => \$check,
218         'strict!'       => \$check,
219         'ignore=s'      => \@ignore,
220         'types=s'       => \@use,
221         'show-types!'   => \$show_types,
222         'list-types!'   => \$list_types,
223         'max-line-length=i' => \$max_line_length,
224         'min-conf-desc-length=i' => \$min_conf_desc_length,
225         'tab-size=i'    => \$tabsize,
226         'root=s'        => \$root,
227         'summary!'      => \$summary,
228         'mailback!'     => \$mailback,
229         'summary-file!' => \$summary_file,
230         'fix!'          => \$fix,
231         'fix-inplace!'  => \$fix_inplace,
232         'ignore-perl-version!' => \$ignore_perl_version,
233         'debug=s'       => \%debug,
234         'test-only=s'   => \$tst_only,
235         'codespell!'    => \$codespell,
236         'codespellfile=s'       => \$codespellfile,
237         'typedefsfile=s'        => \$typedefsfile,
238         'color=s'       => \$color,
239         'no-color'      => \$color,     #keep old behaviors of -nocolor
240         'nocolor'       => \$color,     #keep old behaviors of -nocolor
241         'kconfig-prefix=s'      => \${CONFIG_},
242         'h|help'        => \$help,
243         'version'       => \$help
244 ) or help(1);
245
246 help(0) if ($help);
247
248 list_types(0) if ($list_types);
249
250 $fix = 1 if ($fix_inplace);
251 $check_orig = $check;
252
253 die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
254
255 my $exit = 0;
256
257 my $perl_version_ok = 1;
258 if ($^V && $^V lt $minimum_perl_version) {
259         $perl_version_ok = 0;
260         printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
261         exit(1) if (!$ignore_perl_version);
262 }
263
264 #if no filenames are given, push '-' to read patch from stdin
265 if ($#ARGV < 0) {
266         push(@ARGV, '-');
267 }
268
269 if ($color =~ /^[01]$/) {
270         $color = !$color;
271 } elsif ($color =~ /^always$/i) {
272         $color = 1;
273 } elsif ($color =~ /^never$/i) {
274         $color = 0;
275 } elsif ($color =~ /^auto$/i) {
276         $color = (-t STDOUT);
277 } else {
278         die "$P: Invalid color mode: $color\n";
279 }
280
281 # skip TAB size 1 to avoid additional checks on $tabsize - 1
282 die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
283
284 sub hash_save_array_words {
285         my ($hashRef, $arrayRef) = @_;
286
287         my @array = split(/,/, join(',', @$arrayRef));
288         foreach my $word (@array) {
289                 $word =~ s/\s*\n?$//g;
290                 $word =~ s/^\s*//g;
291                 $word =~ s/\s+/ /g;
292                 $word =~ tr/[a-z]/[A-Z]/;
293
294                 next if ($word =~ m/^\s*#/);
295                 next if ($word =~ m/^\s*$/);
296
297                 $hashRef->{$word}++;
298         }
299 }
300
301 sub hash_show_words {
302         my ($hashRef, $prefix) = @_;
303
304         if (keys %$hashRef) {
305                 print "\nNOTE: $prefix message types:";
306                 foreach my $word (sort keys %$hashRef) {
307                         print " $word";
308                 }
309                 print "\n";
310         }
311 }
312
313 hash_save_array_words(\%ignore_type, \@ignore);
314 hash_save_array_words(\%use_type, \@use);
315
316 my $dbg_values = 0;
317 my $dbg_possible = 0;
318 my $dbg_type = 0;
319 my $dbg_attr = 0;
320 for my $key (keys %debug) {
321         ## no critic
322         eval "\${dbg_$key} = '$debug{$key}';";
323         die "$@" if ($@);
324 }
325
326 my $rpt_cleaners = 0;
327
328 if ($terse) {
329         $emacs = 1;
330         $quiet++;
331 }
332
333 if ($tree) {
334         if (defined $root) {
335                 if (!top_of_kernel_tree($root)) {
336                         die "$P: $root: --root does not point at a valid tree\n";
337                 }
338         } else {
339                 if (top_of_kernel_tree('.')) {
340                         $root = '.';
341                 } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
342                                                 top_of_kernel_tree($1)) {
343                         $root = $1;
344                 }
345         }
346
347         if (!defined $root) {
348                 print "Must be run from the top-level dir. of a kernel tree\n";
349                 exit(2);
350         }
351 }
352
353 my $emitted_corrupt = 0;
354
355 our $Ident      = qr{
356                         [A-Za-z_][A-Za-z\d_]*
357                         (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
358                 }x;
359 our $Storage    = qr{extern|static|asmlinkage};
360 our $Sparse     = qr{
361                         __user|
362                         __kernel|
363                         __force|
364                         __iomem|
365                         __must_check|
366                         __kprobes|
367                         __ref|
368                         __refconst|
369                         __refdata|
370                         __rcu|
371                         __private
372                 }x;
373 our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
374 our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
375 our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
376 our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
377 our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
378
379 # Notes to $Attribute:
380 # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
381 our $Attribute  = qr{
382                         const|
383                         __percpu|
384                         __nocast|
385                         __safe|
386                         __bitwise|
387                         __packed__|
388                         __packed2__|
389                         __naked|
390                         __maybe_unused|
391                         __always_unused|
392                         __noreturn|
393                         __used|
394                         __cold|
395                         __pure|
396                         __noclone|
397                         __deprecated|
398                         __read_mostly|
399                         __ro_after_init|
400                         __kprobes|
401                         $InitAttribute|
402                         ____cacheline_aligned|
403                         ____cacheline_aligned_in_smp|
404                         ____cacheline_internodealigned_in_smp|
405                         __weak
406                   }x;
407 our $Modifier;
408 our $Inline     = qr{inline|__always_inline|noinline|__inline|__inline__};
409 our $Member     = qr{->$Ident|\.$Ident|\[[^]]*\]};
410 our $Lval       = qr{$Ident(?:$Member)*};
411
412 our $Int_type   = qr{(?i)llu|ull|ll|lu|ul|l|u};
413 our $Binary     = qr{(?i)0b[01]+$Int_type?};
414 our $Hex        = qr{(?i)0x[0-9a-f]+$Int_type?};
415 our $Int        = qr{[0-9]+$Int_type?};
416 our $Octal      = qr{0[0-7]+$Int_type?};
417 our $String     = qr{"[X\t]*"};
418 our $Float_hex  = qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
419 our $Float_dec  = qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
420 our $Float_int  = qr{(?i)[0-9]+e-?[0-9]+[fl]?};
421 our $Float      = qr{$Float_hex|$Float_dec|$Float_int};
422 our $Constant   = qr{$Float|$Binary|$Octal|$Hex|$Int};
423 our $Assignment = qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
424 our $Compare    = qr{<=|>=|==|!=|<|(?<!-)>};
425 our $Arithmetic = qr{\+|-|\*|\/|%};
426 our $Operators  = qr{
427                         <=|>=|==|!=|
428                         =>|->|<<|>>|<|>|!|~|
429                         &&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
430                   }x;
431
432 our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
433
434 our $BasicType;
435 our $NonptrType;
436 our $NonptrTypeMisordered;
437 our $NonptrTypeWithAttr;
438 our $Type;
439 our $TypeMisordered;
440 our $Declare;
441 our $DeclareMisordered;
442
443 our $NON_ASCII_UTF8     = qr{
444         [\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
445         |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
446         | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
447         |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
448         |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
449         | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
450         |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
451 }x;
452
453 our $UTF8       = qr{
454         [\x09\x0A\x0D\x20-\x7E]              # ASCII
455         | $NON_ASCII_UTF8
456 }x;
457
458 our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
459 our $typeOtherOSTypedefs = qr{(?x:
460         u_(?:char|short|int|long) |          # bsd
461         u(?:nchar|short|int|long)            # sysv
462 )};
463 our $typeKernelTypedefs = qr{(?x:
464         (?:__)?(?:u|s|be|le)(?:8|16|32|64)|
465         atomic_t
466 )};
467 our $typeTypedefs = qr{(?x:
468         $typeC99Typedefs\b|
469         $typeOtherOSTypedefs\b|
470         $typeKernelTypedefs\b
471 )};
472
473 our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
474
475 our $logFunctions = qr{(?x:
476         printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
477         (?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
478         TP_printk|
479         WARN(?:_RATELIMIT|_ONCE|)|
480         panic|
481         MODULE_[A-Z_]+|
482         seq_vprintf|seq_printf|seq_puts
483 )};
484
485 our $allocFunctions = qr{(?x:
486         (?:(?:devm_)?
487                 (?:kv|k|v)[czm]alloc(?:_node|_array)? |
488                 kstrdup(?:_const)? |
489                 kmemdup(?:_nul)?) |
490         (?:\w+)?alloc_skb(?:_ip_align)? |
491                                 # dev_alloc_skb/netdev_alloc_skb, et al
492         dma_alloc_coherent
493 )};
494
495 our $signature_tags = qr{(?xi:
496         Signed-off-by:|
497         Co-developed-by:|
498         Acked-by:|
499         Tested-by:|
500         Reviewed-by:|
501         Reported-by:|
502         Suggested-by:|
503         To:|
504         Cc:
505 )};
506
507 our @typeListMisordered = (
508         qr{char\s+(?:un)?signed},
509         qr{int\s+(?:(?:un)?signed\s+)?short\s},
510         qr{int\s+short(?:\s+(?:un)?signed)},
511         qr{short\s+int(?:\s+(?:un)?signed)},
512         qr{(?:un)?signed\s+int\s+short},
513         qr{short\s+(?:un)?signed},
514         qr{long\s+int\s+(?:un)?signed},
515         qr{int\s+long\s+(?:un)?signed},
516         qr{long\s+(?:un)?signed\s+int},
517         qr{int\s+(?:un)?signed\s+long},
518         qr{int\s+(?:un)?signed},
519         qr{int\s+long\s+long\s+(?:un)?signed},
520         qr{long\s+long\s+int\s+(?:un)?signed},
521         qr{long\s+long\s+(?:un)?signed\s+int},
522         qr{long\s+long\s+(?:un)?signed},
523         qr{long\s+(?:un)?signed},
524 );
525
526 our @typeList = (
527         qr{void},
528         qr{(?:(?:un)?signed\s+)?char},
529         qr{(?:(?:un)?signed\s+)?short\s+int},
530         qr{(?:(?:un)?signed\s+)?short},
531         qr{(?:(?:un)?signed\s+)?int},
532         qr{(?:(?:un)?signed\s+)?long\s+int},
533         qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
534         qr{(?:(?:un)?signed\s+)?long\s+long},
535         qr{(?:(?:un)?signed\s+)?long},
536         qr{(?:un)?signed},
537         qr{float},
538         qr{double},
539         qr{bool},
540         qr{struct\s+$Ident},
541         qr{union\s+$Ident},
542         qr{enum\s+$Ident},
543         qr{${Ident}_t},
544         qr{${Ident}_handler},
545         qr{${Ident}_handler_fn},
546         @typeListMisordered,
547 );
548
549 our $C90_int_types = qr{(?x:
550         long\s+long\s+int\s+(?:un)?signed|
551         long\s+long\s+(?:un)?signed\s+int|
552         long\s+long\s+(?:un)?signed|
553         (?:(?:un)?signed\s+)?long\s+long\s+int|
554         (?:(?:un)?signed\s+)?long\s+long|
555         int\s+long\s+long\s+(?:un)?signed|
556         int\s+(?:(?:un)?signed\s+)?long\s+long|
557
558         long\s+int\s+(?:un)?signed|
559         long\s+(?:un)?signed\s+int|
560         long\s+(?:un)?signed|
561         (?:(?:un)?signed\s+)?long\s+int|
562         (?:(?:un)?signed\s+)?long|
563         int\s+long\s+(?:un)?signed|
564         int\s+(?:(?:un)?signed\s+)?long|
565
566         int\s+(?:un)?signed|
567         (?:(?:un)?signed\s+)?int
568 )};
569
570 our @typeListFile = ();
571 our @typeListWithAttr = (
572         @typeList,
573         qr{struct\s+$InitAttribute\s+$Ident},
574         qr{union\s+$InitAttribute\s+$Ident},
575 );
576
577 our @modifierList = (
578         qr{fastcall},
579 );
580 our @modifierListFile = ();
581
582 our @mode_permission_funcs = (
583         ["module_param", 3],
584         ["module_param_(?:array|named|string)", 4],
585         ["module_param_array_named", 5],
586         ["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
587         ["proc_create(?:_data|)", 2],
588         ["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
589         ["IIO_DEV_ATTR_[A-Z_]+", 1],
590         ["SENSOR_(?:DEVICE_|)ATTR_2", 2],
591         ["SENSOR_TEMPLATE(?:_2|)", 3],
592         ["__ATTR", 2],
593 );
594
595 my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
596
597 #Create a search pattern for all these functions to speed up a loop below
598 our $mode_perms_search = "";
599 foreach my $entry (@mode_permission_funcs) {
600         $mode_perms_search .= '|' if ($mode_perms_search ne "");
601         $mode_perms_search .= $entry->[0];
602 }
603 $mode_perms_search = "(?:${mode_perms_search})";
604
605 our %deprecated_apis = (
606         "synchronize_rcu_bh"                    => "synchronize_rcu",
607         "synchronize_rcu_bh_expedited"          => "synchronize_rcu_expedited",
608         "call_rcu_bh"                           => "call_rcu",
609         "rcu_barrier_bh"                        => "rcu_barrier",
610         "synchronize_sched"                     => "synchronize_rcu",
611         "synchronize_sched_expedited"           => "synchronize_rcu_expedited",
612         "call_rcu_sched"                        => "call_rcu",
613         "rcu_barrier_sched"                     => "rcu_barrier",
614         "get_state_synchronize_sched"           => "get_state_synchronize_rcu",
615         "cond_synchronize_sched"                => "cond_synchronize_rcu",
616 );
617
618 #Create a search pattern for all these strings to speed up a loop below
619 our $deprecated_apis_search = "";
620 foreach my $entry (keys %deprecated_apis) {
621         $deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
622         $deprecated_apis_search .= $entry;
623 }
624 $deprecated_apis_search = "(?:${deprecated_apis_search})";
625
626 our $mode_perms_world_writable = qr{
627         S_IWUGO         |
628         S_IWOTH         |
629         S_IRWXUGO       |
630         S_IALLUGO       |
631         0[0-7][0-7][2367]
632 }x;
633
634 our %mode_permission_string_types = (
635         "S_IRWXU" => 0700,
636         "S_IRUSR" => 0400,
637         "S_IWUSR" => 0200,
638         "S_IXUSR" => 0100,
639         "S_IRWXG" => 0070,
640         "S_IRGRP" => 0040,
641         "S_IWGRP" => 0020,
642         "S_IXGRP" => 0010,
643         "S_IRWXO" => 0007,
644         "S_IROTH" => 0004,
645         "S_IWOTH" => 0002,
646         "S_IXOTH" => 0001,
647         "S_IRWXUGO" => 0777,
648         "S_IRUGO" => 0444,
649         "S_IWUGO" => 0222,
650         "S_IXUGO" => 0111,
651 );
652
653 #Create a search pattern for all these strings to speed up a loop below
654 our $mode_perms_string_search = "";
655 foreach my $entry (keys %mode_permission_string_types) {
656         $mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
657         $mode_perms_string_search .= $entry;
658 }
659 our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
660 our $multi_mode_perms_string_search = qr{
661         ${single_mode_perms_string_search}
662         (?:\s*\|\s*${single_mode_perms_string_search})*
663 }x;
664
665 sub perms_to_octal {
666         my ($string) = @_;
667
668         return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
669
670         my $val = "";
671         my $oval = "";
672         my $to = 0;
673         my $curpos = 0;
674         my $lastpos = 0;
675         while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
676                 $curpos = pos($string);
677                 my $match = $2;
678                 my $omatch = $1;
679                 last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
680                 $lastpos = $curpos;
681                 $to |= $mode_permission_string_types{$match};
682                 $val .= '\s*\|\s*' if ($val ne "");
683                 $val .= $match;
684                 $oval .= $omatch;
685         }
686         $oval =~ s/^\s*\|\s*//;
687         $oval =~ s/\s*\|\s*$//;
688         return sprintf("%04o", $to);
689 }
690
691 our $allowed_asm_includes = qr{(?x:
692         irq|
693         memory|
694         time|
695         reboot
696 )};
697 # memory.h: ARM has a custom one
698
699 # Load common spelling mistakes and build regular expression list.
700 my $misspellings;
701 my %spelling_fix;
702
703 if (open(my $spelling, '<', $spelling_file)) {
704         while (<$spelling>) {
705                 my $line = $_;
706
707                 $line =~ s/\s*\n?$//g;
708                 $line =~ s/^\s*//g;
709
710                 next if ($line =~ m/^\s*#/);
711                 next if ($line =~ m/^\s*$/);
712
713                 my ($suspect, $fix) = split(/\|\|/, $line);
714
715                 $spelling_fix{$suspect} = $fix;
716         }
717         close($spelling);
718 } else {
719         warn "No typos will be found - file '$spelling_file': $!\n";
720 }
721
722 if ($codespell) {
723         if (open(my $spelling, '<', $codespellfile)) {
724                 while (<$spelling>) {
725                         my $line = $_;
726
727                         $line =~ s/\s*\n?$//g;
728                         $line =~ s/^\s*//g;
729
730                         next if ($line =~ m/^\s*#/);
731                         next if ($line =~ m/^\s*$/);
732                         next if ($line =~ m/, disabled/i);
733
734                         $line =~ s/,.*$//;
735
736                         my ($suspect, $fix) = split(/->/, $line);
737
738                         $spelling_fix{$suspect} = $fix;
739                 }
740                 close($spelling);
741         } else {
742                 warn "No codespell typos will be found - file '$codespellfile': $!\n";
743         }
744 }
745
746 $misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
747
748 sub read_words {
749         my ($wordsRef, $file) = @_;
750
751         if (open(my $words, '<', $file)) {
752                 while (<$words>) {
753                         my $line = $_;
754
755                         $line =~ s/\s*\n?$//g;
756                         $line =~ s/^\s*//g;
757
758                         next if ($line =~ m/^\s*#/);
759                         next if ($line =~ m/^\s*$/);
760                         if ($line =~ /\s/) {
761                                 print("$file: '$line' invalid - ignored\n");
762                                 next;
763                         }
764
765                         $$wordsRef .= '|' if (defined $$wordsRef);
766                         $$wordsRef .= $line;
767                 }
768                 close($file);
769                 return 1;
770         }
771
772         return 0;
773 }
774
775 my $const_structs;
776 if (show_type("CONST_STRUCT")) {
777         read_words(\$const_structs, $conststructsfile)
778             or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
779 }
780
781 if (defined($typedefsfile)) {
782         my $typeOtherTypedefs;
783         read_words(\$typeOtherTypedefs, $typedefsfile)
784             or warn "No additional types will be considered - file '$typedefsfile': $!\n";
785         $typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
786 }
787
788 sub build_types {
789         my $mods = "(?x:  \n" . join("|\n  ", (@modifierList, @modifierListFile)) . "\n)";
790         my $all = "(?x:  \n" . join("|\n  ", (@typeList, @typeListFile)) . "\n)";
791         my $Misordered = "(?x:  \n" . join("|\n  ", @typeListMisordered) . "\n)";
792         my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
793         $Modifier       = qr{(?:$Attribute|$Sparse|$mods)};
794         $BasicType      = qr{
795                                 (?:$typeTypedefs\b)|
796                                 (?:${all}\b)
797                 }x;
798         $NonptrType     = qr{
799                         (?:$Modifier\s+|const\s+)*
800                         (?:
801                                 (?:typeof|__typeof__)\s*\([^\)]*\)|
802                                 (?:$typeTypedefs\b)|
803                                 (?:${all}\b)
804                         )
805                         (?:\s+$Modifier|\s+const)*
806                   }x;
807         $NonptrTypeMisordered   = qr{
808                         (?:$Modifier\s+|const\s+)*
809                         (?:
810                                 (?:${Misordered}\b)
811                         )
812                         (?:\s+$Modifier|\s+const)*
813                   }x;
814         $NonptrTypeWithAttr     = qr{
815                         (?:$Modifier\s+|const\s+)*
816                         (?:
817                                 (?:typeof|__typeof__)\s*\([^\)]*\)|
818                                 (?:$typeTypedefs\b)|
819                                 (?:${allWithAttr}\b)
820                         )
821                         (?:\s+$Modifier|\s+const)*
822                   }x;
823         $Type   = qr{
824                         $NonptrType
825                         (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
826                         (?:\s+$Inline|\s+$Modifier)*
827                   }x;
828         $TypeMisordered = qr{
829                         $NonptrTypeMisordered
830                         (?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
831                         (?:\s+$Inline|\s+$Modifier)*
832                   }x;
833         $Declare        = qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
834         $DeclareMisordered      = qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
835 }
836 build_types();
837
838 our $Typecast   = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
839
840 # Using $balanced_parens, $LvalOrFunc, or $FuncArg
841 # requires at least perl version v5.10.0
842 # Any use must be runtime checked with $^V
843
844 our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
845 our $LvalOrFunc = qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
846 our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
847
848 our $declaration_macros = qr{(?x:
849         (?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
850         (?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
851         (?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
852 )};
853
854 sub deparenthesize {
855         my ($string) = @_;
856         return "" if (!defined($string));
857
858         while ($string =~ /^\s*\(.*\)\s*$/) {
859                 $string =~ s@^\s*\(\s*@@;
860                 $string =~ s@\s*\)\s*$@@;
861         }
862
863         $string =~ s@\s+@ @g;
864
865         return $string;
866 }
867
868 sub seed_camelcase_file {
869         my ($file) = @_;
870
871         return if (!(-f $file));
872
873         local $/;
874
875         open(my $include_file, '<', "$file")
876             or warn "$P: Can't read '$file' $!\n";
877         my $text = <$include_file>;
878         close($include_file);
879
880         my @lines = split('\n', $text);
881
882         foreach my $line (@lines) {
883                 next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
884                 if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
885                         $camelcase{$1} = 1;
886                 } elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
887                         $camelcase{$1} = 1;
888                 } elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
889                         $camelcase{$1} = 1;
890                 }
891         }
892 }
893
894 our %maintained_status = ();
895
896 sub is_maintained_obsolete {
897         my ($filename) = @_;
898
899         return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
900
901         if (!exists($maintained_status{$filename})) {
902                 $maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
903         }
904
905         return $maintained_status{$filename} =~ /obsolete/i;
906 }
907
908 sub is_SPDX_License_valid {
909         my ($license) = @_;
910
911         return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$root/.git"));
912
913         my $root_path = abs_path($root);
914         my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
915         return 0 if ($status ne "");
916         return 1;
917 }
918
919 my $camelcase_seeded = 0;
920 sub seed_camelcase_includes {
921         return if ($camelcase_seeded);
922
923         my $files;
924         my $camelcase_cache = "";
925         my @include_files = ();
926
927         $camelcase_seeded = 1;
928
929         if (-e ".git") {
930                 my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
931                 chomp $git_last_include_commit;
932                 $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
933         } else {
934                 my $last_mod_date = 0;
935                 $files = `find $root/include -name "*.h"`;
936                 @include_files = split('\n', $files);
937                 foreach my $file (@include_files) {
938                         my $date = POSIX::strftime("%Y%m%d%H%M",
939                                                    localtime((stat $file)[9]));
940                         $last_mod_date = $date if ($last_mod_date < $date);
941                 }
942                 $camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
943         }
944
945         if ($camelcase_cache ne "" && -f $camelcase_cache) {
946                 open(my $camelcase_file, '<', "$camelcase_cache")
947                     or warn "$P: Can't read '$camelcase_cache' $!\n";
948                 while (<$camelcase_file>) {
949                         chomp;
950                         $camelcase{$_} = 1;
951                 }
952                 close($camelcase_file);
953
954                 return;
955         }
956
957         if (-e ".git") {
958                 $files = `${git_command} ls-files "include/*.h"`;
959                 @include_files = split('\n', $files);
960         }
961
962         foreach my $file (@include_files) {
963                 seed_camelcase_file($file);
964         }
965
966         if ($camelcase_cache ne "") {
967                 unlink glob ".checkpatch-camelcase.*";
968                 open(my $camelcase_file, '>', "$camelcase_cache")
969                     or warn "$P: Can't write '$camelcase_cache' $!\n";
970                 foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
971                         print $camelcase_file ("$_\n");
972                 }
973                 close($camelcase_file);
974         }
975 }
976
977 sub git_is_single_file {
978         my ($filename) = @_;
979
980         return 0 if ((which("git") eq "") || !(-e "$gitroot"));
981
982         my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
983         my $count = $output =~ tr/\n//;
984         return $count eq 1 && $output =~ m{^${filename}$};
985 }
986
987 sub git_commit_info {
988         my ($commit, $id, $desc) = @_;
989
990         return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
991
992         my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
993         $output =~ s/^\s*//gm;
994         my @lines = split("\n", $output);
995
996         return ($id, $desc) if ($#lines < 0);
997
998         if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
999 # Maybe one day convert this block of bash into something that returns
1000 # all matching commit ids, but it's very slow...
1001 #
1002 #               echo "checking commits $1..."
1003 #               git rev-list --remotes | grep -i "^$1" |
1004 #               while read line ; do
1005 #                   git log --format='%H %s' -1 $line |
1006 #                   echo "commit $(cut -c 1-12,41-)"
1007 #               done
1008         } elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
1009                 $id = undef;
1010         } else {
1011                 $id = substr($lines[0], 0, 12);
1012                 $desc = substr($lines[0], 41);
1013         }
1014
1015         return ($id, $desc);
1016 }
1017
1018 $chk_signoff = 0 if ($file);
1019
1020 my @rawlines = ();
1021 my @lines = ();
1022 my @fixed = ();
1023 my @fixed_inserted = ();
1024 my @fixed_deleted = ();
1025 my $fixlinenr = -1;
1026
1027 # If input is git commits, extract all commits from the commit expressions.
1028 # For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1029 die "$P: No git repository found\n" if ($git && !-e ".git");
1030
1031 if ($git) {
1032         my @commits = ();
1033         foreach my $commit_expr (@ARGV) {
1034                 my $git_range;
1035                 if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1036                         $git_range = "-$2 $1";
1037                 } elsif ($commit_expr =~ m/\.\./) {
1038                         $git_range = "$commit_expr";
1039                 } else {
1040                         $git_range = "-1 $commit_expr";
1041                 }
1042                 my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1043                 foreach my $line (split(/\n/, $lines)) {
1044                         $line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1045                         next if (!defined($1) || !defined($2));
1046                         my $sha1 = $1;
1047                         my $subject = $2;
1048                         unshift(@commits, $sha1);
1049                         $git_commits{$sha1} = $subject;
1050                 }
1051         }
1052         die "$P: no git commits after extraction!\n" if (@commits == 0);
1053         @ARGV = @commits;
1054 }
1055
1056 my $vname;
1057 $allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1058 for my $filename (@ARGV) {
1059         my $FILE;
1060         my $is_git_file = git_is_single_file($filename);
1061         my $oldfile = $file;
1062         $file = 1 if ($is_git_file);
1063         if ($git) {
1064                 open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1065                         die "$P: $filename: git format-patch failed - $!\n";
1066         } elsif ($file) {
1067                 open($FILE, '-|', "diff -u /dev/null $filename") ||
1068                         die "$P: $filename: diff failed - $!\n";
1069         } elsif ($filename eq '-') {
1070                 open($FILE, '<&STDIN');
1071         } else {
1072                 open($FILE, '<', "$filename") ||
1073                         die "$P: $filename: open failed - $!\n";
1074         }
1075         if ($filename eq '-') {
1076                 $vname = 'Your patch';
1077         } elsif ($git) {
1078                 $vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1079         } else {
1080                 $vname = $filename;
1081         }
1082         while (<$FILE>) {
1083                 chomp;
1084                 push(@rawlines, $_);
1085                 $vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1086         }
1087         close($FILE);
1088
1089         if ($#ARGV > 0 && $quiet == 0) {
1090                 print '-' x length($vname) . "\n";
1091                 print "$vname\n";
1092                 print '-' x length($vname) . "\n";
1093         }
1094
1095         if (!process($filename)) {
1096                 $exit = 1;
1097         }
1098         @rawlines = ();
1099         @lines = ();
1100         @fixed = ();
1101         @fixed_inserted = ();
1102         @fixed_deleted = ();
1103         $fixlinenr = -1;
1104         @modifierListFile = ();
1105         @typeListFile = ();
1106         build_types();
1107         $file = $oldfile if ($is_git_file);
1108 }
1109
1110 if (!$quiet) {
1111         hash_show_words(\%use_type, "Used");
1112         hash_show_words(\%ignore_type, "Ignored");
1113
1114         if (!$perl_version_ok) {
1115                 print << "EOM"
1116
1117 NOTE: perl $^V is not modern enough to detect all possible issues.
1118       An upgrade to at least perl $minimum_perl_version is suggested.
1119 EOM
1120         }
1121         if ($exit) {
1122                 print << "EOM"
1123
1124 NOTE: If any of the errors are false positives, please report
1125       them to the maintainer, see CHECKPATCH in MAINTAINERS.
1126 EOM
1127         }
1128 }
1129
1130 exit($exit);
1131
1132 sub top_of_kernel_tree {
1133         my ($root) = @_;
1134
1135         my @tree_check = (
1136                 "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1137                 "README", "Documentation", "arch", "include", "drivers",
1138                 "fs", "init", "ipc", "kernel", "lib", "scripts",
1139         );
1140
1141         foreach my $check (@tree_check) {
1142                 if (! -e $root . '/' . $check) {
1143                         return 0;
1144                 }
1145         }
1146         return 1;
1147 }
1148
1149 sub parse_email {
1150         my ($formatted_email) = @_;
1151
1152         my $name = "";
1153         my $name_comment = "";
1154         my $address = "";
1155         my $comment = "";
1156
1157         if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1158                 $name = $1;
1159                 $address = $2;
1160                 $comment = $3 if defined $3;
1161         } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1162                 $address = $1;
1163                 $comment = $2 if defined $2;
1164         } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1165                 $address = $1;
1166                 $comment = $2 if defined $2;
1167                 $formatted_email =~ s/\Q$address\E.*$//;
1168                 $name = $formatted_email;
1169                 $name = trim($name);
1170                 $name =~ s/^\"|\"$//g;
1171                 # If there's a name left after stripping spaces and
1172                 # leading quotes, and the address doesn't have both
1173                 # leading and trailing angle brackets, the address
1174                 # is invalid. ie:
1175                 #   "joe smith joe@smith.com" bad
1176                 #   "joe smith <joe@smith.com" bad
1177                 if ($name ne "" && $address !~ /^<[^>]+>$/) {
1178                         $name = "";
1179                         $address = "";
1180                         $comment = "";
1181                 }
1182         }
1183
1184         $name = trim($name);
1185         $name =~ s/^\"|\"$//g;
1186         $name =~ s/(\s*\([^\)]+\))\s*//;
1187         if (defined($1)) {
1188                 $name_comment = trim($1);
1189         }
1190         $address = trim($address);
1191         $address =~ s/^\<|\>$//g;
1192
1193         if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1194                 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1195                 $name = "\"$name\"";
1196         }
1197
1198         return ($name, $name_comment, $address, $comment);
1199 }
1200
1201 sub format_email {
1202         my ($name, $address) = @_;
1203
1204         my $formatted_email;
1205
1206         $name = trim($name);
1207         $name =~ s/^\"|\"$//g;
1208         $address = trim($address);
1209
1210         if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1211                 $name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1212                 $name = "\"$name\"";
1213         }
1214
1215         if ("$name" eq "") {
1216                 $formatted_email = "$address";
1217         } else {
1218                 $formatted_email = "$name <$address>";
1219         }
1220
1221         return $formatted_email;
1222 }
1223
1224 sub reformat_email {
1225         my ($email) = @_;
1226
1227         my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1228         return format_email($email_name, $email_address);
1229 }
1230
1231 sub same_email_addresses {
1232         my ($email1, $email2) = @_;
1233
1234         my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1235         my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1236
1237         return $email1_name eq $email2_name &&
1238                $email1_address eq $email2_address;
1239 }
1240
1241 sub which {
1242         my ($bin) = @_;
1243
1244         foreach my $path (split(/:/, $ENV{PATH})) {
1245                 if (-e "$path/$bin") {
1246                         return "$path/$bin";
1247                 }
1248         }
1249
1250         return "";
1251 }
1252
1253 sub which_conf {
1254         my ($conf) = @_;
1255
1256         foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1257                 if (-e "$path/$conf") {
1258                         return "$path/$conf";
1259                 }
1260         }
1261
1262         return "";
1263 }
1264
1265 sub expand_tabs {
1266         my ($str) = @_;
1267
1268         my $res = '';
1269         my $n = 0;
1270         for my $c (split(//, $str)) {
1271                 if ($c eq "\t") {
1272                         $res .= ' ';
1273                         $n++;
1274                         for (; ($n % $tabsize) != 0; $n++) {
1275                                 $res .= ' ';
1276                         }
1277                         next;
1278                 }
1279                 $res .= $c;
1280                 $n++;
1281         }
1282
1283         return $res;
1284 }
1285 sub copy_spacing {
1286         (my $res = shift) =~ tr/\t/ /c;
1287         return $res;
1288 }
1289
1290 sub line_stats {
1291         my ($line) = @_;
1292
1293         # Drop the diff line leader and expand tabs
1294         $line =~ s/^.//;
1295         $line = expand_tabs($line);
1296
1297         # Pick the indent from the front of the line.
1298         my ($white) = ($line =~ /^(\s*)/);
1299
1300         return (length($line), length($white));
1301 }
1302
1303 my $sanitise_quote = '';
1304
1305 sub sanitise_line_reset {
1306         my ($in_comment) = @_;
1307
1308         if ($in_comment) {
1309                 $sanitise_quote = '*/';
1310         } else {
1311                 $sanitise_quote = '';
1312         }
1313 }
1314 sub sanitise_line {
1315         my ($line) = @_;
1316
1317         my $res = '';
1318         my $l = '';
1319
1320         my $qlen = 0;
1321         my $off = 0;
1322         my $c;
1323
1324         # Always copy over the diff marker.
1325         $res = substr($line, 0, 1);
1326
1327         for ($off = 1; $off < length($line); $off++) {
1328                 $c = substr($line, $off, 1);
1329
1330                 # Comments we are whacking completely including the begin
1331                 # and end, all to $;.
1332                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1333                         $sanitise_quote = '*/';
1334
1335                         substr($res, $off, 2, "$;$;");
1336                         $off++;
1337                         next;
1338                 }
1339                 if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1340                         $sanitise_quote = '';
1341                         substr($res, $off, 2, "$;$;");
1342                         $off++;
1343                         next;
1344                 }
1345                 if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1346                         $sanitise_quote = '//';
1347
1348                         substr($res, $off, 2, $sanitise_quote);
1349                         $off++;
1350                         next;
1351                 }
1352
1353                 # A \ in a string means ignore the next character.
1354                 if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1355                     $c eq "\\") {
1356                         substr($res, $off, 2, 'XX');
1357                         $off++;
1358                         next;
1359                 }
1360                 # Regular quotes.
1361                 if ($c eq "'" || $c eq '"') {
1362                         if ($sanitise_quote eq '') {
1363                                 $sanitise_quote = $c;
1364
1365                                 substr($res, $off, 1, $c);
1366                                 next;
1367                         } elsif ($sanitise_quote eq $c) {
1368                                 $sanitise_quote = '';
1369                         }
1370                 }
1371
1372                 #print "c<$c> SQ<$sanitise_quote>\n";
1373                 if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1374                         substr($res, $off, 1, $;);
1375                 } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1376                         substr($res, $off, 1, $;);
1377                 } elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1378                         substr($res, $off, 1, 'X');
1379                 } else {
1380                         substr($res, $off, 1, $c);
1381                 }
1382         }
1383
1384         if ($sanitise_quote eq '//') {
1385                 $sanitise_quote = '';
1386         }
1387
1388         # The pathname on a #include may be surrounded by '<' and '>'.
1389         if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1390                 my $clean = 'X' x length($1);
1391                 $res =~ s@\<.*\>@<$clean>@;
1392
1393         # The whole of a #error is a string.
1394         } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1395                 my $clean = 'X' x length($1);
1396                 $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1397         }
1398
1399         if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1400                 my $match = $1;
1401                 $res =~ s/\Q$match\E/"$;" x length($match)/e;
1402         }
1403
1404         return $res;
1405 }
1406
1407 sub get_quoted_string {
1408         my ($line, $rawline) = @_;
1409
1410         return "" if (!defined($line) || !defined($rawline));
1411         return "" if ($line !~ m/($String)/g);
1412         return substr($rawline, $-[0], $+[0] - $-[0]);
1413 }
1414
1415 sub ctx_statement_block {
1416         my ($linenr, $remain, $off) = @_;
1417         my $line = $linenr - 1;
1418         my $blk = '';
1419         my $soff = $off;
1420         my $coff = $off - 1;
1421         my $coff_set = 0;
1422
1423         my $loff = 0;
1424
1425         my $type = '';
1426         my $level = 0;
1427         my @stack = ();
1428         my $p;
1429         my $c;
1430         my $len = 0;
1431
1432         my $remainder;
1433         while (1) {
1434                 @stack = (['', 0]) if ($#stack == -1);
1435
1436                 #warn "CSB: blk<$blk> remain<$remain>\n";
1437                 # If we are about to drop off the end, pull in more
1438                 # context.
1439                 if ($off >= $len) {
1440                         for (; $remain > 0; $line++) {
1441                                 last if (!defined $lines[$line]);
1442                                 next if ($lines[$line] =~ /^-/);
1443                                 $remain--;
1444                                 $loff = $len;
1445                                 $blk .= $lines[$line] . "\n";
1446                                 $len = length($blk);
1447                                 $line++;
1448                                 last;
1449                         }
1450                         # Bail if there is no further context.
1451                         #warn "CSB: blk<$blk> off<$off> len<$len>\n";
1452                         if ($off >= $len) {
1453                                 last;
1454                         }
1455                         if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1456                                 $level++;
1457                                 $type = '#';
1458                         }
1459                 }
1460                 $p = $c;
1461                 $c = substr($blk, $off, 1);
1462                 $remainder = substr($blk, $off);
1463
1464                 #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1465
1466                 # Handle nested #if/#else.
1467                 if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1468                         push(@stack, [ $type, $level ]);
1469                 } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1470                         ($type, $level) = @{$stack[$#stack - 1]};
1471                 } elsif ($remainder =~ /^#\s*endif\b/) {
1472                         ($type, $level) = @{pop(@stack)};
1473                 }
1474
1475                 # Statement ends at the ';' or a close '}' at the
1476                 # outermost level.
1477                 if ($level == 0 && $c eq ';') {
1478                         last;
1479                 }
1480
1481                 # An else is really a conditional as long as its not else if
1482                 if ($level == 0 && $coff_set == 0 &&
1483                                 (!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1484                                 $remainder =~ /^(else)(?:\s|{)/ &&
1485                                 $remainder !~ /^else\s+if\b/) {
1486                         $coff = $off + length($1) - 1;
1487                         $coff_set = 1;
1488                         #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1489                         #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1490                 }
1491
1492                 if (($type eq '' || $type eq '(') && $c eq '(') {
1493                         $level++;
1494                         $type = '(';
1495                 }
1496                 if ($type eq '(' && $c eq ')') {
1497                         $level--;
1498                         $type = ($level != 0)? '(' : '';
1499
1500                         if ($level == 0 && $coff < $soff) {
1501                                 $coff = $off;
1502                                 $coff_set = 1;
1503                                 #warn "CSB: mark coff<$coff>\n";
1504                         }
1505                 }
1506                 if (($type eq '' || $type eq '{') && $c eq '{') {
1507                         $level++;
1508                         $type = '{';
1509                 }
1510                 if ($type eq '{' && $c eq '}') {
1511                         $level--;
1512                         $type = ($level != 0)? '{' : '';
1513
1514                         if ($level == 0) {
1515                                 if (substr($blk, $off + 1, 1) eq ';') {
1516                                         $off++;
1517                                 }
1518                                 last;
1519                         }
1520                 }
1521                 # Preprocessor commands end at the newline unless escaped.
1522                 if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1523                         $level--;
1524                         $type = '';
1525                         $off++;
1526                         last;
1527                 }
1528                 $off++;
1529         }
1530         # We are truly at the end, so shuffle to the next line.
1531         if ($off == $len) {
1532                 $loff = $len + 1;
1533                 $line++;
1534                 $remain--;
1535         }
1536
1537         my $statement = substr($blk, $soff, $off - $soff + 1);
1538         my $condition = substr($blk, $soff, $coff - $soff + 1);
1539
1540         #warn "STATEMENT<$statement>\n";
1541         #warn "CONDITION<$condition>\n";
1542
1543         #print "coff<$coff> soff<$off> loff<$loff>\n";
1544
1545         return ($statement, $condition,
1546                         $line, $remain + 1, $off - $loff + 1, $level);
1547 }
1548
1549 sub statement_lines {
1550         my ($stmt) = @_;
1551
1552         # Strip the diff line prefixes and rip blank lines at start and end.
1553         $stmt =~ s/(^|\n)./$1/g;
1554         $stmt =~ s/^\s*//;
1555         $stmt =~ s/\s*$//;
1556
1557         my @stmt_lines = ($stmt =~ /\n/g);
1558
1559         return $#stmt_lines + 2;
1560 }
1561
1562 sub statement_rawlines {
1563         my ($stmt) = @_;
1564
1565         my @stmt_lines = ($stmt =~ /\n/g);
1566
1567         return $#stmt_lines + 2;
1568 }
1569
1570 sub statement_block_size {
1571         my ($stmt) = @_;
1572
1573         $stmt =~ s/(^|\n)./$1/g;
1574         $stmt =~ s/^\s*{//;
1575         $stmt =~ s/}\s*$//;
1576         $stmt =~ s/^\s*//;
1577         $stmt =~ s/\s*$//;
1578
1579         my @stmt_lines = ($stmt =~ /\n/g);
1580         my @stmt_statements = ($stmt =~ /;/g);
1581
1582         my $stmt_lines = $#stmt_lines + 2;
1583         my $stmt_statements = $#stmt_statements + 1;
1584
1585         if ($stmt_lines > $stmt_statements) {
1586                 return $stmt_lines;
1587         } else {
1588                 return $stmt_statements;
1589         }
1590 }
1591
1592 sub ctx_statement_full {
1593         my ($linenr, $remain, $off) = @_;
1594         my ($statement, $condition, $level);
1595
1596         my (@chunks);
1597
1598         # Grab the first conditional/block pair.
1599         ($statement, $condition, $linenr, $remain, $off, $level) =
1600                                 ctx_statement_block($linenr, $remain, $off);
1601         #print "F: c<$condition> s<$statement> remain<$remain>\n";
1602         push(@chunks, [ $condition, $statement ]);
1603         if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1604                 return ($level, $linenr, @chunks);
1605         }
1606
1607         # Pull in the following conditional/block pairs and see if they
1608         # could continue the statement.
1609         for (;;) {
1610                 ($statement, $condition, $linenr, $remain, $off, $level) =
1611                                 ctx_statement_block($linenr, $remain, $off);
1612                 #print "C: c<$condition> s<$statement> remain<$remain>\n";
1613                 last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1614                 #print "C: push\n";
1615                 push(@chunks, [ $condition, $statement ]);
1616         }
1617
1618         return ($level, $linenr, @chunks);
1619 }
1620
1621 sub ctx_block_get {
1622         my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1623         my $line;
1624         my $start = $linenr - 1;
1625         my $blk = '';
1626         my @o;
1627         my @c;
1628         my @res = ();
1629
1630         my $level = 0;
1631         my @stack = ($level);
1632         for ($line = $start; $remain > 0; $line++) {
1633                 next if ($rawlines[$line] =~ /^-/);
1634                 $remain--;
1635
1636                 $blk .= $rawlines[$line];
1637
1638                 # Handle nested #if/#else.
1639                 if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1640                         push(@stack, $level);
1641                 } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1642                         $level = $stack[$#stack - 1];
1643                 } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1644                         $level = pop(@stack);
1645                 }
1646
1647                 foreach my $c (split(//, $lines[$line])) {
1648                         ##print "C<$c>L<$level><$open$close>O<$off>\n";
1649                         if ($off > 0) {
1650                                 $off--;
1651                                 next;
1652                         }
1653
1654                         if ($c eq $close && $level > 0) {
1655                                 $level--;
1656                                 last if ($level == 0);
1657                         } elsif ($c eq $open) {
1658                                 $level++;
1659                         }
1660                 }
1661
1662                 if (!$outer || $level <= 1) {
1663                         push(@res, $rawlines[$line]);
1664                 }
1665
1666                 last if ($level == 0);
1667         }
1668
1669         return ($level, @res);
1670 }
1671 sub ctx_block_outer {
1672         my ($linenr, $remain) = @_;
1673
1674         my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1675         return @r;
1676 }
1677 sub ctx_block {
1678         my ($linenr, $remain) = @_;
1679
1680         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1681         return @r;
1682 }
1683 sub ctx_statement {
1684         my ($linenr, $remain, $off) = @_;
1685
1686         my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1687         return @r;
1688 }
1689 sub ctx_block_level {
1690         my ($linenr, $remain) = @_;
1691
1692         return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1693 }
1694 sub ctx_statement_level {
1695         my ($linenr, $remain, $off) = @_;
1696
1697         return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1698 }
1699
1700 sub ctx_locate_comment {
1701         my ($first_line, $end_line) = @_;
1702
1703         # If c99 comment on the current line, or the line before or after
1704         my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1705         return $current_comment if (defined $current_comment);
1706         ($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1707         return $current_comment if (defined $current_comment);
1708         ($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1709         return $current_comment if (defined $current_comment);
1710
1711         # Catch a comment on the end of the line itself.
1712         ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1713         return $current_comment if (defined $current_comment);
1714
1715         # Look through the context and try and figure out if there is a
1716         # comment.
1717         my $in_comment = 0;
1718         $current_comment = '';
1719         for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1720                 my $line = $rawlines[$linenr - 1];
1721                 #warn "           $line\n";
1722                 if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1723                         $in_comment = 1;
1724                 }
1725                 if ($line =~ m@/\*@) {
1726                         $in_comment = 1;
1727                 }
1728                 if (!$in_comment && $current_comment ne '') {
1729                         $current_comment = '';
1730                 }
1731                 $current_comment .= $line . "\n" if ($in_comment);
1732                 if ($line =~ m@\*/@) {
1733                         $in_comment = 0;
1734                 }
1735         }
1736
1737         chomp($current_comment);
1738         return($current_comment);
1739 }
1740 sub ctx_has_comment {
1741         my ($first_line, $end_line) = @_;
1742         my $cmt = ctx_locate_comment($first_line, $end_line);
1743
1744         ##print "LINE: $rawlines[$end_line - 1 ]\n";
1745         ##print "CMMT: $cmt\n";
1746
1747         return ($cmt ne '');
1748 }
1749
1750 sub raw_line {
1751         my ($linenr, $cnt) = @_;
1752
1753         my $offset = $linenr - 1;
1754         $cnt++;
1755
1756         my $line;
1757         while ($cnt) {
1758                 $line = $rawlines[$offset++];
1759                 next if (defined($line) && $line =~ /^-/);
1760                 $cnt--;
1761         }
1762
1763         return $line;
1764 }
1765
1766 sub get_stat_real {
1767         my ($linenr, $lc) = @_;
1768
1769         my $stat_real = raw_line($linenr, 0);
1770         for (my $count = $linenr + 1; $count <= $lc; $count++) {
1771                 $stat_real = $stat_real . "\n" . raw_line($count, 0);
1772         }
1773
1774         return $stat_real;
1775 }
1776
1777 sub get_stat_here {
1778         my ($linenr, $cnt, $here) = @_;
1779
1780         my $herectx = $here . "\n";
1781         for (my $n = 0; $n < $cnt; $n++) {
1782                 $herectx .= raw_line($linenr, $n) . "\n";
1783         }
1784
1785         return $herectx;
1786 }
1787
1788 sub cat_vet {
1789         my ($vet) = @_;
1790         my ($res, $coded);
1791
1792         $res = '';
1793         while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1794                 $res .= $1;
1795                 if ($2 ne '') {
1796                         $coded = sprintf("^%c", unpack('C', $2) + 64);
1797                         $res .= $coded;
1798                 }
1799         }
1800         $res =~ s/$/\$/;
1801
1802         return $res;
1803 }
1804
1805 my $av_preprocessor = 0;
1806 my $av_pending;
1807 my @av_paren_type;
1808 my $av_pend_colon;
1809
1810 sub annotate_reset {
1811         $av_preprocessor = 0;
1812         $av_pending = '_';
1813         @av_paren_type = ('E');
1814         $av_pend_colon = 'O';
1815 }
1816
1817 sub annotate_values {
1818         my ($stream, $type) = @_;
1819
1820         my $res;
1821         my $var = '_' x length($stream);
1822         my $cur = $stream;
1823
1824         print "$stream\n" if ($dbg_values > 1);
1825
1826         while (length($cur)) {
1827                 @av_paren_type = ('E') if ($#av_paren_type < 0);
1828                 print " <" . join('', @av_paren_type) .
1829                                 "> <$type> <$av_pending>" if ($dbg_values > 1);
1830                 if ($cur =~ /^(\s+)/o) {
1831                         print "WS($1)\n" if ($dbg_values > 1);
1832                         if ($1 =~ /\n/ && $av_preprocessor) {
1833                                 $type = pop(@av_paren_type);
1834                                 $av_preprocessor = 0;
1835                         }
1836
1837                 } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1838                         print "CAST($1)\n" if ($dbg_values > 1);
1839                         push(@av_paren_type, $type);
1840                         $type = 'c';
1841
1842                 } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1843                         print "DECLARE($1)\n" if ($dbg_values > 1);
1844                         $type = 'T';
1845
1846                 } elsif ($cur =~ /^($Modifier)\s*/) {
1847                         print "MODIFIER($1)\n" if ($dbg_values > 1);
1848                         $type = 'T';
1849
1850                 } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1851                         print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1852                         $av_preprocessor = 1;
1853                         push(@av_paren_type, $type);
1854                         if ($2 ne '') {
1855                                 $av_pending = 'N';
1856                         }
1857                         $type = 'E';
1858
1859                 } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1860                         print "UNDEF($1)\n" if ($dbg_values > 1);
1861                         $av_preprocessor = 1;
1862                         push(@av_paren_type, $type);
1863
1864                 } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1865                         print "PRE_START($1)\n" if ($dbg_values > 1);
1866                         $av_preprocessor = 1;
1867
1868                         push(@av_paren_type, $type);
1869                         push(@av_paren_type, $type);
1870                         $type = 'E';
1871
1872                 } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1873                         print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1874                         $av_preprocessor = 1;
1875
1876                         push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1877
1878                         $type = 'E';
1879
1880                 } elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1881                         print "PRE_END($1)\n" if ($dbg_values > 1);
1882
1883                         $av_preprocessor = 1;
1884
1885                         # Assume all arms of the conditional end as this
1886                         # one does, and continue as if the #endif was not here.
1887                         pop(@av_paren_type);
1888                         push(@av_paren_type, $type);
1889                         $type = 'E';
1890
1891                 } elsif ($cur =~ /^(\\\n)/o) {
1892                         print "PRECONT($1)\n" if ($dbg_values > 1);
1893
1894                 } elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1895                         print "ATTR($1)\n" if ($dbg_values > 1);
1896                         $av_pending = $type;
1897                         $type = 'N';
1898
1899                 } elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1900                         print "SIZEOF($1)\n" if ($dbg_values > 1);
1901                         if (defined $2) {
1902                                 $av_pending = 'V';
1903                         }
1904                         $type = 'N';
1905
1906                 } elsif ($cur =~ /^(if|while|for)\b/o) {
1907                         print "COND($1)\n" if ($dbg_values > 1);
1908                         $av_pending = 'E';
1909                         $type = 'N';
1910
1911                 } elsif ($cur =~/^(case)/o) {
1912                         print "CASE($1)\n" if ($dbg_values > 1);
1913                         $av_pend_colon = 'C';
1914                         $type = 'N';
1915
1916                 } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1917                         print "KEYWORD($1)\n" if ($dbg_values > 1);
1918                         $type = 'N';
1919
1920                 } elsif ($cur =~ /^(\()/o) {
1921                         print "PAREN('$1')\n" if ($dbg_values > 1);
1922                         push(@av_paren_type, $av_pending);
1923                         $av_pending = '_';
1924                         $type = 'N';
1925
1926                 } elsif ($cur =~ /^(\))/o) {
1927                         my $new_type = pop(@av_paren_type);
1928                         if ($new_type ne '_') {
1929                                 $type = $new_type;
1930                                 print "PAREN('$1') -> $type\n"
1931                                                         if ($dbg_values > 1);
1932                         } else {
1933                                 print "PAREN('$1')\n" if ($dbg_values > 1);
1934                         }
1935
1936                 } elsif ($cur =~ /^($Ident)\s*\(/o) {
1937                         print "FUNC($1)\n" if ($dbg_values > 1);
1938                         $type = 'V';
1939                         $av_pending = 'V';
1940
1941                 } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1942                         if (defined $2 && $type eq 'C' || $type eq 'T') {
1943                                 $av_pend_colon = 'B';
1944                         } elsif ($type eq 'E') {
1945                                 $av_pend_colon = 'L';
1946                         }
1947                         print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1948                         $type = 'V';
1949
1950                 } elsif ($cur =~ /^($Ident|$Constant)/o) {
1951                         print "IDENT($1)\n" if ($dbg_values > 1);
1952                         $type = 'V';
1953
1954                 } elsif ($cur =~ /^($Assignment)/o) {
1955                         print "ASSIGN($1)\n" if ($dbg_values > 1);
1956                         $type = 'N';
1957
1958                 } elsif ($cur =~/^(;|{|})/) {
1959                         print "END($1)\n" if ($dbg_values > 1);
1960                         $type = 'E';
1961                         $av_pend_colon = 'O';
1962
1963                 } elsif ($cur =~/^(,)/) {
1964                         print "COMMA($1)\n" if ($dbg_values > 1);
1965                         $type = 'C';
1966
1967                 } elsif ($cur =~ /^(\?)/o) {
1968                         print "QUESTION($1)\n" if ($dbg_values > 1);
1969                         $type = 'N';
1970
1971                 } elsif ($cur =~ /^(:)/o) {
1972                         print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1973
1974                         substr($var, length($res), 1, $av_pend_colon);
1975                         if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1976                                 $type = 'E';
1977                         } else {
1978                                 $type = 'N';
1979                         }
1980                         $av_pend_colon = 'O';
1981
1982                 } elsif ($cur =~ /^(\[)/o) {
1983                         print "CLOSE($1)\n" if ($dbg_values > 1);
1984                         $type = 'N';
1985
1986                 } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1987                         my $variant;
1988
1989                         print "OPV($1)\n" if ($dbg_values > 1);
1990                         if ($type eq 'V') {
1991                                 $variant = 'B';
1992                         } else {
1993                                 $variant = 'U';
1994                         }
1995
1996                         substr($var, length($res), 1, $variant);
1997                         $type = 'N';
1998
1999                 } elsif ($cur =~ /^($Operators)/o) {
2000                         print "OP($1)\n" if ($dbg_values > 1);
2001                         if ($1 ne '++' && $1 ne '--') {
2002                                 $type = 'N';
2003                         }
2004
2005                 } elsif ($cur =~ /(^.)/o) {
2006                         print "C($1)\n" if ($dbg_values > 1);
2007                 }
2008                 if (defined $1) {
2009                         $cur = substr($cur, length($1));
2010                         $res .= $type x length($1);
2011                 }
2012         }
2013
2014         return ($res, $var);
2015 }
2016
2017 sub possible {
2018         my ($possible, $line) = @_;
2019         my $notPermitted = qr{(?:
2020                 ^(?:
2021                         $Modifier|
2022                         $Storage|
2023                         $Type|
2024                         DEFINE_\S+
2025                 )$|
2026                 ^(?:
2027                         goto|
2028                         return|
2029                         case|
2030                         else|
2031                         asm|__asm__|
2032                         do|
2033                         \#|
2034                         \#\#|
2035                 )(?:\s|$)|
2036                 ^(?:typedef|struct|enum)\b
2037             )}x;
2038         warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2039         if ($possible !~ $notPermitted) {
2040                 # Check for modifiers.
2041                 $possible =~ s/\s*$Storage\s*//g;
2042                 $possible =~ s/\s*$Sparse\s*//g;
2043                 if ($possible =~ /^\s*$/) {
2044
2045                 } elsif ($possible =~ /\s/) {
2046                         $possible =~ s/\s*$Type\s*//g;
2047                         for my $modifier (split(' ', $possible)) {
2048                                 if ($modifier !~ $notPermitted) {
2049                                         warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2050                                         push(@modifierListFile, $modifier);
2051                                 }
2052                         }
2053
2054                 } else {
2055                         warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2056                         push(@typeListFile, $possible);
2057                 }
2058                 build_types();
2059         } else {
2060                 warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2061         }
2062 }
2063
2064 my $prefix = '';
2065
2066 sub show_type {
2067         my ($type) = @_;
2068
2069         $type =~ tr/[a-z]/[A-Z]/;
2070
2071         return defined $use_type{$type} if (scalar keys %use_type > 0);
2072
2073         return !defined $ignore_type{$type};
2074 }
2075
2076 sub report {
2077         my ($level, $type, $msg) = @_;
2078
2079         if (!show_type($type) ||
2080             (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2081                 return 0;
2082         }
2083         my $output = '';
2084         if ($color) {
2085                 if ($level eq 'ERROR') {
2086                         $output .= RED;
2087                 } elsif ($level eq 'WARNING') {
2088                         $output .= YELLOW;
2089                 } else {
2090                         $output .= GREEN;
2091                 }
2092         }
2093         $output .= $prefix . $level . ':';
2094         if ($show_types) {
2095                 $output .= BLUE if ($color);
2096                 $output .= "$type:";
2097         }
2098         $output .= RESET if ($color);
2099         $output .= ' ' . $msg . "\n";
2100
2101         if ($showfile) {
2102                 my @lines = split("\n", $output, -1);
2103                 splice(@lines, 1, 1);
2104                 $output = join("\n", @lines);
2105         }
2106         $output = (split('\n', $output))[0] . "\n" if ($terse);
2107
2108         push(our @report, $output);
2109
2110         return 1;
2111 }
2112
2113 sub report_dump {
2114         our @report;
2115 }
2116
2117 sub fixup_current_range {
2118         my ($lineRef, $offset, $length) = @_;
2119
2120         if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2121                 my $o = $1;
2122                 my $l = $2;
2123                 my $no = $o + $offset;
2124                 my $nl = $l + $length;
2125                 $$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2126         }
2127 }
2128
2129 sub fix_inserted_deleted_lines {
2130         my ($linesRef, $insertedRef, $deletedRef) = @_;
2131
2132         my $range_last_linenr = 0;
2133         my $delta_offset = 0;
2134
2135         my $old_linenr = 0;
2136         my $new_linenr = 0;
2137
2138         my $next_insert = 0;
2139         my $next_delete = 0;
2140
2141         my @lines = ();
2142
2143         my $inserted = @{$insertedRef}[$next_insert++];
2144         my $deleted = @{$deletedRef}[$next_delete++];
2145
2146         foreach my $old_line (@{$linesRef}) {
2147                 my $save_line = 1;
2148                 my $line = $old_line;   #don't modify the array
2149                 if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) {      #new filename
2150                         $delta_offset = 0;
2151                 } elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) {    #new hunk
2152                         $range_last_linenr = $new_linenr;
2153                         fixup_current_range(\$line, $delta_offset, 0);
2154                 }
2155
2156                 while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2157                         $deleted = @{$deletedRef}[$next_delete++];
2158                         $save_line = 0;
2159                         fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2160                 }
2161
2162                 while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2163                         push(@lines, ${$inserted}{'LINE'});
2164                         $inserted = @{$insertedRef}[$next_insert++];
2165                         $new_linenr++;
2166                         fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2167                 }
2168
2169                 if ($save_line) {
2170                         push(@lines, $line);
2171                         $new_linenr++;
2172                 }
2173
2174                 $old_linenr++;
2175         }
2176
2177         return @lines;
2178 }
2179
2180 sub fix_insert_line {
2181         my ($linenr, $line) = @_;
2182
2183         my $inserted = {
2184                 LINENR => $linenr,
2185                 LINE => $line,
2186         };
2187         push(@fixed_inserted, $inserted);
2188 }
2189
2190 sub fix_delete_line {
2191         my ($linenr, $line) = @_;
2192
2193         my $deleted = {
2194                 LINENR => $linenr,
2195                 LINE => $line,
2196         };
2197
2198         push(@fixed_deleted, $deleted);
2199 }
2200
2201 sub ERROR {
2202         my ($type, $msg) = @_;
2203
2204         if (report("ERROR", $type, $msg)) {
2205                 our $clean = 0;
2206                 our $cnt_error++;
2207                 return 1;
2208         }
2209         return 0;
2210 }
2211 sub WARN {
2212         my ($type, $msg) = @_;
2213
2214         if (report("WARNING", $type, $msg)) {
2215                 our $clean = 0;
2216                 our $cnt_warn++;
2217                 return 1;
2218         }
2219         return 0;
2220 }
2221 sub CHK {
2222         my ($type, $msg) = @_;
2223
2224         if ($check && report("CHECK", $type, $msg)) {
2225                 our $clean = 0;
2226                 our $cnt_chk++;
2227                 return 1;
2228         }
2229         return 0;
2230 }
2231
2232 sub check_absolute_file {
2233         my ($absolute, $herecurr) = @_;
2234         my $file = $absolute;
2235
2236         ##print "absolute<$absolute>\n";
2237
2238         # See if any suffix of this path is a path within the tree.
2239         while ($file =~ s@^[^/]*/@@) {
2240                 if (-f "$root/$file") {
2241                         ##print "file<$file>\n";
2242                         last;
2243                 }
2244         }
2245         if (! -f _)  {
2246                 return 0;
2247         }
2248
2249         # It is, so see if the prefix is acceptable.
2250         my $prefix = $absolute;
2251         substr($prefix, -length($file)) = '';
2252
2253         ##print "prefix<$prefix>\n";
2254         if ($prefix ne ".../") {
2255                 WARN("USE_RELATIVE_PATH",
2256                      "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2257         }
2258 }
2259
2260 sub trim {
2261         my ($string) = @_;
2262
2263         $string =~ s/^\s+|\s+$//g;
2264
2265         return $string;
2266 }
2267
2268 sub ltrim {
2269         my ($string) = @_;
2270
2271         $string =~ s/^\s+//;
2272
2273         return $string;
2274 }
2275
2276 sub rtrim {
2277         my ($string) = @_;
2278
2279         $string =~ s/\s+$//;
2280
2281         return $string;
2282 }
2283
2284 sub string_find_replace {
2285         my ($string, $find, $replace) = @_;
2286
2287         $string =~ s/$find/$replace/g;
2288
2289         return $string;
2290 }
2291
2292 sub tabify {
2293         my ($leading) = @_;
2294
2295         my $source_indent = $tabsize;
2296         my $max_spaces_before_tab = $source_indent - 1;
2297         my $spaces_to_tab = " " x $source_indent;
2298
2299         #convert leading spaces to tabs
2300         1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2301         #Remove spaces before a tab
2302         1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2303
2304         return "$leading";
2305 }
2306
2307 sub pos_last_openparen {
2308         my ($line) = @_;
2309
2310         my $pos = 0;
2311
2312         my $opens = $line =~ tr/\(/\(/;
2313         my $closes = $line =~ tr/\)/\)/;
2314
2315         my $last_openparen = 0;
2316
2317         if (($opens == 0) || ($closes >= $opens)) {
2318                 return -1;
2319         }
2320
2321         my $len = length($line);
2322
2323         for ($pos = 0; $pos < $len; $pos++) {
2324                 my $string = substr($line, $pos);
2325                 if ($string =~ /^($FuncArg|$balanced_parens)/) {
2326                         $pos += length($1) - 1;
2327                 } elsif (substr($line, $pos, 1) eq '(') {
2328                         $last_openparen = $pos;
2329                 } elsif (index($string, '(') == -1) {
2330                         last;
2331                 }
2332         }
2333
2334         return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2335 }
2336
2337 sub get_raw_comment {
2338         my ($line, $rawline) = @_;
2339         my $comment = '';
2340
2341         for my $i (0 .. (length($line) - 1)) {
2342                 if (substr($line, $i, 1) eq "$;") {
2343                         $comment .= substr($rawline, $i, 1);
2344                 }
2345         }
2346
2347         return $comment;
2348 }
2349
2350 sub process {
2351         my $filename = shift;
2352
2353         my $linenr=0;
2354         my $prevline="";
2355         my $prevrawline="";
2356         my $stashline="";
2357         my $stashrawline="";
2358
2359         my $length;
2360         my $indent;
2361         my $previndent=0;
2362         my $stashindent=0;
2363
2364         our $clean = 1;
2365         my $signoff = 0;
2366         my $author = '';
2367         my $authorsignoff = 0;
2368         my $is_patch = 0;
2369         my $is_binding_patch = -1;
2370         my $in_header_lines = $file ? 0 : 1;
2371         my $in_commit_log = 0;          #Scanning lines before patch
2372         my $has_patch_separator = 0;    #Found a --- line
2373         my $has_commit_log = 0;         #Encountered lines before patch
2374         my $commit_log_lines = 0;       #Number of commit log lines
2375         my $commit_log_possible_stack_dump = 0;
2376         my $commit_log_long_line = 0;
2377         my $commit_log_has_diff = 0;
2378         my $reported_maintainer_file = 0;
2379         my $non_utf8_charset = 0;
2380
2381         my $last_blank_line = 0;
2382         my $last_coalesced_string_linenr = -1;
2383
2384         our @report = ();
2385         our $cnt_lines = 0;
2386         our $cnt_error = 0;
2387         our $cnt_warn = 0;
2388         our $cnt_chk = 0;
2389
2390         # Trace the real file/line as we go.
2391         my $realfile = '';
2392         my $realline = 0;
2393         my $realcnt = 0;
2394         my $here = '';
2395         my $context_function;           #undef'd unless there's a known function
2396         my $in_comment = 0;
2397         my $comment_edge = 0;
2398         my $first_line = 0;
2399         my $p1_prefix = '';
2400
2401         my $prev_values = 'E';
2402
2403         # suppression flags
2404         my %suppress_ifbraces;
2405         my %suppress_whiletrailers;
2406         my %suppress_export;
2407         my $suppress_statement = 0;
2408
2409         my %signatures = ();
2410
2411         # Pre-scan the patch sanitizing the lines.
2412         # Pre-scan the patch looking for any __setup documentation.
2413         #
2414         my @setup_docs = ();
2415         my $setup_docs = 0;
2416
2417         my $camelcase_file_seeded = 0;
2418
2419         my $checklicenseline = 1;
2420
2421         sanitise_line_reset();
2422         my $line;
2423         foreach my $rawline (@rawlines) {
2424                 $linenr++;
2425                 $line = $rawline;
2426
2427                 push(@fixed, $rawline) if ($fix);
2428
2429                 if ($rawline=~/^\+\+\+\s+(\S+)/) {
2430                         $setup_docs = 0;
2431                         if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2432                                 $setup_docs = 1;
2433                         }
2434                         #next;
2435                 }
2436                 if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2437                         $realline=$1-1;
2438                         if (defined $2) {
2439                                 $realcnt=$3+1;
2440                         } else {
2441                                 $realcnt=1+1;
2442                         }
2443                         $in_comment = 0;
2444
2445                         # Guestimate if this is a continuing comment.  Run
2446                         # the context looking for a comment "edge".  If this
2447                         # edge is a close comment then we must be in a comment
2448                         # at context start.
2449                         my $edge;
2450                         my $cnt = $realcnt;
2451                         for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2452                                 next if (defined $rawlines[$ln - 1] &&
2453                                          $rawlines[$ln - 1] =~ /^-/);
2454                                 $cnt--;
2455                                 #print "RAW<$rawlines[$ln - 1]>\n";
2456                                 last if (!defined $rawlines[$ln - 1]);
2457                                 if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2458                                     $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2459                                         ($edge) = $1;
2460                                         last;
2461                                 }
2462                         }
2463                         if (defined $edge && $edge eq '*/') {
2464                                 $in_comment = 1;
2465                         }
2466
2467                         # Guestimate if this is a continuing comment.  If this
2468                         # is the start of a diff block and this line starts
2469                         # ' *' then it is very likely a comment.
2470                         if (!defined $edge &&
2471                             $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2472                         {
2473                                 $in_comment = 1;
2474                         }
2475
2476                         ##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2477                         sanitise_line_reset($in_comment);
2478
2479                 } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2480                         # Standardise the strings and chars within the input to
2481                         # simplify matching -- only bother with positive lines.
2482                         $line = sanitise_line($rawline);
2483                 }
2484                 push(@lines, $line);
2485
2486                 if ($realcnt > 1) {
2487                         $realcnt-- if ($line =~ /^(?:\+| |$)/);
2488                 } else {
2489                         $realcnt = 0;
2490                 }
2491
2492                 #print "==>$rawline\n";
2493                 #print "-->$line\n";
2494
2495                 if ($setup_docs && $line =~ /^\+/) {
2496                         push(@setup_docs, $line);
2497                 }
2498         }
2499
2500         $prefix = '';
2501
2502         $realcnt = 0;
2503         $linenr = 0;
2504         $fixlinenr = -1;
2505         foreach my $line (@lines) {
2506                 $linenr++;
2507                 $fixlinenr++;
2508                 my $sline = $line;      #copy of $line
2509                 $sline =~ s/$;/ /g;     #with comments as spaces
2510
2511                 my $rawline = $rawlines[$linenr - 1];
2512                 my $raw_comment = get_raw_comment($line, $rawline);
2513
2514 # check if it's a mode change, rename or start of a patch
2515                 if (!$in_commit_log &&
2516                     ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2517                     ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2518                      $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2519                         $is_patch = 1;
2520                 }
2521
2522 #extract the line range in the file after the patch is applied
2523                 if (!$in_commit_log &&
2524                     $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2525                         my $context = $4;
2526                         $is_patch = 1;
2527                         $first_line = $linenr + 1;
2528                         $realline=$1-1;
2529                         if (defined $2) {
2530                                 $realcnt=$3+1;
2531                         } else {
2532                                 $realcnt=1+1;
2533                         }
2534                         annotate_reset();
2535                         $prev_values = 'E';
2536
2537                         %suppress_ifbraces = ();
2538                         %suppress_whiletrailers = ();
2539                         %suppress_export = ();
2540                         $suppress_statement = 0;
2541                         if ($context =~ /\b(\w+)\s*\(/) {
2542                                 $context_function = $1;
2543                         } else {
2544                                 undef $context_function;
2545                         }
2546                         next;
2547
2548 # track the line number as we move through the hunk, note that
2549 # new versions of GNU diff omit the leading space on completely
2550 # blank context lines so we need to count that too.
2551                 } elsif ($line =~ /^( |\+|$)/) {
2552                         $realline++;
2553                         $realcnt-- if ($realcnt != 0);
2554
2555                         # Measure the line length and indent.
2556                         ($length, $indent) = line_stats($rawline);
2557
2558                         # Track the previous line.
2559                         ($prevline, $stashline) = ($stashline, $line);
2560                         ($previndent, $stashindent) = ($stashindent, $indent);
2561                         ($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2562
2563                         #warn "line<$line>\n";
2564
2565                 } elsif ($realcnt == 1) {
2566                         $realcnt--;
2567                 }
2568
2569                 my $hunk_line = ($realcnt != 0);
2570
2571                 $here = "#$linenr: " if (!$file);
2572                 $here = "#$realline: " if ($file);
2573
2574                 my $found_file = 0;
2575                 # extract the filename as it passes
2576                 if ($line =~ /^diff --git.*?(\S+)$/) {
2577                         $realfile = $1;
2578                         $realfile =~ s@^([^/]*)/@@ if (!$file);
2579                         $in_commit_log = 0;
2580                         $found_file = 1;
2581                 } elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2582                         $realfile = $1;
2583                         $realfile =~ s@^([^/]*)/@@ if (!$file);
2584                         $in_commit_log = 0;
2585
2586                         $p1_prefix = $1;
2587                         if (!$file && $tree && $p1_prefix ne '' &&
2588                             -e "$root/$p1_prefix") {
2589                                 WARN("PATCH_PREFIX",
2590                                      "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2591                         }
2592
2593                         if ($realfile =~ m@^include/asm/@) {
2594                                 ERROR("MODIFIED_INCLUDE_ASM",
2595                                       "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2596                         }
2597                         $found_file = 1;
2598                 }
2599
2600 #make up the handle for any error we report on this line
2601                 if ($showfile) {
2602                         $prefix = "$realfile:$realline: "
2603                 } elsif ($emacs) {
2604                         if ($file) {
2605                                 $prefix = "$filename:$realline: ";
2606                         } else {
2607                                 $prefix = "$filename:$linenr: ";
2608                         }
2609                 }
2610
2611                 if ($found_file) {
2612                         if (is_maintained_obsolete($realfile)) {
2613                                 WARN("OBSOLETE",
2614                                      "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy.  No unnecessary modifications please.\n");
2615                         }
2616                         if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2617                                 $check = 1;
2618                         } else {
2619                                 $check = $check_orig;
2620                         }
2621                         $checklicenseline = 1;
2622
2623                         if ($realfile !~ /^MAINTAINERS/) {
2624                                 my $last_binding_patch = $is_binding_patch;
2625
2626                                 $is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2627
2628                                 if (($last_binding_patch != -1) &&
2629                                     ($last_binding_patch ^ $is_binding_patch)) {
2630                                         WARN("DT_SPLIT_BINDING_PATCH",
2631                                              "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2632                                 }
2633                         }
2634
2635                         next;
2636                 }
2637
2638                 $here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2639
2640                 my $hereline = "$here\n$rawline\n";
2641                 my $herecurr = "$here\n$rawline\n";
2642                 my $hereprev = "$here\n$prevrawline\n$rawline\n";
2643
2644                 $cnt_lines++ if ($realcnt != 0);
2645
2646 # Verify the existence of a commit log if appropriate
2647 # 2 is used because a $signature is counted in $commit_log_lines
2648                 if ($in_commit_log) {
2649                         if ($line !~ /^\s*$/) {
2650                                 $commit_log_lines++;    #could be a $signature
2651                         }
2652                 } elsif ($has_commit_log && $commit_log_lines < 2) {
2653                         WARN("COMMIT_MESSAGE",
2654                              "Missing commit description - Add an appropriate one\n");
2655                         $commit_log_lines = 2;  #warn only once
2656                 }
2657
2658 # Check if the commit log has what seems like a diff which can confuse patch
2659                 if ($in_commit_log && !$commit_log_has_diff &&
2660                     (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2661                       $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2662                      $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2663                      $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2664                         ERROR("DIFF_IN_COMMIT_MSG",
2665                               "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2666                         $commit_log_has_diff = 1;
2667                 }
2668
2669 # Check for incorrect file permissions
2670                 if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2671                         my $permhere = $here . "FILE: $realfile\n";
2672                         if ($realfile !~ m@scripts/@ &&
2673                             $realfile !~ /\.(py|pl|awk|sh)$/) {
2674                                 ERROR("EXECUTE_PERMISSIONS",
2675                                       "do not set execute permissions for source files\n" . $permhere);
2676                         }
2677                 }
2678
2679 # Check the patch for a From:
2680                 if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2681                         $author = $1;
2682                         my $curline = $linenr;
2683                         while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2684                                 $author .= $1;
2685                         }
2686                         $author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2687                         $author =~ s/"//g;
2688                         $author = reformat_email($author);
2689                 }
2690
2691 # Check the patch for a signoff:
2692                 if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2693                         $signoff++;
2694                         $in_commit_log = 0;
2695                         if ($author ne '') {
2696                                 if (same_email_addresses($1, $author)) {
2697                                         $authorsignoff = 1;
2698                                 }
2699                         }
2700                 }
2701
2702 # Check for patch separator
2703                 if ($line =~ /^---$/) {
2704                         $has_patch_separator = 1;
2705                         $in_commit_log = 0;
2706                 }
2707
2708 # Check if MAINTAINERS is being updated.  If so, there's probably no need to
2709 # emit the "does MAINTAINERS need updating?" message on file add/move/delete
2710                 if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2711                         $reported_maintainer_file = 1;
2712                 }
2713
2714 # Check signature styles
2715                 if (!$in_header_lines &&
2716                     $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2717                         my $space_before = $1;
2718                         my $sign_off = $2;
2719                         my $space_after = $3;
2720                         my $email = $4;
2721                         my $ucfirst_sign_off = ucfirst(lc($sign_off));
2722
2723                         if ($sign_off !~ /$signature_tags/) {
2724                                 WARN("BAD_SIGN_OFF",
2725                                      "Non-standard signature: $sign_off\n" . $herecurr);
2726                         }
2727                         if (defined $space_before && $space_before ne "") {
2728                                 if (WARN("BAD_SIGN_OFF",
2729                                          "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2730                                     $fix) {
2731                                         $fixed[$fixlinenr] =
2732                                             "$ucfirst_sign_off $email";
2733                                 }
2734                         }
2735                         if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2736                                 if (WARN("BAD_SIGN_OFF",
2737                                          "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2738                                     $fix) {
2739                                         $fixed[$fixlinenr] =
2740                                             "$ucfirst_sign_off $email";
2741                                 }
2742
2743                         }
2744                         if (!defined $space_after || $space_after ne " ") {
2745                                 if (WARN("BAD_SIGN_OFF",
2746                                          "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2747                                     $fix) {
2748                                         $fixed[$fixlinenr] =
2749                                             "$ucfirst_sign_off $email";
2750                                 }
2751                         }
2752
2753                         my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
2754                         my $suggested_email = format_email(($email_name, $email_address));
2755                         if ($suggested_email eq "") {
2756                                 ERROR("BAD_SIGN_OFF",
2757                                       "Unrecognized email address: '$email'\n" . $herecurr);
2758                         } else {
2759                                 my $dequoted = $suggested_email;
2760                                 $dequoted =~ s/^"//;
2761                                 $dequoted =~ s/" </ </;
2762                                 # Don't force email to have quotes
2763                                 # Allow just an angle bracketed address
2764                                 if (!same_email_addresses($email, $suggested_email)) {
2765                                         WARN("BAD_SIGN_OFF",
2766                                              "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2767                                 }
2768                         }
2769
2770 # Check for duplicate signatures
2771                         my $sig_nospace = $line;
2772                         $sig_nospace =~ s/\s//g;
2773                         $sig_nospace = lc($sig_nospace);
2774                         if (defined $signatures{$sig_nospace}) {
2775                                 WARN("BAD_SIGN_OFF",
2776                                      "Duplicate signature\n" . $herecurr);
2777                         } else {
2778                                 $signatures{$sig_nospace} = 1;
2779                         }
2780
2781 # Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
2782                         if ($sign_off =~ /^co-developed-by:$/i) {
2783                                 if ($email eq $author) {
2784                                         WARN("BAD_SIGN_OFF",
2785                                               "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
2786                                 }
2787                                 if (!defined $lines[$linenr]) {
2788                                         WARN("BAD_SIGN_OFF",
2789                                              "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
2790                                 } elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
2791                                         WARN("BAD_SIGN_OFF",
2792                                              "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2793                                 } elsif ($1 ne $email) {
2794                                         WARN("BAD_SIGN_OFF",
2795                                              "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2796                                 }
2797                         }
2798                 }
2799
2800 # Check email subject for common tools that don't need to be mentioned
2801                 if ($in_header_lines &&
2802                     $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2803                         WARN("EMAIL_SUBJECT",
2804                              "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2805                 }
2806
2807 # Check for Gerrit Change-Ids not in any patch context
2808                 if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
2809                         ERROR("GERRIT_CHANGE_ID",
2810                               "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr);
2811                 }
2812
2813 # Check if the commit log is in a possible stack dump
2814                 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2815                     ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2816                      $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2817                                         # timestamp
2818                      $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
2819                      $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
2820                      $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
2821                                         # stack dump address styles
2822                         $commit_log_possible_stack_dump = 1;
2823                 }
2824
2825 # Check for line lengths > 75 in commit log, warn once
2826                 if ($in_commit_log && !$commit_log_long_line &&
2827                     length($line) > 75 &&
2828                     !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2829                                         # file delta changes
2830                       $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2831                                         # filename then :
2832                       $line =~ /^\s*(?:Fixes:|Link:)/i ||
2833                                         # A Fixes: or Link: line
2834                       $commit_log_possible_stack_dump)) {
2835                         WARN("COMMIT_LOG_LONG_LINE",
2836                              "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2837                         $commit_log_long_line = 1;
2838                 }
2839
2840 # Reset possible stack dump if a blank line is found
2841                 if ($in_commit_log && $commit_log_possible_stack_dump &&
2842                     $line =~ /^\s*$/) {
2843                         $commit_log_possible_stack_dump = 0;
2844                 }
2845
2846 # Check for git id commit length and improperly formed commit descriptions
2847                 if ($in_commit_log && !$commit_log_possible_stack_dump &&
2848                     $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
2849                     $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2850                     ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2851                      ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2852                       $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2853                       $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2854                         my $init_char = "c";
2855                         my $orig_commit = "";
2856                         my $short = 1;
2857                         my $long = 0;
2858                         my $case = 1;
2859                         my $space = 1;
2860                         my $hasdesc = 0;
2861                         my $hasparens = 0;
2862                         my $id = '0123456789ab';
2863                         my $orig_desc = "commit description";
2864                         my $description = "";
2865
2866                         if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2867                                 $init_char = $1;
2868                                 $orig_commit = lc($2);
2869                         } elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2870                                 $orig_commit = lc($1);
2871                         }
2872
2873                         $short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2874                         $long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2875                         $space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2876                         $case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2877                         if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2878                                 $orig_desc = $1;
2879                                 $hasparens = 1;
2880                         } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2881                                  defined $rawlines[$linenr] &&
2882                                  $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2883                                 $orig_desc = $1;
2884                                 $hasparens = 1;
2885                         } elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2886                                  defined $rawlines[$linenr] &&
2887                                  $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2888                                 $line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2889                                 $orig_desc = $1;
2890                                 $rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2891                                 $orig_desc .= " " . $1;
2892                                 $hasparens = 1;
2893                         }
2894
2895                         ($id, $description) = git_commit_info($orig_commit,
2896                                                               $id, $orig_desc);
2897
2898                         if (defined($id) &&
2899                            ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2900                                 ERROR("GIT_COMMIT_ID",
2901                                       "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2902                         }
2903                 }
2904
2905 # Check for added, moved or deleted files
2906                 if (!$reported_maintainer_file && !$in_commit_log &&
2907                     ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2908                      $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2909                      ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2910                       (defined($1) || defined($2))))) {
2911                         $is_patch = 1;
2912                         $reported_maintainer_file = 1;
2913                         WARN("FILE_PATH_CHANGES",
2914                              "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2915                 }
2916
2917 # Check for adding new DT bindings not in schema format
2918                 if (!$in_commit_log &&
2919                     ($line =~ /^new file mode\s*\d+\s*$/) &&
2920                     ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
2921                         WARN("DT_SCHEMA_BINDING_PATCH",
2922                              "DT bindings should be in DT schema format. See: Documentation/devicetree/writing-schema.rst\n");
2923                 }
2924
2925 # Check for wrappage within a valid hunk of the file
2926                 if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2927                         ERROR("CORRUPTED_PATCH",
2928                               "patch seems to be corrupt (line wrapped?)\n" .
2929                                 $herecurr) if (!$emitted_corrupt++);
2930                 }
2931
2932 # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2933                 if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2934                     $rawline !~ m/^$UTF8*$/) {
2935                         my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2936
2937                         my $blank = copy_spacing($rawline);
2938                         my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2939                         my $hereptr = "$hereline$ptr\n";
2940
2941                         CHK("INVALID_UTF8",
2942                             "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2943                 }
2944
2945 # Check if it's the start of a commit log
2946 # (not a header line and we haven't seen the patch filename)
2947                 if ($in_header_lines && $realfile =~ /^$/ &&
2948                     !($rawline =~ /^\s+(?:\S|$)/ ||
2949                       $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2950                         $in_header_lines = 0;
2951                         $in_commit_log = 1;
2952                         $has_commit_log = 1;
2953                 }
2954
2955 # Check if there is UTF-8 in a commit log when a mail header has explicitly
2956 # declined it, i.e defined some charset where it is missing.
2957                 if ($in_header_lines &&
2958                     $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2959                     $1 !~ /utf-8/i) {
2960                         $non_utf8_charset = 1;
2961                 }
2962
2963                 if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2964                     $rawline =~ /$NON_ASCII_UTF8/) {
2965                         WARN("UTF8_BEFORE_PATCH",
2966                             "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2967                 }
2968
2969 # Check for absolute kernel paths in commit message
2970                 if ($tree && $in_commit_log) {
2971                         while ($line =~ m{(?:^|\s)(/\S*)}g) {
2972                                 my $file = $1;
2973
2974                                 if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2975                                     check_absolute_file($1, $herecurr)) {
2976                                         #
2977                                 } else {
2978                                         check_absolute_file($file, $herecurr);
2979                                 }
2980                         }
2981                 }
2982
2983 # Check for various typo / spelling mistakes
2984                 if (defined($misspellings) &&
2985                     ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2986                         while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2987                                 my $typo = $1;
2988                                 my $typo_fix = $spelling_fix{lc($typo)};
2989                                 $typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2990                                 $typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2991                                 my $msg_level = \&WARN;
2992                                 $msg_level = \&CHK if ($file);
2993                                 if (&{$msg_level}("TYPO_SPELLING",
2994                                                   "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2995                                     $fix) {
2996                                         $fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2997                                 }
2998                         }
2999                 }
3000
3001 # check for invalid commit id
3002                 if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3003                         my $id;
3004                         my $description;
3005                         ($id, $description) = git_commit_info($2, undef, undef);
3006                         if (!defined($id)) {
3007                                 WARN("UNKNOWN_COMMIT_ID",
3008                                      "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3009                         }
3010                 }
3011
3012 # check for repeated words separated by a single space
3013                 if ($rawline =~ /^\+/ || $in_commit_log) {
3014                         while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3015
3016                                 my $first = $1;
3017                                 my $second = $2;
3018
3019                                 if ($first =~ /(?:struct|union|enum)/) {
3020                                         pos($rawline) += length($first) + length($second) + 1;
3021                                         next;
3022                                 }
3023
3024                                 next if ($first ne $second);
3025                                 next if ($first eq 'long');
3026
3027                                 if (WARN("REPEATED_WORD",
3028                                          "Possible repeated word: '$first'\n" . $herecurr) &&
3029                                     $fix) {
3030                                         $fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3031                                 }
3032                         }
3033
3034                         # if it's a repeated word on consecutive lines in a comment block
3035                         if ($prevline =~ /$;+\s*$/ &&
3036                             $prevrawline =~ /($word_pattern)\s*$/) {
3037                                 my $last_word = $1;
3038                                 if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3039                                         if (WARN("REPEATED_WORD",
3040                                                  "Possible repeated word: '$last_word'\n" . $hereprev) &&
3041                                             $fix) {
3042                                                 $fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3043                                         }
3044                                 }
3045                         }
3046                 }
3047
3048 # ignore non-hunk lines and lines being removed
3049                 next if (!$hunk_line || $line =~ /^-/);
3050
3051 #trailing whitespace
3052                 if ($line =~ /^\+.*\015/) {
3053                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3054                         if (ERROR("DOS_LINE_ENDINGS",
3055                                   "DOS line endings\n" . $herevet) &&
3056                             $fix) {
3057                                 $fixed[$fixlinenr] =~ s/[\s\015]+$//;
3058                         }
3059                 } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3060                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3061                         if (ERROR("TRAILING_WHITESPACE",
3062                                   "trailing whitespace\n" . $herevet) &&
3063                             $fix) {
3064                                 $fixed[$fixlinenr] =~ s/\s+$//;
3065                         }
3066
3067                         $rpt_cleaners = 1;
3068                 }
3069
3070 # Check for FSF mailing addresses.
3071                 if ($rawline =~ /\bwrite to the Free/i ||
3072                     $rawline =~ /\b675\s+Mass\s+Ave/i ||
3073                     $rawline =~ /\b59\s+Temple\s+Pl/i ||
3074                     $rawline =~ /\b51\s+Franklin\s+St/i) {
3075                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3076                         my $msg_level = \&ERROR;
3077                         $msg_level = \&CHK if ($file);
3078                         &{$msg_level}("FSF_MAILING_ADDRESS",
3079                                       "Do not include the paragraph about writing to the Free Software Foundation's mailing address from the sample GPL notice. The FSF has changed addresses in the past, and may do so again. Linux already includes a copy of the GPL.\n" . $herevet)
3080                 }
3081
3082 # check for Kconfig help text having a real description
3083 # Only applies when adding the entry originally, after that we do not have
3084 # sufficient context to determine whether it is indeed long enough.
3085                 if ($realfile =~ /Kconfig/ &&
3086                     # 'choice' is usually the last thing on the line (though
3087                     # Kconfig supports named choices), so use a word boundary
3088                     # (\b) rather than a whitespace character (\s)
3089                     $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3090                         my $length = 0;
3091                         my $cnt = $realcnt;
3092                         my $ln = $linenr + 1;
3093                         my $f;
3094                         my $is_start = 0;
3095                         my $is_end = 0;
3096                         for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
3097                                 $f = $lines[$ln - 1];
3098                                 $cnt-- if ($lines[$ln - 1] !~ /^-/);
3099                                 $is_end = $lines[$ln - 1] =~ /^\+/;
3100
3101                                 next if ($f =~ /^-/);
3102                                 last if (!$file && $f =~ /^\@\@/);
3103
3104                                 if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3105                                         $is_start = 1;
3106                                 } elsif ($lines[$ln - 1] =~ /^\+\s*(?:---)?help(?:---)?$/) {
3107                                         $length = -1;
3108                                 }
3109
3110                                 $f =~ s/^.//;
3111                                 $f =~ s/#.*//;
3112                                 $f =~ s/^\s+//;
3113                                 next if ($f =~ /^$/);
3114
3115                                 # This only checks context lines in the patch
3116                                 # and so hopefully shouldn't trigger false
3117                                 # positives, even though some of these are
3118                                 # common words in help texts
3119                                 if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3120                                                   if|endif|menu|endmenu|source)\b/x) {
3121                                         $is_end = 1;
3122                                         last;
3123                                 }
3124                                 $length++;
3125                         }
3126                         if ($is_start && $is_end && $length < $min_conf_desc_length) {
3127                                 WARN("CONFIG_DESCRIPTION",
3128                                      "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3129                         }
3130                         #print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3131                 }
3132
3133 # check MAINTAINERS entries
3134                 if ($realfile =~ /^MAINTAINERS$/) {
3135 # check MAINTAINERS entries for the right form
3136                         if ($rawline =~ /^\+[A-Z]:/ &&
3137                             $rawline !~ /^\+[A-Z]:\t\S/) {
3138                                 if (WARN("MAINTAINERS_STYLE",
3139                                          "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3140                                     $fix) {
3141                                         $fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3142                                 }
3143                         }
3144 # check MAINTAINERS entries for the right ordering too
3145                         my $preferred_order = 'MRLSWQBCPTFXNK';
3146                         if ($rawline =~ /^\+[A-Z]:/ &&
3147                             $prevrawline =~ /^[\+ ][A-Z]:/) {
3148                                 $rawline =~ /^\+([A-Z]):\s*(.*)/;
3149                                 my $cur = $1;
3150                                 my $curval = $2;
3151                                 $prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3152                                 my $prev = $1;
3153                                 my $prevval = $2;
3154                                 my $curindex = index($preferred_order, $cur);
3155                                 my $previndex = index($preferred_order, $prev);
3156                                 if ($curindex < 0) {
3157                                         WARN("MAINTAINERS_STYLE",
3158                                              "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3159                                 } else {
3160                                         if ($previndex >= 0 && $curindex < $previndex) {
3161                                                 WARN("MAINTAINERS_STYLE",
3162                                                      "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3163                                         } elsif ((($prev eq 'F' && $cur eq 'F') ||
3164                                                   ($prev eq 'X' && $cur eq 'X')) &&
3165                                                  ($prevval cmp $curval) > 0) {
3166                                                 WARN("MAINTAINERS_STYLE",
3167                                                      "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3168                                         }
3169                                 }
3170                         }
3171                 }
3172
3173 # discourage the use of boolean for type definition attributes of Kconfig options
3174                 if ($realfile =~ /Kconfig/ &&
3175                     $line =~ /^\+\s*\bboolean\b/) {
3176                         WARN("CONFIG_TYPE_BOOLEAN",
3177                              "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
3178                 }
3179
3180                 if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3181                     ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3182                         my $flag = $1;
3183                         my $replacement = {
3184                                 'EXTRA_AFLAGS' =>   'asflags-y',
3185                                 'EXTRA_CFLAGS' =>   'ccflags-y',
3186                                 'EXTRA_CPPFLAGS' => 'cppflags-y',
3187                                 'EXTRA_LDFLAGS' =>  'ldflags-y',
3188                         };
3189
3190                         WARN("DEPRECATED_VARIABLE",
3191                              "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3192                 }
3193
3194 # check for DT compatible documentation
3195                 if (defined $root &&
3196                         (($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3197                          ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3198
3199                         my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3200
3201                         my $dt_path = $root . "/Documentation/devicetree/bindings/";
3202                         my $vp_file = $dt_path . "vendor-prefixes.yaml";
3203
3204                         foreach my $compat (@compats) {
3205                                 my $compat2 = $compat;
3206                                 $compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3207                                 my $compat3 = $compat;
3208                                 $compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3209                                 `grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3210                                 if ( $? >> 8 ) {
3211                                         WARN("UNDOCUMENTED_DT_STRING",
3212                                              "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3213                                 }
3214
3215                                 next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3216                                 my $vendor = $1;
3217                                 `grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3218                                 if ( $? >> 8 ) {
3219                                         WARN("UNDOCUMENTED_DT_STRING",
3220                                              "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3221                                 }
3222                         }
3223                 }
3224
3225 # check for using SPDX license tag at beginning of files
3226                 if ($realline == $checklicenseline) {
3227                         if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3228                                 $checklicenseline = 2;
3229                         } elsif ($rawline =~ /^\+/) {
3230                                 my $comment = "";
3231                                 if ($realfile =~ /\.(h|s|S)$/) {
3232                                         $comment = '/*';
3233                                 } elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3234                                         $comment = '//';
3235                                 } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3236                                         $comment = '#';
3237                                 } elsif ($realfile =~ /\.rst$/) {
3238                                         $comment = '..';
3239                                 }
3240
3241 # check SPDX comment style for .[chsS] files
3242                                 if ($realfile =~ /\.[chsS]$/ &&
3243                                     $rawline =~ /SPDX-License-Identifier:/ &&
3244                                     $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3245                                         WARN("SPDX_LICENSE_TAG",
3246                                              "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3247                                 }
3248
3249                                 if ($comment !~ /^$/ &&
3250                                     $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3251                                         WARN("SPDX_LICENSE_TAG",
3252                                              "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3253                                 } elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3254                                         my $spdx_license = $1;
3255                                         if (!is_SPDX_License_valid($spdx_license)) {
3256                                                 WARN("SPDX_LICENSE_TAG",
3257                                                      "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3258                                         }
3259                                         if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3260                                             not $spdx_license =~ /GPL-2\.0.*BSD-2-Clause/) {
3261                                                 my $msg_level = \&WARN;
3262                                                 $msg_level = \&CHK if ($file);
3263                                                 if (&{$msg_level}("SPDX_LICENSE_TAG",
3264
3265                                                                   "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3266                                                     $fix) {
3267                                                         $fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3268                                                 }
3269                                         }
3270                                 }
3271                         }
3272                 }
3273
3274 # check for embedded filenames
3275                 if ($rawline =~ /^\+.*\Q$realfile\E/) {
3276                         WARN("EMBEDDED_FILENAME",
3277                              "It's generally not useful to have the filename in the file\n" . $herecurr);
3278                 }
3279
3280 # check we are in a valid source file if not then ignore this hunk
3281                 next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3282
3283 # check for using SPDX-License-Identifier on the wrong line number
3284                 if ($realline != $checklicenseline &&
3285                     $rawline =~ /\bSPDX-License-Identifier:/ &&
3286                     substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3287                         WARN("SPDX_LICENSE_TAG",
3288                              "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3289                 }
3290
3291 # line length limit (with some exclusions)
3292 #
3293 # There are a few types of lines that may extend beyond $max_line_length:
3294 #       logging functions like pr_info that end in a string
3295 #       lines with a single string
3296 #       #defines that are a single string
3297 #       lines with an RFC3986 like URL
3298 #
3299 # There are 3 different line length message types:
3300 # LONG_LINE_COMMENT     a comment starts before but extends beyond $max_line_length
3301 # LONG_LINE_STRING      a string starts before but extends beyond $max_line_length
3302 # LONG_LINE             all other lines longer than $max_line_length
3303 #
3304 # if LONG_LINE is ignored, the other 2 types are also ignored
3305 #
3306
3307                 if ($line =~ /^\+/ && $length > $max_line_length) {
3308                         my $msg_type = "LONG_LINE";
3309
3310                         # Check the allowed long line types first
3311
3312                         # logging functions that end in a string that starts
3313                         # before $max_line_length
3314                         if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3315                             length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3316                                 $msg_type = "";
3317
3318                         # lines with only strings (w/ possible termination)
3319                         # #defines with only strings
3320                         } elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3321                                  $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3322                                 $msg_type = "";
3323
3324                         # More special cases
3325                         } elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3326                                  $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3327                                 $msg_type = "";
3328
3329                         # URL ($rawline is used in case the URL is in a comment)
3330                         } elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3331                                 $msg_type = "";
3332
3333                         # Otherwise set the alternate message types
3334
3335                         # a comment starts before $max_line_length
3336                         } elsif ($line =~ /($;[\s$;]*)$/ &&
3337                                  length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3338                                 $msg_type = "LONG_LINE_COMMENT"
3339
3340                         # a quoted string starts before $max_line_length
3341                         } elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3342                                  length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3343                                 $msg_type = "LONG_LINE_STRING"
3344                         }
3345
3346                         if ($msg_type ne "" &&
3347                             (show_type("LONG_LINE") || show_type($msg_type))) {
3348                                 my $msg_level = \&WARN;
3349                                 $msg_level = \&CHK if ($file);
3350                                 &{$msg_level}($msg_type,
3351                                               "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3352                         }
3353                 }
3354
3355 # check for adding lines without a newline.
3356                 if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3357                         WARN("MISSING_EOF_NEWLINE",
3358                              "adding a line without newline at end of file\n" . $herecurr);
3359                 }
3360
3361 # check we are in a valid source file C or perl if not then ignore this hunk
3362                 next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3363
3364 # at the beginning of a line any tabs must come first and anything
3365 # more than $tabsize must use tabs.
3366                 if ($rawline =~ /^\+\s* \t\s*\S/ ||
3367                     $rawline =~ /^\+\s*        \s*/) {
3368                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3369                         $rpt_cleaners = 1;
3370                         if (ERROR("CODE_INDENT",
3371                                   "code indent should use tabs where possible\n" . $herevet) &&
3372                             $fix) {
3373                                 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3374                         }
3375                 }
3376
3377 # check for space before tabs.
3378                 if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3379                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3380                         if (WARN("SPACE_BEFORE_TAB",
3381                                 "please, no space before tabs\n" . $herevet) &&
3382                             $fix) {
3383                                 while ($fixed[$fixlinenr] =~
3384                                            s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3385                                 while ($fixed[$fixlinenr] =~
3386                                            s/(^\+.*) +\t/$1\t/) {}
3387                         }
3388                 }
3389
3390 # check for assignments on the start of a line
3391                 if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3392                         CHK("ASSIGNMENT_CONTINUATIONS",
3393                             "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3394                 }
3395
3396 # check for && or || at the start of a line
3397                 if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3398                         CHK("LOGICAL_CONTINUATIONS",
3399                             "Logical continuations should be on the previous line\n" . $hereprev);
3400                 }
3401
3402 # check indentation starts on a tab stop
3403                 if ($perl_version_ok &&
3404                     $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3405                         my $indent = length($1);
3406                         if ($indent % $tabsize) {
3407                                 if (WARN("TABSTOP",
3408                                          "Statements should start on a tabstop\n" . $herecurr) &&
3409                                     $fix) {
3410                                         $fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3411                                 }
3412                         }
3413                 }
3414
3415 # check multi-line statement indentation matches previous line
3416                 if ($perl_version_ok &&
3417                     $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3418                         $prevline =~ /^\+(\t*)(.*)$/;
3419                         my $oldindent = $1;
3420                         my $rest = $2;
3421
3422                         my $pos = pos_last_openparen($rest);
3423                         if ($pos >= 0) {
3424                                 $line =~ /^(\+| )([ \t]*)/;
3425                                 my $newindent = $2;
3426
3427                                 my $goodtabindent = $oldindent .
3428                                         "\t" x ($pos / $tabsize) .
3429                                         " "  x ($pos % $tabsize);
3430                                 my $goodspaceindent = $oldindent . " "  x $pos;
3431
3432                                 if ($newindent ne $goodtabindent &&
3433                                     $newindent ne $goodspaceindent) {
3434
3435                                         if (CHK("PARENTHESIS_ALIGNMENT",
3436                                                 "Alignment should match open parenthesis\n" . $hereprev) &&
3437                                             $fix && $line =~ /^\+/) {
3438                                                 $fixed[$fixlinenr] =~
3439                                                     s/^\+[ \t]*/\+$goodtabindent/;
3440                                         }
3441                                 }
3442                         }
3443                 }
3444
3445 # check for space after cast like "(int) foo" or "(struct foo) bar"
3446 # avoid checking a few false positives:
3447 #   "sizeof(<type>)" or "__alignof__(<type>)"
3448 #   function pointer declarations like "(*foo)(int) = bar;"
3449 #   structure definitions like "(struct foo) { 0 };"
3450 #   multiline macros that define functions
3451 #   known attributes or the __attribute__ keyword
3452                 if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3453                     (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3454                         if (CHK("SPACING",
3455                                 "No space is necessary after a cast\n" . $herecurr) &&
3456                             $fix) {
3457                                 $fixed[$fixlinenr] =~
3458                                     s/(\(\s*$Type\s*\))[ \t]+/$1/;
3459                         }
3460                 }
3461
3462 # Block comment styles
3463 # Networking with an initial /*
3464                 if ($realfile =~ m@^(drivers/net/|net/)@ &&
3465                     $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3466                     $rawline =~ /^\+[ \t]*\*/ &&
3467                     $realline > 3) { # Do not warn about the initial copyright comment block after SPDX-License-Identifier
3468                         WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3469                              "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3470                 }
3471
3472 # Block comments use * on subsequent lines
3473                 if ($prevline =~ /$;[ \t]*$/ &&                 #ends in comment
3474                     $prevrawline =~ /^\+.*?\/\*/ &&             #starting /*
3475                     $prevrawline !~ /\*\/[ \t]*$/ &&            #no trailing */
3476                     $rawline =~ /^\+/ &&                        #line is new
3477                     $rawline !~ /^\+[ \t]*\*/) {                #no leading *
3478                         WARN("BLOCK_COMMENT_STYLE",
3479                              "Block comments use * on subsequent lines\n" . $hereprev);
3480                 }
3481
3482 # Block comments use */ on trailing lines
3483                 if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&       #trailing */
3484                     $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&      #inline /*...*/
3485                     $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&       #trailing **/
3486                     $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {    #non blank */
3487                         WARN("BLOCK_COMMENT_STYLE",
3488                              "Block comments use a trailing */ on a separate line\n" . $herecurr);
3489                 }
3490
3491 # Block comment * alignment
3492                 if ($prevline =~ /$;[ \t]*$/ &&                 #ends in comment
3493                     $line =~ /^\+[ \t]*$;/ &&                   #leading comment
3494                     $rawline =~ /^\+[ \t]*\*/ &&                #leading *
3495                     (($prevrawline =~ /^\+.*?\/\*/ &&           #leading /*
3496                       $prevrawline !~ /\*\/[ \t]*$/) ||         #no trailing */
3497                      $prevrawline =~ /^\+[ \t]*\*/)) {          #leading *
3498                         my $oldindent;
3499                         $prevrawline =~ m@^\+([ \t]*/?)\*@;
3500                         if (defined($1)) {
3501                                 $oldindent = expand_tabs($1);
3502                         } else {
3503                                 $prevrawline =~ m@^\+(.*/?)\*@;
3504                                 $oldindent = expand_tabs($1);
3505                         }
3506                         $rawline =~ m@^\+([ \t]*)\*@;
3507                         my $newindent = $1;
3508                         $newindent = expand_tabs($newindent);
3509                         if (length($oldindent) ne length($newindent)) {
3510                                 WARN("BLOCK_COMMENT_STYLE",
3511                                      "Block comments should align the * on each line\n" . $hereprev);
3512                         }
3513                 }
3514
3515 # check for missing blank lines after struct/union declarations
3516 # with exceptions for various attributes and macros
3517                 if ($prevline =~ /^[\+ ]};?\s*$/ &&
3518                     $line =~ /^\+/ &&
3519                     !($line =~ /^\+\s*$/ ||
3520                       $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3521                       $line =~ /^\+\s*MODULE_/i ||
3522                       $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3523                       $line =~ /^\+[a-z_]*init/ ||
3524                       $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3525                       $line =~ /^\+\s*DECLARE/ ||
3526                       $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3527                       $line =~ /^\+\s*__setup/)) {
3528                         if (CHK("LINE_SPACING",
3529                                 "Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3530                             $fix) {
3531                                 fix_insert_line($fixlinenr, "\+");
3532                         }
3533                 }
3534
3535 # check for multiple consecutive blank lines
3536                 if ($prevline =~ /^[\+ ]\s*$/ &&
3537                     $line =~ /^\+\s*$/ &&
3538                     $last_blank_line != ($linenr - 1)) {
3539                         if (CHK("LINE_SPACING",
3540                                 "Please don't use multiple blank lines\n" . $hereprev) &&
3541                             $fix) {
3542                                 fix_delete_line($fixlinenr, $rawline);
3543                         }
3544
3545                         $last_blank_line = $linenr;
3546                 }
3547
3548 # check for missing blank lines after declarations
3549                 if ($sline =~ /^\+\s+\S/ &&                     #Not at char 1
3550                         # actual declarations
3551                     ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3552                         # function pointer declarations
3553                      $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3554                         # foo bar; where foo is some local typedef or #define
3555                      $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3556                         # known declaration macros
3557                      $prevline =~ /^\+\s+$declaration_macros/) &&
3558                         # for "else if" which can look like "$Ident $Ident"
3559                     !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3560                         # other possible extensions of declaration lines
3561                       $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3562                         # not starting a section or a macro "\" extended line
3563                       $prevline =~ /(?:\{\s*|\\)$/) &&
3564                         # looks like a declaration
3565                     !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3566                         # function pointer declarations
3567                       $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3568                         # foo bar; where foo is some local typedef or #define
3569                       $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3570                         # known declaration macros
3571                       $sline =~ /^\+\s+$declaration_macros/ ||
3572                         # start of struct or union or enum
3573                       $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3574                         # start or end of block or continuation of declaration
3575                       $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3576                         # bitfield continuation
3577                       $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3578                         # other possible extensions of declaration lines
3579                       $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3580                         # indentation of previous and current line are the same
3581                     (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3582                         if (WARN("LINE_SPACING",
3583                                  "Missing a blank line after declarations\n" . $hereprev) &&
3584                             $fix) {
3585                                 fix_insert_line($fixlinenr, "\+");
3586                         }
3587                 }
3588
3589 # check for spaces at the beginning of a line.
3590 # Exceptions:
3591 #  1) within comments
3592 #  2) indented preprocessor commands
3593 #  3) hanging labels
3594                 if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/)  {
3595                         my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3596                         if (WARN("LEADING_SPACE",
3597                                  "please, no spaces at the start of a line\n" . $herevet) &&
3598                             $fix) {
3599                                 $fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3600                         }
3601                 }
3602
3603 # check we are in a valid C source file if not then ignore this hunk
3604                 next if ($realfile !~ /\.(h|c)$/);
3605
3606 # check for unusual line ending [ or (
3607                 if ($line =~ /^\+.*([\[\(])\s*$/) {
3608                         CHK("OPEN_ENDED_LINE",
3609                             "Lines should not end with a '$1'\n" . $herecurr);
3610                 }
3611
3612 # check if this appears to be the start function declaration, save the name
3613                 if ($sline =~ /^\+\{\s*$/ &&
3614                     $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3615                         $context_function = $1;
3616                 }
3617
3618 # check if this appears to be the end of function declaration
3619                 if ($sline =~ /^\+\}\s*$/) {
3620                         undef $context_function;
3621                 }
3622
3623 # check indentation of any line with a bare else
3624 # (but not if it is a multiple line "if (foo) return bar; else return baz;")
3625 # if the previous line is a break or return and is indented 1 tab more...
3626                 if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3627                         my $tabs = length($1) + 1;
3628                         if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3629                             ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3630                              defined $lines[$linenr] &&
3631                              $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3632                                 WARN("UNNECESSARY_ELSE",
3633                                      "else is not generally useful after a break or return\n" . $hereprev);
3634                         }
3635                 }
3636
3637 # check indentation of a line with a break;
3638 # if the previous line is a goto or return and is indented the same # of tabs
3639                 if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3640                         my $tabs = $1;
3641                         if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3642                                 WARN("UNNECESSARY_BREAK",
3643                                      "break is not useful after a goto or return\n" . $hereprev);
3644                         }
3645                 }
3646
3647 # check for RCS/CVS revision markers
3648                 if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3649                         WARN("CVS_KEYWORD",
3650                              "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3651                 }
3652
3653 # check for old HOTPLUG __dev<foo> section markings
3654                 if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3655                         WARN("HOTPLUG_SECTION",
3656                              "Using $1 is unnecessary\n" . $herecurr);
3657                 }
3658
3659 # Check for potential 'bare' types
3660                 my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3661                     $realline_next);
3662 #print "LINE<$line>\n";
3663                 if ($linenr > $suppress_statement &&
3664                     $realcnt && $sline =~ /.\s*\S/) {
3665                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3666                                 ctx_statement_block($linenr, $realcnt, 0);
3667                         $stat =~ s/\n./\n /g;
3668                         $cond =~ s/\n./\n /g;
3669
3670 #print "linenr<$linenr> <$stat>\n";
3671                         # If this statement has no statement boundaries within
3672                         # it there is no point in retrying a statement scan
3673                         # until we hit end of it.
3674                         my $frag = $stat; $frag =~ s/;+\s*$//;
3675                         if ($frag !~ /(?:{|;)/) {
3676 #print "skip<$line_nr_next>\n";
3677                                 $suppress_statement = $line_nr_next;
3678                         }
3679
3680                         # Find the real next line.
3681                         $realline_next = $line_nr_next;
3682                         if (defined $realline_next &&
3683                             (!defined $lines[$realline_next - 1] ||
3684                              substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3685                                 $realline_next++;
3686                         }
3687
3688                         my $s = $stat;
3689                         $s =~ s/{.*$//s;
3690
3691                         # Ignore goto labels.
3692                         if ($s =~ /$Ident:\*$/s) {
3693
3694                         # Ignore functions being called
3695                         } elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3696
3697                         } elsif ($s =~ /^.\s*else\b/s) {
3698
3699                         # declarations always start with types
3700                         } elsif ($prev_values eq 'E' && $s =~ /^.\s*(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?((?:\s*$Ident)+?)\b(?:\s+$Sparse)?\s*\**\s*(?:$Ident|\(\*[^\)]*\))(?:\s*$Modifier)?\s*(?:;|=|,|\()/s) {
3701                                 my $type = $1;
3702                                 $type =~ s/\s+/ /g;
3703                                 possible($type, "A:" . $s);
3704
3705                         # definitions in global scope can only start with types
3706                         } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3707                                 possible($1, "B:" . $s);
3708                         }
3709
3710                         # any (foo ... *) is a pointer cast, and foo is a type
3711                         while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3712                                 possible($1, "C:" . $s);
3713                         }
3714
3715                         # Check for any sort of function declaration.
3716                         # int foo(something bar, other baz);
3717                         # void (*store_gdt)(x86_descr_ptr *);
3718                         if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3719                                 my ($name_len) = length($1);
3720
3721                                 my $ctx = $s;
3722                                 substr($ctx, 0, $name_len + 1, '');
3723                                 $ctx =~ s/\)[^\)]*$//;
3724
3725                                 for my $arg (split(/\s*,\s*/, $ctx)) {
3726                                         if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3727
3728                                                 possible($1, "D:" . $s);
3729                                         }
3730                                 }
3731                         }
3732
3733                 }
3734
3735 #
3736 # Checks which may be anchored in the context.
3737 #
3738
3739 # Check for switch () and associated case and default
3740 # statements should be at the same indent.
3741                 if ($line=~/\bswitch\s*\(.*\)/) {
3742                         my $err = '';
3743                         my $sep = '';
3744                         my @ctx = ctx_block_outer($linenr, $realcnt);
3745                         shift(@ctx);
3746                         for my $ctx (@ctx) {
3747                                 my ($clen, $cindent) = line_stats($ctx);
3748                                 if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3749                                                         $indent != $cindent) {
3750                                         $err .= "$sep$ctx\n";
3751                                         $sep = '';
3752                                 } else {
3753                                         $sep = "[...]\n";
3754                                 }
3755                         }
3756                         if ($err ne '') {
3757                                 ERROR("SWITCH_CASE_INDENT_LEVEL",
3758                                       "switch and case should be at the same indent\n$hereline$err");
3759                         }
3760                 }
3761
3762 # if/while/etc brace do not go on next line, unless defining a do while loop,
3763 # or if that brace on the next line is for something else
3764                 if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3765                         my $pre_ctx = "$1$2";
3766
3767                         my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3768
3769                         if ($line =~ /^\+\t{6,}/) {
3770                                 WARN("DEEP_INDENTATION",
3771                                      "Too many leading tabs - consider code refactoring\n" . $herecurr);
3772                         }
3773
3774                         my $ctx_cnt = $realcnt - $#ctx - 1;
3775                         my $ctx = join("\n", @ctx);
3776
3777                         my $ctx_ln = $linenr;
3778                         my $ctx_skip = $realcnt;
3779
3780                         while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3781                                         defined $lines[$ctx_ln - 1] &&
3782                                         $lines[$ctx_ln - 1] =~ /^-/)) {
3783                                 ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3784                                 $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3785                                 $ctx_ln++;
3786                         }
3787
3788                         #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3789                         #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3790
3791                         if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3792                                 ERROR("OPEN_BRACE",
3793                                       "that open brace { should be on the previous line\n" .
3794                                         "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3795                         }
3796                         if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3797                             $ctx =~ /\)\s*\;\s*$/ &&
3798                             defined $lines[$ctx_ln - 1])
3799                         {
3800                                 my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3801                                 if ($nindent > $indent) {
3802                                         WARN("TRAILING_SEMICOLON",
3803                                              "trailing semicolon indicates no statements, indent implies otherwise\n" .
3804                                                 "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3805                                 }
3806                         }
3807                 }
3808
3809 # Check relative indent for conditionals and blocks.
3810                 if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3811                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3812                                 ctx_statement_block($linenr, $realcnt, 0)
3813                                         if (!defined $stat);
3814                         my ($s, $c) = ($stat, $cond);
3815
3816                         substr($s, 0, length($c), '');
3817
3818                         # remove inline comments
3819                         $s =~ s/$;/ /g;
3820                         $c =~ s/$;/ /g;
3821
3822                         # Find out how long the conditional actually is.
3823                         my @newlines = ($c =~ /\n/gs);
3824                         my $cond_lines = 1 + $#newlines;
3825
3826                         # Make sure we remove the line prefixes as we have
3827                         # none on the first line, and are going to readd them
3828                         # where necessary.
3829                         $s =~ s/\n./\n/gs;
3830                         while ($s =~ /\n\s+\\\n/) {
3831                                 $cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3832                         }
3833
3834                         # We want to check the first line inside the block
3835                         # starting at the end of the conditional, so remove:
3836                         #  1) any blank line termination
3837                         #  2) any opening brace { on end of the line
3838                         #  3) any do (...) {
3839                         my $continuation = 0;
3840                         my $check = 0;
3841                         $s =~ s/^.*\bdo\b//;
3842                         $s =~ s/^\s*{//;
3843                         if ($s =~ s/^\s*\\//) {
3844                                 $continuation = 1;
3845                         }
3846                         if ($s =~ s/^\s*?\n//) {
3847                                 $check = 1;
3848                                 $cond_lines++;
3849                         }
3850
3851                         # Also ignore a loop construct at the end of a
3852                         # preprocessor statement.
3853                         if (($prevline =~ /^.\s*#\s*define\s/ ||
3854                             $prevline =~ /\\\s*$/) && $continuation == 0) {
3855                                 $check = 0;
3856                         }
3857
3858                         my $cond_ptr = -1;
3859                         $continuation = 0;
3860                         while ($cond_ptr != $cond_lines) {
3861                                 $cond_ptr = $cond_lines;
3862
3863                                 # If we see an #else/#elif then the code
3864                                 # is not linear.
3865                                 if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3866                                         $check = 0;
3867                                 }
3868
3869                                 # Ignore:
3870                                 #  1) blank lines, they should be at 0,
3871                                 #  2) preprocessor lines, and
3872                                 #  3) labels.
3873                                 if ($continuation ||
3874                                     $s =~ /^\s*?\n/ ||
3875                                     $s =~ /^\s*#\s*?/ ||
3876                                     $s =~ /^\s*$Ident\s*:/) {
3877                                         $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3878                                         if ($s =~ s/^.*?\n//) {
3879                                                 $cond_lines++;
3880                                         }
3881                                 }
3882                         }
3883
3884                         my (undef, $sindent) = line_stats("+" . $s);
3885                         my $stat_real = raw_line($linenr, $cond_lines);
3886
3887                         # Check if either of these lines are modified, else
3888                         # this is not this patch's fault.
3889                         if (!defined($stat_real) ||
3890                             $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3891                                 $check = 0;
3892                         }
3893                         if (defined($stat_real) && $cond_lines > 1) {
3894                                 $stat_real = "[...]\n$stat_real";
3895                         }
3896
3897                         #print "line<$line> prevline<$prevline> indent<$indent> sindent<$sindent> check<$check> continuation<$continuation> s<$s> cond_lines<$cond_lines> stat_real<$stat_real> stat<$stat>\n";
3898
3899                         if ($check && $s ne '' &&
3900                             (($sindent % $tabsize) != 0 ||
3901                              ($sindent < $indent) ||
3902                              ($sindent == $indent &&
3903                               ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3904                              ($sindent > $indent + $tabsize))) {
3905                                 WARN("SUSPECT_CODE_INDENT",
3906                                      "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3907                         }
3908                 }
3909
3910                 # Track the 'values' across context and added lines.
3911                 my $opline = $line; $opline =~ s/^./ /;
3912                 my ($curr_values, $curr_vars) =
3913                                 annotate_values($opline . "\n", $prev_values);
3914                 $curr_values = $prev_values . $curr_values;
3915                 if ($dbg_values) {
3916                         my $outline = $opline; $outline =~ s/\t/ /g;
3917                         print "$linenr > .$outline\n";
3918                         print "$linenr > $curr_values\n";
3919                         print "$linenr >  $curr_vars\n";
3920                 }
3921                 $prev_values = substr($curr_values, -1);
3922
3923 #ignore lines not being added
3924                 next if ($line =~ /^[^\+]/);
3925
3926 # check for self assignments used to avoid compiler warnings
3927 # e.g.: int foo = foo, *bar = NULL;
3928 #       struct foo bar = *(&(bar));
3929                 if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
3930                         my $var = $1;
3931                         if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
3932                                 WARN("SELF_ASSIGNMENT",
3933                                      "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
3934                         }
3935                 }
3936
3937 # check for dereferences that span multiple lines
3938                 if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3939                     $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3940                         $prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3941                         my $ref = $1;
3942                         $line =~ /^.\s*($Lval)/;
3943                         $ref .= $1;
3944                         $ref =~ s/\s//g;
3945                         WARN("MULTILINE_DEREFERENCE",
3946                              "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3947                 }
3948
3949 # check for declarations of signed or unsigned without int
3950                 while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3951                         my $type = $1;
3952                         my $var = $2;
3953                         $var = "" if (!defined $var);
3954                         if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3955                                 my $sign = $1;
3956                                 my $pointer = $2;
3957
3958                                 $pointer = "" if (!defined $pointer);
3959
3960                                 if (WARN("UNSPECIFIED_INT",
3961                                          "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3962                                     $fix) {
3963                                         my $decl = trim($sign) . " int ";
3964                                         my $comp_pointer = $pointer;
3965                                         $comp_pointer =~ s/\s//g;
3966                                         $decl .= $comp_pointer;
3967                                         $decl = rtrim($decl) if ($var eq "");
3968                                         $fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3969                                 }
3970                         }
3971                 }
3972
3973 # TEST: allow direct testing of the type matcher.
3974                 if ($dbg_type) {
3975                         if ($line =~ /^.\s*$Declare\s*$/) {
3976                                 ERROR("TEST_TYPE",
3977                                       "TEST: is type\n" . $herecurr);
3978                         } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3979                                 ERROR("TEST_NOT_TYPE",
3980                                       "TEST: is not type ($1 is)\n". $herecurr);
3981                         }
3982                         next;
3983                 }
3984 # TEST: allow direct testing of the attribute matcher.
3985                 if ($dbg_attr) {
3986                         if ($line =~ /^.\s*$Modifier\s*$/) {
3987                                 ERROR("TEST_ATTR",
3988                                       "TEST: is attr\n" . $herecurr);
3989                         } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3990                                 ERROR("TEST_NOT_ATTR",
3991                                       "TEST: is not attr ($1 is)\n". $herecurr);
3992                         }
3993                         next;
3994                 }
3995
3996 # check for initialisation to aggregates open brace on the next line
3997                 if ($line =~ /^.\s*{/ &&
3998                     $prevline =~ /(?:^|[^=])=\s*$/) {
3999                         if (ERROR("OPEN_BRACE",
4000                                   "that open brace { should be on the previous line\n" . $hereprev) &&
4001                             $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4002                                 fix_delete_line($fixlinenr - 1, $prevrawline);
4003                                 fix_delete_line($fixlinenr, $rawline);
4004                                 my $fixedline = $prevrawline;
4005                                 $fixedline =~ s/\s*=\s*$/ = {/;
4006                                 fix_insert_line($fixlinenr, $fixedline);
4007                                 $fixedline = $line;
4008                                 $fixedline =~ s/^(.\s*)\{\s*/$1/;
4009                                 fix_insert_line($fixlinenr, $fixedline);
4010                         }
4011                 }
4012
4013 #
4014 # Checks which are anchored on the added line.
4015 #
4016
4017 # check for malformed paths in #include statements (uses RAW line)
4018                 if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4019                         my $path = $1;
4020                         if ($path =~ m{//}) {
4021                                 ERROR("MALFORMED_INCLUDE",
4022                                       "malformed #include filename\n" . $herecurr);
4023                         }
4024                         if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4025                                 ERROR("UAPI_INCLUDE",
4026                                       "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4027                         }
4028                 }
4029
4030 # no C99 // comments
4031                 if ($line =~ m{//}) {
4032                         if (ERROR("C99_COMMENTS",
4033                                   "do not use C99 // comments\n" . $herecurr) &&
4034                             $fix) {
4035                                 my $line = $fixed[$fixlinenr];
4036                                 if ($line =~ /\/\/(.*)$/) {
4037                                         my $comment = trim($1);
4038                                         $fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4039                                 }
4040                         }
4041                 }
4042                 # Remove C99 comments.
4043                 $line =~ s@//.*@@;
4044                 $opline =~ s@//.*@@;
4045
4046 # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4047 # the whole statement.
4048 #print "APW <$lines[$realline_next - 1]>\n";
4049                 if (defined $realline_next &&
4050                     exists $lines[$realline_next - 1] &&
4051                     !defined $suppress_export{$realline_next} &&
4052                     ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4053                      $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4054                         # Handle definitions which produce identifiers with
4055                         # a prefix:
4056                         #   XXX(foo);
4057                         #   EXPORT_SYMBOL(something_foo);
4058                         my $name = $1;
4059                         if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4060                             $name =~ /^${Ident}_$2/) {
4061 #print "FOO C name<$name>\n";
4062                                 $suppress_export{$realline_next} = 1;
4063
4064                         } elsif ($stat !~ /(?:
4065                                 \n.}\s*$|
4066                                 ^.DEFINE_$Ident\(\Q$name\E\)|
4067                                 ^.DECLARE_$Ident\(\Q$name\E\)|
4068                                 ^.LIST_HEAD\(\Q$name\E\)|
4069                                 ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4070                                 \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4071                             )/x) {
4072 #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4073                                 $suppress_export{$realline_next} = 2;
4074                         } else {
4075                                 $suppress_export{$realline_next} = 1;
4076                         }
4077                 }
4078                 if (!defined $suppress_export{$linenr} &&
4079                     $prevline =~ /^.\s*$/ &&
4080                     ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
4081                      $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
4082 #print "FOO B <$lines[$linenr - 1]>\n";
4083                         $suppress_export{$linenr} = 2;
4084                 }
4085                 if (defined $suppress_export{$linenr} &&
4086                     $suppress_export{$linenr} == 2) {
4087                         WARN("EXPORT_SYMBOL",
4088                              "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4089                 }
4090
4091 # check for global initialisers.
4092                 if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
4093                         if (ERROR("GLOBAL_INITIALISERS",
4094                                   "do not initialise globals to $1\n" . $herecurr) &&
4095                             $fix) {
4096                                 $fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4097                         }
4098                 }
4099 # check for static initialisers.
4100                 if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4101                         if (ERROR("INITIALISED_STATIC",
4102                                   "do not initialise statics to $1\n" .
4103                                       $herecurr) &&
4104                             $fix) {
4105                                 $fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4106                         }
4107                 }
4108
4109 # check for misordered declarations of char/short/int/long with signed/unsigned
4110                 while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4111                         my $tmp = trim($1);
4112                         WARN("MISORDERED_TYPE",
4113                              "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4114                 }
4115
4116 # check for unnecessary <signed> int declarations of short/long/long long
4117                 while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4118                         my $type = trim($1);
4119                         next if ($type !~ /\bint\b/);
4120                         next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4121                         my $new_type = $type;
4122                         $new_type =~ s/\b\s*int\s*\b/ /;
4123                         $new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4124                         $new_type =~ s/^const\s+//;
4125                         $new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4126                         $new_type = "const $new_type" if ($type =~ /^const\b/);
4127                         $new_type =~ s/\s+/ /g;
4128                         $new_type = trim($new_type);
4129                         if (WARN("UNNECESSARY_INT",
4130                                  "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4131                             $fix) {
4132                                 $fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4133                         }
4134                 }
4135
4136 # check for static const char * arrays.
4137                 if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4138                         WARN("STATIC_CONST_CHAR_ARRAY",
4139                              "static const char * array should probably be static const char * const\n" .
4140                                 $herecurr);
4141                 }
4142
4143 # check for initialized const char arrays that should be static const
4144                 if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4145                         if (WARN("STATIC_CONST_CHAR_ARRAY",
4146                                  "const array should probably be static const\n" . $herecurr) &&
4147                             $fix) {
4148                                 $fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4149                         }
4150                 }
4151
4152 # check for static char foo[] = "bar" declarations.
4153                 if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4154                         WARN("STATIC_CONST_CHAR_ARRAY",
4155                              "static char array declaration should probably be static const char\n" .
4156                                 $herecurr);
4157                 }
4158
4159 # check for const <foo> const where <foo> is not a pointer or array type
4160                 if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4161                         my $found = $1;
4162                         if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4163                                 WARN("CONST_CONST",
4164                                      "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4165                         } elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4166                                 WARN("CONST_CONST",
4167                                      "'const $found const' should probably be 'const $found'\n" . $herecurr);
4168                         }
4169                 }
4170
4171 # check for non-global char *foo[] = {"bar", ...} declarations.
4172                 if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4173                         WARN("STATIC_CONST_CHAR_ARRAY",
4174                              "char * array declaration might be better as static const\n" .
4175                                 $herecurr);
4176                }
4177
4178 # check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4179                 if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4180                         my $array = $1;
4181                         if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4182                                 my $array_div = $1;
4183                                 if (WARN("ARRAY_SIZE",
4184                                          "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4185                                     $fix) {
4186                                         $fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4187                                 }
4188                         }
4189                 }
4190
4191 # check for function declarations without arguments like "int foo()"
4192                 if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4193                         if (ERROR("FUNCTION_WITHOUT_ARGS",
4194                                   "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4195                             $fix) {
4196                                 $fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4197                         }
4198                 }
4199
4200 # check for new typedefs, only function parameters and sparse annotations
4201 # make sense.
4202                 if ($line =~ /\btypedef\s/ &&
4203                     $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4204                     $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4205                     $line !~ /\b$typeTypedefs\b/ &&
4206                     $line !~ /\b__bitwise\b/) {
4207                         WARN("NEW_TYPEDEFS",
4208                              "do not add new typedefs\n" . $herecurr);
4209                 }
4210
4211 # * goes on variable not on type
4212                 # (char*[ const])
4213                 while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4214                         #print "AA<$1>\n";
4215                         my ($ident, $from, $to) = ($1, $2, $2);
4216
4217                         # Should start with a space.
4218                         $to =~ s/^(\S)/ $1/;
4219                         # Should not end with a space.
4220                         $to =~ s/\s+$//;
4221                         # '*'s should not have spaces between.
4222                         while ($to =~ s/\*\s+\*/\*\*/) {
4223                         }
4224
4225 ##                      print "1: from<$from> to<$to> ident<$ident>\n";
4226                         if ($from ne $to) {
4227                                 if (ERROR("POINTER_LOCATION",
4228                                           "\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr) &&
4229                                     $fix) {
4230                                         my $sub_from = $ident;
4231                                         my $sub_to = $ident;
4232                                         $sub_to =~ s/\Q$from\E/$to/;
4233                                         $fixed[$fixlinenr] =~
4234                                             s@\Q$sub_from\E@$sub_to@;
4235                                 }
4236                         }
4237                 }
4238                 while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4239                         #print "BB<$1>\n";
4240                         my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4241
4242                         # Should start with a space.
4243                         $to =~ s/^(\S)/ $1/;
4244                         # Should not end with a space.
4245                         $to =~ s/\s+$//;
4246                         # '*'s should not have spaces between.
4247                         while ($to =~ s/\*\s+\*/\*\*/) {
4248                         }
4249                         # Modifiers should have spaces.
4250                         $to =~ s/(\b$Modifier$)/$1 /;
4251
4252 ##                      print "2: from<$from> to<$to> ident<$ident>\n";
4253                         if ($from ne $to && $ident !~ /^$Modifier$/) {
4254                                 if (ERROR("POINTER_LOCATION",
4255                                           "\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr) &&
4256                                     $fix) {
4257
4258                                         my $sub_from = $match;
4259                                         my $sub_to = $match;
4260                                         $sub_to =~ s/\Q$from\E/$to/;
4261                                         $fixed[$fixlinenr] =~
4262                                             s@\Q$sub_from\E@$sub_to@;
4263                                 }
4264                         }
4265                 }
4266
4267 # avoid BUG() or BUG_ON()
4268                 if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4269                         my $msg_level = \&WARN;
4270                         $msg_level = \&CHK if ($file);
4271                         &{$msg_level}("AVOID_BUG",
4272                                       "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4273                 }
4274
4275 # avoid LINUX_VERSION_CODE
4276                 if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4277                         WARN("LINUX_VERSION_CODE",
4278                              "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4279                 }
4280
4281 # check for uses of printk_ratelimit
4282                 if ($line =~ /\bprintk_ratelimit\s*\(/) {
4283                         WARN("PRINTK_RATELIMITED",
4284                              "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4285                 }
4286
4287 # printk should use KERN_* levels
4288                 if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4289                         WARN("PRINTK_WITHOUT_KERN_LEVEL",
4290                              "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4291                 }
4292
4293                 if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4294                         my $orig = $1;
4295                         my $level = lc($orig);
4296                         $level = "warn" if ($level eq "warning");
4297                         my $level2 = $level;
4298                         $level2 = "dbg" if ($level eq "debug");
4299                         WARN("PREFER_PR_LEVEL",
4300                              "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(...  to printk(KERN_$orig ...\n" . $herecurr);
4301                 }
4302
4303                 if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4304                         my $orig = $1;
4305                         my $level = lc($orig);
4306                         $level = "warn" if ($level eq "warning");
4307                         $level = "dbg" if ($level eq "debug");
4308                         WARN("PREFER_DEV_LEVEL",
4309                              "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4310                 }
4311
4312 # trace_printk should not be used in production code.
4313                 if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4314                         WARN("TRACE_PRINTK",
4315                              "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4316                 }
4317
4318 # ENOSYS means "bad syscall nr" and nothing else.  This will have a small
4319 # number of false positives, but assembly files are not checked, so at
4320 # least the arch entry code will not trigger this warning.
4321                 if ($line =~ /\bENOSYS\b/) {
4322                         WARN("ENOSYS",
4323                              "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4324                 }
4325
4326 # ENOTSUPP is not a standard error code and should be avoided in new patches.
4327 # Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4328 # Similarly to ENOSYS warning a small number of false positives is expected.
4329                 if (!$file && $line =~ /\bENOTSUPP\b/) {
4330                         if (WARN("ENOTSUPP",
4331                                  "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4332                             $fix) {
4333                                 $fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4334                         }
4335                 }
4336
4337 # function brace can't be on same line, except for #defines of do while,
4338 # or if closed on same line
4339                 if ($perl_version_ok &&
4340                     $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4341                     $sline !~ /\#\s*define\b.*do\s*\{/ &&
4342                     $sline !~ /}/) {
4343                         if (ERROR("OPEN_BRACE",
4344                                   "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4345                             $fix) {
4346                                 fix_delete_line($fixlinenr, $rawline);
4347                                 my $fixed_line = $rawline;
4348                                 $fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4349                                 my $line1 = $1;
4350                                 my $line2 = $2;
4351                                 fix_insert_line($fixlinenr, ltrim($line1));
4352                                 fix_insert_line($fixlinenr, "\+{");
4353                                 if ($line2 !~ /^\s*$/) {
4354                                         fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4355                                 }
4356                         }
4357                 }
4358
4359 # open braces for enum, union and struct go on the same line.
4360                 if ($line =~ /^.\s*{/ &&
4361                     $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4362                         if (ERROR("OPEN_BRACE",
4363                                   "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4364                             $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4365                                 fix_delete_line($fixlinenr - 1, $prevrawline);
4366                                 fix_delete_line($fixlinenr, $rawline);
4367                                 my $fixedline = rtrim($prevrawline) . " {";
4368                                 fix_insert_line($fixlinenr, $fixedline);
4369                                 $fixedline = $rawline;
4370                                 $fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4371                                 if ($fixedline !~ /^\+\s*$/) {
4372                                         fix_insert_line($fixlinenr, $fixedline);
4373                                 }
4374                         }
4375                 }
4376
4377 # missing space after union, struct or enum definition
4378                 if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4379                         if (WARN("SPACING",
4380                                  "missing space after $1 definition\n" . $herecurr) &&
4381                             $fix) {
4382                                 $fixed[$fixlinenr] =~
4383                                     s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4384                         }
4385                 }
4386
4387 # Function pointer declarations
4388 # check spacing between type, funcptr, and args
4389 # canonical declaration is "type (*funcptr)(args...)"
4390                 if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4391                         my $declare = $1;
4392                         my $pre_pointer_space = $2;
4393                         my $post_pointer_space = $3;
4394                         my $funcname = $4;
4395                         my $post_funcname_space = $5;
4396                         my $pre_args_space = $6;
4397
4398 # the $Declare variable will capture all spaces after the type
4399 # so check it for a missing trailing missing space but pointer return types
4400 # don't need a space so don't warn for those.
4401                         my $post_declare_space = "";
4402                         if ($declare =~ /(\s+)$/) {
4403                                 $post_declare_space = $1;
4404                                 $declare = rtrim($declare);
4405                         }
4406                         if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4407                                 WARN("SPACING",
4408                                      "missing space after return type\n" . $herecurr);
4409                                 $post_declare_space = " ";
4410                         }
4411
4412 # unnecessary space "type  (*funcptr)(args...)"
4413 # This test is not currently implemented because these declarations are
4414 # equivalent to
4415 #       int  foo(int bar, ...)
4416 # and this is form shouldn't/doesn't generate a checkpatch warning.
4417 #
4418 #                       elsif ($declare =~ /\s{2,}$/) {
4419 #                               WARN("SPACING",
4420 #                                    "Multiple spaces after return type\n" . $herecurr);
4421 #                       }
4422
4423 # unnecessary space "type ( *funcptr)(args...)"
4424                         if (defined $pre_pointer_space &&
4425                             $pre_pointer_space =~ /^\s/) {
4426                                 WARN("SPACING",
4427                                      "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4428                         }
4429
4430 # unnecessary space "type (* funcptr)(args...)"
4431                         if (defined $post_pointer_space &&
4432                             $post_pointer_space =~ /^\s/) {
4433                                 WARN("SPACING",
4434                                      "Unnecessary space before function pointer name\n" . $herecurr);
4435                         }
4436
4437 # unnecessary space "type (*funcptr )(args...)"
4438                         if (defined $post_funcname_space &&
4439                             $post_funcname_space =~ /^\s/) {
4440                                 WARN("SPACING",
4441                                      "Unnecessary space after function pointer name\n" . $herecurr);
4442                         }
4443
4444 # unnecessary space "type (*funcptr) (args...)"
4445                         if (defined $pre_args_space &&
4446                             $pre_args_space =~ /^\s/) {
4447                                 WARN("SPACING",
4448                                      "Unnecessary space before function pointer arguments\n" . $herecurr);
4449                         }
4450
4451                         if (show_type("SPACING") && $fix) {
4452                                 $fixed[$fixlinenr] =~
4453                                     s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4454                         }
4455                 }
4456
4457 # check for spacing round square brackets; allowed:
4458 #  1. with a type on the left -- int [] a;
4459 #  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4460 #  3. inside a curly brace -- = { [0...10] = 5 }
4461                 while ($line =~ /(.*?\s)\[/g) {
4462                         my ($where, $prefix) = ($-[1], $1);
4463                         if ($prefix !~ /$Type\s+$/ &&
4464                             ($where != 0 || $prefix !~ /^.\s+$/) &&
4465                             $prefix !~ /[{,:]\s+$/) {
4466                                 if (ERROR("BRACKET_SPACE",
4467                                           "space prohibited before open square bracket '['\n" . $herecurr) &&
4468                                     $fix) {
4469                                     $fixed[$fixlinenr] =~
4470                                         s/^(\+.*?)\s+\[/$1\[/;
4471                                 }
4472                         }
4473                 }
4474
4475 # check for spaces between functions and their parentheses.
4476                 while ($line =~ /($Ident)\s+\(/g) {
4477                         my $name = $1;
4478                         my $ctx_before = substr($line, 0, $-[1]);
4479                         my $ctx = "$ctx_before$name";
4480
4481                         # Ignore those directives where spaces _are_ permitted.
4482                         if ($name =~ /^(?:
4483                                 if|for|while|switch|return|case|
4484                                 volatile|__volatile__|
4485                                 __attribute__|format|__extension__|
4486                                 asm|__asm__)$/x)
4487                         {
4488                         # cpp #define statements have non-optional spaces, ie
4489                         # if there is a space between the name and the open
4490                         # parenthesis it is simply not a parameter group.
4491                         } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4492
4493                         # cpp #elif statement condition may start with a (
4494                         } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4495
4496                         # If this whole things ends with a type its most
4497                         # likely a typedef for a function.
4498                         } elsif ($ctx =~ /$Type$/) {
4499
4500                         } else {
4501                                 if (WARN("SPACING",
4502                                          "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4503                                              $fix) {
4504                                         $fixed[$fixlinenr] =~
4505                                             s/\b$name\s+\(/$name\(/;
4506                                 }
4507                         }
4508                 }
4509
4510 # Check operator spacing.
4511                 if (!($line=~/\#\s*include/)) {
4512                         my $fixed_line = "";
4513                         my $line_fixed = 0;
4514
4515                         my $ops = qr{
4516                                 <<=|>>=|<=|>=|==|!=|
4517                                 \+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4518                                 =>|->|<<|>>|<|>|=|!|~|
4519                                 &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4520                                 \?:|\?|:
4521                         }x;
4522                         my @elements = split(/($ops|;)/, $opline);
4523
4524 ##                      print("element count: <" . $#elements . ">\n");
4525 ##                      foreach my $el (@elements) {
4526 ##                              print("el: <$el>\n");
4527 ##                      }
4528
4529                         my @fix_elements = ();
4530                         my $off = 0;
4531
4532                         foreach my $el (@elements) {
4533                                 push(@fix_elements, substr($rawline, $off, length($el)));
4534                                 $off += length($el);
4535                         }
4536
4537                         $off = 0;
4538
4539                         my $blank = copy_spacing($opline);
4540                         my $last_after = -1;
4541
4542                         for (my $n = 0; $n < $#elements; $n += 2) {
4543
4544                                 my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4545
4546 ##                              print("n: <$n> good: <$good>\n");
4547
4548                                 $off += length($elements[$n]);
4549
4550                                 # Pick up the preceding and succeeding characters.
4551                                 my $ca = substr($opline, 0, $off);
4552                                 my $cc = '';
4553                                 if (length($opline) >= ($off + length($elements[$n + 1]))) {
4554                                         $cc = substr($opline, $off + length($elements[$n + 1]));
4555                                 }
4556                                 my $cb = "$ca$;$cc";
4557
4558                                 my $a = '';
4559                                 $a = 'V' if ($elements[$n] ne '');
4560                                 $a = 'W' if ($elements[$n] =~ /\s$/);
4561                                 $a = 'C' if ($elements[$n] =~ /$;$/);
4562                                 $a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4563                                 $a = 'O' if ($elements[$n] eq '');
4564                                 $a = 'E' if ($ca =~ /^\s*$/);
4565
4566                                 my $op = $elements[$n + 1];
4567
4568                                 my $c = '';
4569                                 if (defined $elements[$n + 2]) {
4570                                         $c = 'V' if ($elements[$n + 2] ne '');
4571                                         $c = 'W' if ($elements[$n + 2] =~ /^\s/);
4572                                         $c = 'C' if ($elements[$n + 2] =~ /^$;/);
4573                                         $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4574                                         $c = 'O' if ($elements[$n + 2] eq '');
4575                                         $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4576                                 } else {
4577                                         $c = 'E';
4578                                 }
4579
4580                                 my $ctx = "${a}x${c}";
4581
4582                                 my $at = "(ctx:$ctx)";
4583
4584                                 my $ptr = substr($blank, 0, $off) . "^";
4585                                 my $hereptr = "$hereline$ptr\n";
4586
4587                                 # Pull out the value of this operator.
4588                                 my $op_type = substr($curr_values, $off + 1, 1);
4589
4590                                 # Get the full operator variant.
4591                                 my $opv = $op . substr($curr_vars, $off, 1);
4592
4593                                 # Ignore operators passed as parameters.
4594                                 if ($op_type ne 'V' &&
4595                                     $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4596
4597 #                               # Ignore comments
4598 #                               } elsif ($op =~ /^$;+$/) {
4599
4600                                 # ; should have either the end of line or a space or \ after it
4601                                 } elsif ($op eq ';') {
4602                                         if ($ctx !~ /.x[WEBC]/ &&
4603                                             $cc !~ /^\\/ && $cc !~ /^;/) {
4604                                                 if (ERROR("SPACING",
4605                                                           "space required after that '$op' $at\n" . $hereptr)) {
4606                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4607                                                         $line_fixed = 1;
4608                                                 }
4609                                         }
4610
4611                                 # // is a comment
4612                                 } elsif ($op eq '//') {
4613
4614                                 #   :   when part of a bitfield
4615                                 } elsif ($opv eq ':B') {
4616                                         # skip the bitfield test for now
4617
4618                                 # No spaces for:
4619                                 #   ->
4620                                 } elsif ($op eq '->') {
4621                                         if ($ctx =~ /Wx.|.xW/) {
4622                                                 if (ERROR("SPACING",
4623                                                           "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4624                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4625                                                         if (defined $fix_elements[$n + 2]) {
4626                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4627                                                         }
4628                                                         $line_fixed = 1;
4629                                                 }
4630                                         }
4631
4632                                 # , must not have a space before and must have a space on the right.
4633                                 } elsif ($op eq ',') {
4634                                         my $rtrim_before = 0;
4635                                         my $space_after = 0;
4636                                         if ($ctx =~ /Wx./) {
4637                                                 if (ERROR("SPACING",
4638                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
4639                                                         $line_fixed = 1;
4640                                                         $rtrim_before = 1;
4641                                                 }
4642                                         }
4643                                         if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4644                                                 if (ERROR("SPACING",
4645                                                           "space required after that '$op' $at\n" . $hereptr)) {
4646                                                         $line_fixed = 1;
4647                                                         $last_after = $n;
4648                                                         $space_after = 1;
4649                                                 }
4650                                         }
4651                                         if ($rtrim_before || $space_after) {
4652                                                 if ($rtrim_before) {
4653                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4654                                                 } else {
4655                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4656                                                 }
4657                                                 if ($space_after) {
4658                                                         $good .= " ";
4659                                                 }
4660                                         }
4661
4662                                 # '*' as part of a type definition -- reported already.
4663                                 } elsif ($opv eq '*_') {
4664                                         #warn "'*' is part of type\n";
4665
4666                                 # unary operators should have a space before and
4667                                 # none after.  May be left adjacent to another
4668                                 # unary operator, or a cast
4669                                 } elsif ($op eq '!' || $op eq '~' ||
4670                                          $opv eq '*U' || $opv eq '-U' ||
4671                                          $opv eq '&U' || $opv eq '&&U') {
4672                                         if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4673                                                 if (ERROR("SPACING",
4674                                                           "space required before that '$op' $at\n" . $hereptr)) {
4675                                                         if ($n != $last_after + 2) {
4676                                                                 $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4677                                                                 $line_fixed = 1;
4678                                                         }
4679                                                 }
4680                                         }
4681                                         if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4682                                                 # A unary '*' may be const
4683
4684                                         } elsif ($ctx =~ /.xW/) {
4685                                                 if (ERROR("SPACING",
4686                                                           "space prohibited after that '$op' $at\n" . $hereptr)) {
4687                                                         $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4688                                                         if (defined $fix_elements[$n + 2]) {
4689                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4690                                                         }
4691                                                         $line_fixed = 1;
4692                                                 }
4693                                         }
4694
4695                                 # unary ++ and unary -- are allowed no space on one side.
4696                                 } elsif ($op eq '++' or $op eq '--') {
4697                                         if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4698                                                 if (ERROR("SPACING",
4699                                                           "space required one side of that '$op' $at\n" . $hereptr)) {
4700                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4701                                                         $line_fixed = 1;
4702                                                 }
4703                                         }
4704                                         if ($ctx =~ /Wx[BE]/ ||
4705                                             ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4706                                                 if (ERROR("SPACING",
4707                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
4708                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4709                                                         $line_fixed = 1;
4710                                                 }
4711                                         }
4712                                         if ($ctx =~ /ExW/) {
4713                                                 if (ERROR("SPACING",
4714                                                           "space prohibited after that '$op' $at\n" . $hereptr)) {
4715                                                         $good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4716                                                         if (defined $fix_elements[$n + 2]) {
4717                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4718                                                         }
4719                                                         $line_fixed = 1;
4720                                                 }
4721                                         }
4722
4723                                 # << and >> may either have or not have spaces both sides
4724                                 } elsif ($op eq '<<' or $op eq '>>' or
4725                                          $op eq '&' or $op eq '^' or $op eq '|' or
4726                                          $op eq '+' or $op eq '-' or
4727                                          $op eq '*' or $op eq '/' or
4728                                          $op eq '%')
4729                                 {
4730                                         if ($check) {
4731                                                 if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4732                                                         if (CHK("SPACING",
4733                                                                 "spaces preferred around that '$op' $at\n" . $hereptr)) {
4734                                                                 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4735                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4736                                                                 $line_fixed = 1;
4737                                                         }
4738                                                 } elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4739                                                         if (CHK("SPACING",
4740                                                                 "space preferred before that '$op' $at\n" . $hereptr)) {
4741                                                                 $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4742                                                                 $line_fixed = 1;
4743                                                         }
4744                                                 }
4745                                         } elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4746                                                 if (ERROR("SPACING",
4747                                                           "need consistent spacing around '$op' $at\n" . $hereptr)) {
4748                                                         $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4749                                                         if (defined $fix_elements[$n + 2]) {
4750                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4751                                                         }
4752                                                         $line_fixed = 1;
4753                                                 }
4754                                         }
4755
4756                                 # A colon needs no spaces before when it is
4757                                 # terminating a case value or a label.
4758                                 } elsif ($opv eq ':C' || $opv eq ':L') {
4759                                         if ($ctx =~ /Wx./) {
4760                                                 if (ERROR("SPACING",
4761                                                           "space prohibited before that '$op' $at\n" . $hereptr)) {
4762                                                         $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4763                                                         $line_fixed = 1;
4764                                                 }
4765                                         }
4766
4767                                 # All the others need spaces both sides.
4768                                 } elsif ($ctx !~ /[EWC]x[CWE]/) {
4769                                         my $ok = 0;
4770
4771                                         # Ignore email addresses <foo@bar>
4772                                         if (($op eq '<' &&
4773                                              $cc =~ /^\S+\@\S+>/) ||
4774                                             ($op eq '>' &&
4775                                              $ca =~ /<\S+\@\S+$/))
4776                                         {
4777                                                 $ok = 1;
4778                                         }
4779
4780                                         # for asm volatile statements
4781                                         # ignore a colon with another
4782                                         # colon immediately before or after
4783                                         if (($op eq ':') &&
4784                                             ($ca =~ /:$/ || $cc =~ /^:/)) {
4785                                                 $ok = 1;
4786                                         }
4787
4788                                         # messages are ERROR, but ?: are CHK
4789                                         if ($ok == 0) {
4790                                                 my $msg_level = \&ERROR;
4791                                                 $msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4792
4793                                                 if (&{$msg_level}("SPACING",
4794                                                                   "spaces required around that '$op' $at\n" . $hereptr)) {
4795                                                         $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4796                                                         if (defined $fix_elements[$n + 2]) {
4797                                                                 $fix_elements[$n + 2] =~ s/^\s+//;
4798                                                         }
4799                                                         $line_fixed = 1;
4800                                                 }
4801                                         }
4802                                 }
4803                                 $off += length($elements[$n + 1]);
4804
4805 ##                              print("n: <$n> GOOD: <$good>\n");
4806
4807                                 $fixed_line = $fixed_line . $good;
4808                         }
4809
4810                         if (($#elements % 2) == 0) {
4811                                 $fixed_line = $fixed_line . $fix_elements[$#elements];
4812                         }
4813
4814                         if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4815                                 $fixed[$fixlinenr] = $fixed_line;
4816                         }
4817
4818
4819                 }
4820
4821 # check for whitespace before a non-naked semicolon
4822                 if ($line =~ /^\+.*\S\s+;\s*$/) {
4823                         if (WARN("SPACING",
4824                                  "space prohibited before semicolon\n" . $herecurr) &&
4825                             $fix) {
4826                                 1 while $fixed[$fixlinenr] =~
4827                                     s/^(\+.*\S)\s+;/$1;/;
4828                         }
4829                 }
4830
4831 # check for multiple assignments
4832                 if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4833                         CHK("MULTIPLE_ASSIGNMENTS",
4834                             "multiple assignments should be avoided\n" . $herecurr);
4835                 }
4836
4837 ## # check for multiple declarations, allowing for a function declaration
4838 ## # continuation.
4839 ##              if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4840 ##                  $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4841 ##
4842 ##                      # Remove any bracketed sections to ensure we do not
4843 ##                      # falsly report the parameters of functions.
4844 ##                      my $ln = $line;
4845 ##                      while ($ln =~ s/\([^\(\)]*\)//g) {
4846 ##                      }
4847 ##                      if ($ln =~ /,/) {
4848 ##                              WARN("MULTIPLE_DECLARATION",
4849 ##                                   "declaring multiple variables together should be avoided\n" . $herecurr);
4850 ##                      }
4851 ##              }
4852
4853 #need space before brace following if, while, etc
4854                 if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4855                     $line =~ /\b(?:else|do)\{/) {
4856                         if (ERROR("SPACING",
4857                                   "space required before the open brace '{'\n" . $herecurr) &&
4858                             $fix) {
4859                                 $fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4860                         }
4861                 }
4862
4863 ## # check for blank lines before declarations
4864 ##              if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4865 ##                  $prevrawline =~ /^.\s*$/) {
4866 ##                      WARN("SPACING",
4867 ##                           "No blank lines before declarations\n" . $hereprev);
4868 ##              }
4869 ##
4870
4871 # closing brace should have a space following it when it has anything
4872 # on the line
4873                 if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
4874                         if (ERROR("SPACING",
4875                                   "space required after that close brace '}'\n" . $herecurr) &&
4876                             $fix) {
4877                                 $fixed[$fixlinenr] =~
4878                                     s/}((?!(?:,|;|\)))\S)/} $1/;
4879                         }
4880                 }
4881
4882 # check spacing on square brackets
4883                 if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4884                         if (ERROR("SPACING",
4885                                   "space prohibited after that open square bracket '['\n" . $herecurr) &&
4886                             $fix) {
4887                                 $fixed[$fixlinenr] =~
4888                                     s/\[\s+/\[/;
4889                         }
4890                 }
4891                 if ($line =~ /\s\]/) {
4892                         if (ERROR("SPACING",
4893                                   "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4894                             $fix) {
4895                                 $fixed[$fixlinenr] =~
4896                                     s/\s+\]/\]/;
4897                         }
4898                 }
4899
4900 # check spacing on parentheses
4901                 if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4902                     $line !~ /for\s*\(\s+;/) {
4903                         if (ERROR("SPACING",
4904                                   "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4905                             $fix) {
4906                                 $fixed[$fixlinenr] =~
4907                                     s/\(\s+/\(/;
4908                         }
4909                 }
4910                 if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4911                     $line !~ /for\s*\(.*;\s+\)/ &&
4912                     $line !~ /:\s+\)/) {
4913                         if (ERROR("SPACING",
4914                                   "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4915                             $fix) {
4916                                 $fixed[$fixlinenr] =~
4917                                     s/\s+\)/\)/;
4918                         }
4919                 }
4920
4921 # check unnecessary parentheses around addressof/dereference single $Lvals
4922 # ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4923
4924                 while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4925                         my $var = $1;
4926                         if (CHK("UNNECESSARY_PARENTHESES",
4927                                 "Unnecessary parentheses around $var\n" . $herecurr) &&
4928                             $fix) {
4929                                 $fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4930                         }
4931                 }
4932
4933 # check for unnecessary parentheses around function pointer uses
4934 # ie: (foo->bar)(); should be foo->bar();
4935 # but not "if (foo->bar) (" to avoid some false positives
4936                 if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4937                         my $var = $2;
4938                         if (CHK("UNNECESSARY_PARENTHESES",
4939                                 "Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4940                             $fix) {
4941                                 my $var2 = deparenthesize($var);
4942                                 $var2 =~ s/\s//g;
4943                                 $fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4944                         }
4945                 }
4946
4947 # check for unnecessary parentheses around comparisons in if uses
4948 # when !drivers/staging or command-line uses --strict
4949                 if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4950                     $perl_version_ok && defined($stat) &&
4951                     $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4952                         my $if_stat = $1;
4953                         my $test = substr($2, 1, -1);
4954                         my $herectx;
4955                         while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4956                                 my $match = $1;
4957                                 # avoid parentheses around potential macro args
4958                                 next if ($match =~ /^\s*\w+\s*$/);
4959                                 if (!defined($herectx)) {
4960                                         $herectx = $here . "\n";
4961                                         my $cnt = statement_rawlines($if_stat);
4962                                         for (my $n = 0; $n < $cnt; $n++) {
4963                                                 my $rl = raw_line($linenr, $n);
4964                                                 $herectx .=  $rl . "\n";
4965                                                 last if $rl =~ /^[ \+].*\{/;
4966                                         }
4967                                 }
4968                                 CHK("UNNECESSARY_PARENTHESES",
4969                                     "Unnecessary parentheses around '$match'\n" . $herectx);
4970                         }
4971                 }
4972
4973 #goto labels aren't indented, allow a single space however
4974                 if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4975                    !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4976                         if (WARN("INDENTED_LABEL",
4977                                  "labels should not be indented\n" . $herecurr) &&
4978                             $fix) {
4979                                 $fixed[$fixlinenr] =~
4980                                     s/^(.)\s+/$1/;
4981                         }
4982                 }
4983
4984 # check if a statement with a comma should be two statements like:
4985 #       foo = bar(),    /* comma should be semicolon */
4986 #       bar = baz();
4987                 if (defined($stat) &&
4988                     $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
4989                         my $cnt = statement_rawlines($stat);
4990                         my $herectx = get_stat_here($linenr, $cnt, $here);
4991                         WARN("SUSPECT_COMMA_SEMICOLON",
4992                              "Possible comma where semicolon could be used\n" . $herectx);
4993                 }
4994
4995 # return is not a function
4996                 if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4997                         my $spacing = $1;
4998                         if ($perl_version_ok &&
4999                             $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5000                                 my $value = $1;
5001                                 $value = deparenthesize($value);
5002                                 if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5003                                         ERROR("RETURN_PARENTHESES",
5004                                               "return is not a function, parentheses are not required\n" . $herecurr);
5005                                 }
5006                         } elsif ($spacing !~ /\s+/) {
5007                                 ERROR("SPACING",
5008                                       "space required before the open parenthesis '('\n" . $herecurr);
5009                         }
5010                 }
5011
5012 # unnecessary return in a void function
5013 # at end-of-function, with the previous line a single leading tab, then return;
5014 # and the line before that not a goto label target like "out:"
5015                 if ($sline =~ /^[ \+]}\s*$/ &&
5016                     $prevline =~ /^\+\treturn\s*;\s*$/ &&
5017                     $linenr >= 3 &&
5018                     $lines[$linenr - 3] =~ /^[ +]/ &&
5019                     $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5020                         WARN("RETURN_VOID",
5021                              "void function return statements are not generally useful\n" . $hereprev);
5022                }
5023
5024 # if statements using unnecessary parentheses - ie: if ((foo == bar))
5025                 if ($perl_version_ok &&
5026                     $line =~ /\bif\s*((?:\(\s*){2,})/) {
5027                         my $openparens = $1;
5028                         my $count = $openparens =~ tr@\(@\(@;
5029                         my $msg = "";
5030                         if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5031                                 my $comp = $4;  #Not $1 because of $LvalOrFunc
5032                                 $msg = " - maybe == should be = ?" if ($comp eq "==");
5033                                 WARN("UNNECESSARY_PARENTHESES",
5034                                      "Unnecessary parentheses$msg\n" . $herecurr);
5035                         }
5036                 }
5037
5038 # comparisons with a constant or upper case identifier on the left
5039 #       avoid cases like "foo + BAR < baz"
5040 #       only fix matches surrounded by parentheses to avoid incorrect
5041 #       conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5042                 if ($perl_version_ok &&
5043                     $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5044                         my $lead = $1;
5045                         my $const = $2;
5046                         my $comp = $3;
5047                         my $to = $4;
5048                         my $newcomp = $comp;
5049                         if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5050                             $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5051                             WARN("CONSTANT_COMPARISON",
5052                                  "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5053                             $fix) {
5054                                 if ($comp eq "<") {
5055                                         $newcomp = ">";
5056                                 } elsif ($comp eq "<=") {
5057                                         $newcomp = ">=";
5058                                 } elsif ($comp eq ">") {
5059                                         $newcomp = "<";
5060                                 } elsif ($comp eq ">=") {
5061                                         $newcomp = "<=";
5062                                 }
5063                                 $fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5064                         }
5065                 }
5066
5067 # Return of what appears to be an errno should normally be negative
5068                 if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5069                         my $name = $1;
5070                         if ($name ne 'EOF' && $name ne 'ERROR') {
5071                                 WARN("USE_NEGATIVE_ERRNO",
5072                                      "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5073                         }
5074                 }
5075
5076 # Need a space before open parenthesis after if, while etc
5077                 if ($line =~ /\b(if|while|for|switch)\(/) {
5078                         if (ERROR("SPACING",
5079                                   "space required before the open parenthesis '('\n" . $herecurr) &&
5080                             $fix) {
5081                                 $fixed[$fixlinenr] =~
5082                                     s/\b(if|while|for|switch)\(/$1 \(/;
5083                         }
5084                 }
5085
5086 # Check for illegal assignment in if conditional -- and check for trailing
5087 # statements after the conditional.
5088                 if ($line =~ /do\s*(?!{)/) {
5089                         ($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5090                                 ctx_statement_block($linenr, $realcnt, 0)
5091                                         if (!defined $stat);
5092                         my ($stat_next) = ctx_statement_block($line_nr_next,
5093                                                 $remain_next, $off_next);
5094                         $stat_next =~ s/\n./\n /g;
5095                         ##print "stat<$stat> stat_next<$stat_next>\n";
5096
5097                         if ($stat_next =~ /^\s*while\b/) {
5098                                 # If the statement carries leading newlines,
5099                                 # then count those as offsets.
5100                                 my ($whitespace) =
5101                                         ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5102                                 my $offset =
5103                                         statement_rawlines($whitespace) - 1;
5104
5105                                 $suppress_whiletrailers{$line_nr_next +
5106                                                                 $offset} = 1;
5107                         }
5108                 }
5109                 if (!defined $suppress_whiletrailers{$linenr} &&
5110                     defined($stat) && defined($cond) &&
5111                     $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5112                         my ($s, $c) = ($stat, $cond);
5113
5114                         if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5115                                 if (ERROR("ASSIGN_IN_IF",
5116                                           "do not use assignment in if condition\n" . $herecurr) &&
5117                                     $fix && $perl_version_ok) {
5118                                         if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5119                                                 my $space = $1;
5120                                                 my $not = $2;
5121                                                 my $statement = $3;
5122                                                 my $assigned = $4;
5123                                                 my $test = $8;
5124                                                 my $against = $9;
5125                                                 my $brace = $15;
5126                                                 fix_delete_line($fixlinenr, $rawline);
5127                                                 fix_insert_line($fixlinenr, "$space$statement;");
5128                                                 my $newline = "${space}if (";
5129                                                 $newline .= '!' if defined($not);
5130                                                 $newline .= '(' if (defined $not && defined($test) && defined($against));
5131                                                 $newline .= "$assigned";
5132                                                 $newline .= " $test $against" if (defined($test) && defined($against));
5133                                                 $newline .= ')' if (defined $not && defined($test) && defined($against));
5134                                                 $newline .= ')';
5135                                                 $newline .= " {" if (defined($brace));
5136                                                 fix_insert_line($fixlinenr + 1, $newline);
5137                                         }
5138                                 }
5139                         }
5140
5141                         # Find out what is on the end of the line after the
5142                         # conditional.
5143                         substr($s, 0, length($c), '');
5144                         $s =~ s/\n.*//g;
5145                         $s =~ s/$;//g;  # Remove any comments
5146                         if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5147                             $c !~ /}\s*while\s*/)
5148                         {
5149                                 # Find out how long the conditional actually is.
5150                                 my @newlines = ($c =~ /\n/gs);
5151                                 my $cond_lines = 1 + $#newlines;
5152                                 my $stat_real = '';
5153
5154                                 $stat_real = raw_line($linenr, $cond_lines)
5155                                                         . "\n" if ($cond_lines);
5156                                 if (defined($stat_real) && $cond_lines > 1) {
5157                                         $stat_real = "[...]\n$stat_real";
5158                                 }
5159
5160                                 ERROR("TRAILING_STATEMENTS",
5161                                       "trailing statements should be on next line\n" . $herecurr . $stat_real);
5162                         }
5163                 }
5164
5165 # Check for bitwise tests written as boolean
5166                 if ($line =~ /
5167                         (?:
5168                                 (?:\[|\(|\&\&|\|\|)
5169                                 \s*0[xX][0-9]+\s*
5170                                 (?:\&\&|\|\|)
5171                         |
5172                                 (?:\&\&|\|\|)
5173                                 \s*0[xX][0-9]+\s*
5174                                 (?:\&\&|\|\||\)|\])
5175                         )/x)
5176                 {
5177                         WARN("HEXADECIMAL_BOOLEAN_TEST",
5178                              "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5179                 }
5180
5181 # if and else should not have general statements after it
5182                 if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5183                         my $s = $1;
5184                         $s =~ s/$;//g;  # Remove any comments
5185                         if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5186                                 ERROR("TRAILING_STATEMENTS",
5187                                       "trailing statements should be on next line\n" . $herecurr);
5188                         }
5189                 }
5190 # if should not continue a brace
5191                 if ($line =~ /}\s*if\b/) {
5192                         ERROR("TRAILING_STATEMENTS",
5193                               "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5194                                 $herecurr);
5195                 }
5196 # case and default should not have general statements after them
5197                 if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5198                     $line !~ /\G(?:
5199                         (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5200                         \s*return\s+
5201                     )/xg)
5202                 {
5203                         ERROR("TRAILING_STATEMENTS",
5204                               "trailing statements should be on next line\n" . $herecurr);
5205                 }
5206
5207                 # Check for }<nl>else {, these must be at the same
5208                 # indent level to be relevant to each other.
5209                 if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5210                     $previndent == $indent) {
5211                         if (ERROR("ELSE_AFTER_BRACE",
5212                                   "else should follow close brace '}'\n" . $hereprev) &&
5213                             $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5214                                 fix_delete_line($fixlinenr - 1, $prevrawline);
5215                                 fix_delete_line($fixlinenr, $rawline);
5216                                 my $fixedline = $prevrawline;
5217                                 $fixedline =~ s/}\s*$//;
5218                                 if ($fixedline !~ /^\+\s*$/) {
5219                                         fix_insert_line($fixlinenr, $fixedline);
5220                                 }
5221                                 $fixedline = $rawline;
5222                                 $fixedline =~ s/^(.\s*)else/$1} else/;
5223                                 fix_insert_line($fixlinenr, $fixedline);
5224                         }
5225                 }
5226
5227                 if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5228                     $previndent == $indent) {
5229                         my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5230
5231                         # Find out what is on the end of the line after the
5232                         # conditional.
5233                         substr($s, 0, length($c), '');
5234                         $s =~ s/\n.*//g;
5235
5236                         if ($s =~ /^\s*;/) {
5237                                 if (ERROR("WHILE_AFTER_BRACE",
5238                                           "while should follow close brace '}'\n" . $hereprev) &&
5239                                     $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5240                                         fix_delete_line($fixlinenr - 1, $prevrawline);
5241                                         fix_delete_line($fixlinenr, $rawline);
5242                                         my $fixedline = $prevrawline;
5243                                         my $trailing = $rawline;
5244                                         $trailing =~ s/^\+//;
5245                                         $trailing = trim($trailing);
5246                                         $fixedline =~ s/}\s*$/} $trailing/;
5247                                         fix_insert_line($fixlinenr, $fixedline);
5248                                 }
5249                         }
5250                 }
5251
5252 #Specific variable tests
5253                 while ($line =~ m{($Constant|$Lval)}g) {
5254                         my $var = $1;
5255
5256 #CamelCase
5257                         if ($var !~ /^$Constant$/ &&
5258                             $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5259 #Ignore Page<foo> variants
5260                             $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5261 #Ignore SI style variants like nS, mV and dB
5262 #(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5263                             $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5264 #Ignore some three character SI units explicitly, like MiB and KHz
5265                             $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5266                                 while ($var =~ m{($Ident)}g) {
5267                                         my $word = $1;
5268                                         next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5269                                         if ($check) {
5270                                                 seed_camelcase_includes();
5271                                                 if (!$file && !$camelcase_file_seeded) {
5272                                                         seed_camelcase_file($realfile);
5273                                                         $camelcase_file_seeded = 1;
5274                                                 }
5275                                         }
5276                                         if (!defined $camelcase{$word}) {
5277                                                 $camelcase{$word} = 1;
5278                                                 CHK("CAMELCASE",
5279                                                     "Avoid CamelCase: <$word>\n" . $herecurr);
5280                                         }
5281                                 }
5282                         }
5283                 }
5284
5285 #no spaces allowed after \ in define
5286                 if ($line =~ /\#\s*define.*\\\s+$/) {
5287                         if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5288                                  "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5289                             $fix) {
5290                                 $fixed[$fixlinenr] =~ s/\s+$//;
5291                         }
5292                 }
5293
5294 # warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5295 # itself <asm/foo.h> (uses RAW line)
5296                 if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5297                         my $file = "$1.h";
5298                         my $checkfile = "include/linux/$file";
5299                         if (-f "$root/$checkfile" &&
5300                             $realfile ne $checkfile &&
5301                             $1 !~ /$allowed_asm_includes/)
5302                         {
5303                                 my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5304                                 if ($asminclude > 0) {
5305                                         if ($realfile =~ m{^arch/}) {
5306                                                 CHK("ARCH_INCLUDE_LINUX",
5307                                                     "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5308                                         } else {
5309                                                 WARN("INCLUDE_LINUX",
5310                                                      "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5311                                         }
5312                                 }
5313                         }
5314                 }
5315
5316 # multi-statement macros should be enclosed in a do while loop, grab the
5317 # first statement and ensure its the whole macro if its not enclosed
5318 # in a known good container
5319                 if ($realfile !~ m@/vmlinux.lds.h$@ &&
5320                     $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5321                         my $ln = $linenr;
5322                         my $cnt = $realcnt;
5323                         my ($off, $dstat, $dcond, $rest);
5324                         my $ctx = '';
5325                         my $has_flow_statement = 0;
5326                         my $has_arg_concat = 0;
5327                         ($dstat, $dcond, $ln, $cnt, $off) =
5328                                 ctx_statement_block($linenr, $realcnt, 0);
5329                         $ctx = $dstat;
5330                         #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5331                         #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5332
5333                         $has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5334                         $has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5335
5336                         $dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5337                         my $define_args = $1;
5338                         my $define_stmt = $dstat;
5339                         my @def_args = ();
5340
5341                         if (defined $define_args && $define_args ne "") {
5342                                 $define_args = substr($define_args, 1, length($define_args) - 2);
5343                                 $define_args =~ s/\s*//g;
5344                                 $define_args =~ s/\\\+?//g;
5345                                 @def_args = split(",", $define_args);
5346                         }
5347
5348                         $dstat =~ s/$;//g;
5349                         $dstat =~ s/\\\n.//g;
5350                         $dstat =~ s/^\s*//s;
5351                         $dstat =~ s/\s*$//s;
5352
5353                         # Flatten any parentheses and braces
5354                         while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5355                                $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5356                                $dstat =~ s/.\[[^\[\]]*\]/1u/)
5357                         {
5358                         }
5359
5360                         # Flatten any obvious string concatenation.
5361                         while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5362                                $dstat =~ s/$Ident\s*($String)/$1/)
5363                         {
5364                         }
5365
5366                         # Make asm volatile uses seem like a generic function
5367                         $dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5368
5369                         my $exceptions = qr{
5370                                 $Declare|
5371                                 module_param_named|
5372                                 MODULE_PARM_DESC|
5373                                 DECLARE_PER_CPU|
5374                                 DEFINE_PER_CPU|
5375                                 __typeof__\(|
5376                                 union|
5377                                 struct|
5378                                 \.$Ident\s*=\s*|
5379                                 ^\"|\"$|
5380                                 ^\[
5381                         }x;
5382                         #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5383
5384                         $ctx =~ s/\n*$//;
5385                         my $stmt_cnt = statement_rawlines($ctx);
5386                         my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5387
5388                         if ($dstat ne '' &&
5389                             $dstat !~ /^(?:$Ident|-?$Constant),$/ &&                    # 10, // foo(),
5390                             $dstat !~ /^(?:$Ident|-?$Constant);$/ &&                    # foo();
5391                             $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ &&          # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5392                             $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ &&                  # character constants
5393                             $dstat !~ /$exceptions/ &&
5394                             $dstat !~ /^\.$Ident\s*=/ &&                                # .foo =
5395                             $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ &&          # stringification #foo
5396                             $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ &&       # do {...} while (...); // do {...} while (...)
5397                             $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ &&           # while (...) {...}
5398                             $dstat !~ /^for\s*$Constant$/ &&                            # for (...)
5399                             $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ &&   # for (...) bar()
5400                             $dstat !~ /^do\s*{/ &&                                      # do {...
5401                             $dstat !~ /^\(\{/ &&                                                # ({...
5402                             $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5403                         {
5404                                 if ($dstat =~ /^\s*if\b/) {
5405                                         ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5406                                               "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5407                                 } elsif ($dstat =~ /;/) {
5408                                         ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5409                                               "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5410                                 } else {
5411                                         ERROR("COMPLEX_MACRO",
5412                                               "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5413                                 }
5414
5415                         }
5416
5417                         # Make $define_stmt single line, comment-free, etc
5418                         my @stmt_array = split('\n', $define_stmt);
5419                         my $first = 1;
5420                         $define_stmt = "";
5421                         foreach my $l (@stmt_array) {
5422                                 $l =~ s/\\$//;
5423                                 if ($first) {
5424                                         $define_stmt = $l;
5425                                         $first = 0;
5426                                 } elsif ($l =~ /^[\+ ]/) {
5427                                         $define_stmt .= substr($l, 1);
5428                                 }
5429                         }
5430                         $define_stmt =~ s/$;//g;
5431                         $define_stmt =~ s/\s+/ /g;
5432                         $define_stmt = trim($define_stmt);
5433
5434 # check if any macro arguments are reused (ignore '...' and 'type')
5435                         foreach my $arg (@def_args) {
5436                                 next if ($arg =~ /\.\.\./);
5437                                 next if ($arg =~ /^type$/i);
5438                                 my $tmp_stmt = $define_stmt;
5439                                 $tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5440                                 $tmp_stmt =~ s/\#+\s*$arg\b//g;
5441                                 $tmp_stmt =~ s/\b$arg\s*\#\#//g;
5442                                 my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5443                                 if ($use_cnt > 1) {
5444                                         CHK("MACRO_ARG_REUSE",
5445                                             "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5446                                     }
5447 # check if any macro arguments may have other precedence issues
5448                                 if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5449                                     ((defined($1) && $1 ne ',') ||
5450                                      (defined($2) && $2 ne ','))) {
5451                                         CHK("MACRO_ARG_PRECEDENCE",
5452                                             "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5453                                 }
5454                         }
5455
5456 # check for macros with flow control, but without ## concatenation
5457 # ## concatenation is commonly a macro that defines a function so ignore those
5458                         if ($has_flow_statement && !$has_arg_concat) {
5459                                 my $cnt = statement_rawlines($ctx);
5460                                 my $herectx = get_stat_here($linenr, $cnt, $here);
5461
5462                                 WARN("MACRO_WITH_FLOW_CONTROL",
5463                                      "Macros with flow control statements should be avoided\n" . "$herectx");
5464                         }
5465
5466 # check for line continuations outside of #defines, preprocessor #, and asm
5467
5468                 } else {
5469                         if ($prevline !~ /^..*\\$/ &&
5470                             $line !~ /^\+\s*\#.*\\$/ &&         # preprocessor
5471                             $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ &&   # asm
5472                             $line =~ /^\+.*\\$/) {
5473                                 WARN("LINE_CONTINUATIONS",
5474                                      "Avoid unnecessary line continuations\n" . $herecurr);
5475                         }
5476                 }
5477
5478 # do {} while (0) macro tests:
5479 # single-statement macros do not need to be enclosed in do while (0) loop,
5480 # macro should not end with a semicolon
5481                 if ($perl_version_ok &&
5482                     $realfile !~ m@/vmlinux.lds.h$@ &&
5483                     $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5484                         my $ln = $linenr;
5485                         my $cnt = $realcnt;
5486                         my ($off, $dstat, $dcond, $rest);
5487                         my $ctx = '';
5488                         ($dstat, $dcond, $ln, $cnt, $off) =
5489                                 ctx_statement_block($linenr, $realcnt, 0);
5490                         $ctx = $dstat;
5491
5492                         $dstat =~ s/\\\n.//g;
5493                         $dstat =~ s/$;/ /g;
5494
5495                         if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5496                                 my $stmts = $2;
5497                                 my $semis = $3;
5498
5499                                 $ctx =~ s/\n*$//;
5500                                 my $cnt = statement_rawlines($ctx);
5501                                 my $herectx = get_stat_here($linenr, $cnt, $here);
5502
5503                                 if (($stmts =~ tr/;/;/) == 1 &&
5504                                     $stmts !~ /^\s*(if|while|for|switch)\b/) {
5505                                         WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5506                                              "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5507                                 }
5508                                 if (defined $semis && $semis ne "") {
5509                                         WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5510                                              "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5511                                 }
5512                         } elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5513                                 $ctx =~ s/\n*$//;
5514                                 my $cnt = statement_rawlines($ctx);
5515                                 my $herectx = get_stat_here($linenr, $cnt, $here);
5516
5517                                 WARN("TRAILING_SEMICOLON",
5518                                      "macros should not use a trailing semicolon\n" . "$herectx");
5519                         }
5520                 }
5521
5522 # check for redundant bracing round if etc
5523                 if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5524                         my ($level, $endln, @chunks) =
5525                                 ctx_statement_full($linenr, $realcnt, 1);
5526                         #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5527                         #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5528                         if ($#chunks > 0 && $level == 0) {
5529                                 my @allowed = ();
5530                                 my $allow = 0;
5531                                 my $seen = 0;
5532                                 my $herectx = $here . "\n";
5533                                 my $ln = $linenr - 1;
5534                                 for my $chunk (@chunks) {
5535                                         my ($cond, $block) = @{$chunk};
5536
5537                                         # If the condition carries leading newlines, then count those as offsets.
5538                                         my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5539                                         my $offset = statement_rawlines($whitespace) - 1;
5540
5541                                         $allowed[$allow] = 0;
5542                                         #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5543
5544                                         # We have looked at and allowed this specific line.
5545                                         $suppress_ifbraces{$ln + $offset} = 1;
5546
5547                                         $herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5548                                         $ln += statement_rawlines($block) - 1;
5549
5550                                         substr($block, 0, length($cond), '');
5551
5552                                         $seen++ if ($block =~ /^\s*{/);
5553
5554                                         #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5555                                         if (statement_lines($cond) > 1) {
5556                                                 #print "APW: ALLOWED: cond<$cond>\n";
5557                                                 $allowed[$allow] = 1;
5558                                         }
5559                                         if ($block =~/\b(?:if|for|while)\b/) {
5560                                                 #print "APW: ALLOWED: block<$block>\n";
5561                                                 $allowed[$allow] = 1;
5562                                         }
5563                                         if (statement_block_size($block) > 1) {
5564                                                 #print "APW: ALLOWED: lines block<$block>\n";
5565                                                 $allowed[$allow] = 1;
5566                                         }
5567                                         $allow++;
5568                                 }
5569                                 if ($seen) {
5570                                         my $sum_allowed = 0;
5571                                         foreach (@allowed) {
5572                                                 $sum_allowed += $_;
5573                                         }
5574                                         if ($sum_allowed == 0) {
5575                                                 WARN("BRACES",
5576                                                      "braces {} are not necessary for any arm of this statement\n" . $herectx);
5577                                         } elsif ($sum_allowed != $allow &&
5578                                                  $seen != $allow) {
5579                                                 CHK("BRACES",
5580                                                     "braces {} should be used on all arms of this statement\n" . $herectx);
5581                                         }
5582                                 }
5583                         }
5584                 }
5585                 if (!defined $suppress_ifbraces{$linenr - 1} &&
5586                                         $line =~ /\b(if|while|for|else)\b/) {
5587                         my $allowed = 0;
5588
5589                         # Check the pre-context.
5590                         if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5591                                 #print "APW: ALLOWED: pre<$1>\n";
5592                                 $allowed = 1;
5593                         }
5594
5595                         my ($level, $endln, @chunks) =
5596                                 ctx_statement_full($linenr, $realcnt, $-[0]);
5597
5598                         # Check the condition.
5599                         my ($cond, $block) = @{$chunks[0]};
5600                         #print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5601                         if (defined $cond) {
5602                                 substr($block, 0, length($cond), '');
5603                         }
5604                         if (statement_lines($cond) > 1) {
5605                                 #print "APW: ALLOWED: cond<$cond>\n";
5606                                 $allowed = 1;
5607                         }
5608                         if ($block =~/\b(?:if|for|while)\b/) {
5609                                 #print "APW: ALLOWED: block<$block>\n";
5610                                 $allowed = 1;
5611                         }
5612                         if (statement_block_size($block) > 1) {
5613                                 #print "APW: ALLOWED: lines block<$block>\n";
5614                                 $allowed = 1;
5615                         }
5616                         # Check the post-context.
5617                         if (defined $chunks[1]) {
5618                                 my ($cond, $block) = @{$chunks[1]};
5619                                 if (defined $cond) {
5620                                         substr($block, 0, length($cond), '');
5621                                 }
5622                                 if ($block =~ /^\s*\{/) {
5623                                         #print "APW: ALLOWED: chunk-1 block<$block>\n";
5624                                         $allowed = 1;
5625                                 }
5626                         }
5627                         if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5628                                 my $cnt = statement_rawlines($block);
5629                                 my $herectx = get_stat_here($linenr, $cnt, $here);
5630
5631                                 WARN("BRACES",
5632                                      "braces {} are not necessary for single statement blocks\n" . $herectx);
5633                         }
5634                 }
5635
5636 # check for single line unbalanced braces
5637                 if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5638                     $sline =~ /^.\s*else\s*\{\s*$/) {
5639                         CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5640                 }
5641
5642 # check for unnecessary blank lines around braces
5643                 if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5644                         if (CHK("BRACES",
5645                                 "Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5646                             $fix && $prevrawline =~ /^\+/) {
5647                                 fix_delete_line($fixlinenr - 1, $prevrawline);
5648                         }
5649                 }
5650                 if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5651                         if (CHK("BRACES",
5652                                 "Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5653                             $fix) {
5654                                 fix_delete_line($fixlinenr, $rawline);
5655                         }
5656                 }
5657
5658 # no volatiles please
5659                 my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5660                 if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5661                         WARN("VOLATILE",
5662                              "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5663                 }
5664
5665 # Check for user-visible strings broken across lines, which breaks the ability
5666 # to grep for the string.  Make exceptions when the previous string ends in a
5667 # newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5668 # (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5669                 if ($line =~ /^\+\s*$String/ &&
5670                     $prevline =~ /"\s*$/ &&
5671                     $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5672                         if (WARN("SPLIT_STRING",
5673                                  "quoted string split across lines\n" . $hereprev) &&
5674                                      $fix &&
5675                                      $prevrawline =~ /^\+.*"\s*$/ &&
5676                                      $last_coalesced_string_linenr != $linenr - 1) {
5677                                 my $extracted_string = get_quoted_string($line, $rawline);
5678                                 my $comma_close = "";
5679                                 if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5680                                         $comma_close = $1;
5681                                 }
5682
5683                                 fix_delete_line($fixlinenr - 1, $prevrawline);
5684                                 fix_delete_line($fixlinenr, $rawline);
5685                                 my $fixedline = $prevrawline;
5686                                 $fixedline =~ s/"\s*$//;
5687                                 $fixedline .= substr($extracted_string, 1) . trim($comma_close);
5688                                 fix_insert_line($fixlinenr - 1, $fixedline);
5689                                 $fixedline = $rawline;
5690                                 $fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5691                                 if ($fixedline !~ /\+\s*$/) {
5692                                         fix_insert_line($fixlinenr, $fixedline);
5693                                 }
5694                                 $last_coalesced_string_linenr = $linenr;
5695                         }
5696                 }
5697
5698 # check for missing a space in a string concatenation
5699                 if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5700                         WARN('MISSING_SPACE',
5701                              "break quoted strings at a space character\n" . $hereprev);
5702                 }
5703
5704 # check for an embedded function name in a string when the function is known
5705 # This does not work very well for -f --file checking as it depends on patch
5706 # context providing the function name or a single line form for in-file
5707 # function declarations
5708                 if ($line =~ /^\+.*$String/ &&
5709                     defined($context_function) &&
5710                     get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5711                     length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5712                         WARN("EMBEDDED_FUNCTION_NAME",
5713                              "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5714                 }
5715
5716 # check for spaces before a quoted newline
5717                 if ($rawline =~ /^.*\".*\s\\n/) {
5718                         if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5719                                  "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5720                             $fix) {
5721                                 $fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5722                         }
5723
5724                 }
5725
5726 # concatenated string without spaces between elements
5727                 if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5728                         if (CHK("CONCATENATED_STRING",
5729                                 "Concatenated strings should use spaces between elements\n" . $herecurr) &&
5730                             $fix) {
5731                                 while ($line =~ /($String)/g) {
5732                                         my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5733                                         $fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5734                                         $fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5735                                 }
5736                         }
5737                 }
5738
5739 # uncoalesced string fragments
5740                 if ($line =~ /$String\s*"/) {
5741                         if (WARN("STRING_FRAGMENTS",
5742                                  "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5743                             $fix) {
5744                                 while ($line =~ /($String)(?=\s*")/g) {
5745                                         my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5746                                         $fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5747                                 }
5748                         }
5749                 }
5750
5751 # check for non-standard and hex prefixed decimal printf formats
5752                 my $show_L = 1; #don't show the same defect twice
5753                 my $show_Z = 1;
5754                 while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5755                         my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5756                         $string =~ s/%%/__/g;
5757                         # check for %L
5758                         if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5759                                 WARN("PRINTF_L",
5760                                      "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5761                                 $show_L = 0;
5762                         }
5763                         # check for %Z
5764                         if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5765                                 WARN("PRINTF_Z",
5766                                      "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5767                                 $show_Z = 0;
5768                         }
5769                         # check for 0x<decimal>
5770                         if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5771                                 ERROR("PRINTF_0XDECIMAL",
5772                                       "Prefixing 0x with decimal output is defective\n" . $herecurr);
5773                         }
5774                 }
5775
5776 # check for line continuations in quoted strings with odd counts of "
5777                 if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5778                         WARN("LINE_CONTINUATIONS",
5779                              "Avoid line continuations in quoted strings\n" . $herecurr);
5780                 }
5781
5782 # warn about #if 0
5783                 if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5784                         WARN("IF_0",
5785                              "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5786                 }
5787
5788 # warn about #if 1
5789                 if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5790                         WARN("IF_1",
5791                              "Consider removing the #if 1 and its #endif\n" . $herecurr);
5792                 }
5793
5794 # check for needless "if (<foo>) fn(<foo>)" uses
5795                 if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5796                         my $tested = quotemeta($1);
5797                         my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5798                         if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5799                                 my $func = $1;
5800                                 if (WARN('NEEDLESS_IF',
5801                                          "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5802                                     $fix) {
5803                                         my $do_fix = 1;
5804                                         my $leading_tabs = "";
5805                                         my $new_leading_tabs = "";
5806                                         if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5807                                                 $leading_tabs = $1;
5808                                         } else {
5809                                                 $do_fix = 0;
5810                                         }
5811                                         if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5812                                                 $new_leading_tabs = $1;
5813                                                 if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5814                                                         $do_fix = 0;
5815                                                 }
5816                                         } else {
5817                                                 $do_fix = 0;
5818                                         }
5819                                         if ($do_fix) {
5820                                                 fix_delete_line($fixlinenr - 1, $prevrawline);
5821                                                 $fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5822                                         }
5823                                 }
5824                         }
5825                 }
5826
5827 # check for unnecessary "Out of Memory" messages
5828                 if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5829                     $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5830                     (defined $1 || defined $3) &&
5831                     $linenr > 3) {
5832                         my $testval = $2;
5833                         my $testline = $lines[$linenr - 3];
5834
5835                         my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5836 #                       print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5837
5838                         if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5839                             $s !~ /\b__GFP_NOWARN\b/ ) {
5840                                 WARN("OOM_MESSAGE",
5841                                      "Possible unnecessary 'out of memory' message\n" . $hereprev);
5842                         }
5843                 }
5844
5845 # check for logging functions with KERN_<LEVEL>
5846                 if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5847                     $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5848                         my $level = $1;
5849                         if (WARN("UNNECESSARY_KERN_LEVEL",
5850                                  "Possible unnecessary $level\n" . $herecurr) &&
5851                             $fix) {
5852                                 $fixed[$fixlinenr] =~ s/\s*$level\s*//;
5853                         }
5854                 }
5855
5856 # check for logging continuations
5857                 if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5858                         WARN("LOGGING_CONTINUATION",
5859                              "Avoid logging continuation uses where feasible\n" . $herecurr);
5860                 }
5861
5862 # check for mask then right shift without a parentheses
5863                 if ($perl_version_ok &&
5864                     $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5865                     $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5866                         WARN("MASK_THEN_SHIFT",
5867                              "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5868                 }
5869
5870 # check for pointer comparisons to NULL
5871                 if ($perl_version_ok) {
5872                         while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5873                                 my $val = $1;
5874                                 my $equal = "!";
5875                                 $equal = "" if ($4 eq "!=");
5876                                 if (CHK("COMPARISON_TO_NULL",
5877                                         "Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5878                                             $fix) {
5879                                         $fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5880                                 }
5881                         }
5882                 }
5883
5884 # check for bad placement of section $InitAttribute (e.g.: __initdata)
5885                 if ($line =~ /(\b$InitAttribute\b)/) {
5886                         my $attr = $1;
5887                         if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5888                                 my $ptr = $1;
5889                                 my $var = $2;
5890                                 if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5891                                       ERROR("MISPLACED_INIT",
5892                                             "$attr should be placed after $var\n" . $herecurr)) ||
5893                                      ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5894                                       WARN("MISPLACED_INIT",
5895                                            "$attr should be placed after $var\n" . $herecurr))) &&
5896                                     $fix) {
5897                                         $fixed[$fixlinenr] =~ s/(\bstatic\s+(?:const\s+)?)(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*([=;])\s*/"$1" . trim(string_find_replace($2, "\\s*$attr\\s*", " ")) . " " . trim(string_find_replace($3, "\\s*$attr\\s*", "")) . " $attr" . ("$4" eq ";" ? ";" : " = ")/e;
5898                                 }
5899                         }
5900                 }
5901
5902 # check for $InitAttributeData (ie: __initdata) with const
5903                 if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5904                         my $attr = $1;
5905                         $attr =~ /($InitAttributePrefix)(.*)/;
5906                         my $attr_prefix = $1;
5907                         my $attr_type = $2;
5908                         if (ERROR("INIT_ATTRIBUTE",
5909                                   "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5910                             $fix) {
5911                                 $fixed[$fixlinenr] =~
5912                                     s/$InitAttributeData/${attr_prefix}initconst/;
5913                         }
5914                 }
5915
5916 # check for $InitAttributeConst (ie: __initconst) without const
5917                 if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5918                         my $attr = $1;
5919                         if (ERROR("INIT_ATTRIBUTE",
5920                                   "Use of $attr requires a separate use of const\n" . $herecurr) &&
5921                             $fix) {
5922                                 my $lead = $fixed[$fixlinenr] =~
5923                                     /(^\+\s*(?:static\s+))/;
5924                                 $lead = rtrim($1);
5925                                 $lead = "$lead " if ($lead !~ /^\+$/);
5926                                 $lead = "${lead}const ";
5927                                 $fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5928                         }
5929                 }
5930
5931 # check for __read_mostly with const non-pointer (should just be const)
5932                 if ($line =~ /\b__read_mostly\b/ &&
5933                     $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5934                         if (ERROR("CONST_READ_MOSTLY",
5935                                   "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5936                             $fix) {
5937                                 $fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5938                         }
5939                 }
5940
5941 # don't use __constant_<foo> functions outside of include/uapi/
5942                 if ($realfile !~ m@^include/uapi/@ &&
5943                     $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5944                         my $constant_func = $1;
5945                         my $func = $constant_func;
5946                         $func =~ s/^__constant_//;
5947                         if (WARN("CONSTANT_CONVERSION",
5948                                  "$constant_func should be $func\n" . $herecurr) &&
5949                             $fix) {
5950                                 $fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5951                         }
5952                 }
5953
5954 # prefer usleep_range over udelay
5955                 if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5956                         my $delay = $1;
5957                         # ignore udelay's < 10, however
5958                         if (! ($delay < 10) ) {
5959                                 CHK("USLEEP_RANGE",
5960                                     "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5961                         }
5962                         if ($delay > 2000) {
5963                                 WARN("LONG_UDELAY",
5964                                      "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5965                         }
5966                 }
5967
5968 # warn about unexpectedly long msleep's
5969                 if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5970                         if ($1 < 20) {
5971                                 WARN("MSLEEP",
5972                                      "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5973                         }
5974                 }
5975
5976 # check for comparisons of jiffies
5977                 if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5978                         WARN("JIFFIES_COMPARISON",
5979                              "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5980                 }
5981
5982 # check for comparisons of get_jiffies_64()
5983                 if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5984                         WARN("JIFFIES_COMPARISON",
5985                              "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5986                 }
5987
5988 # warn about #ifdefs in C files
5989 #               if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5990 #                       print "#ifdef in C files should be avoided\n";
5991 #                       print "$herecurr";
5992 #                       $clean = 0;
5993 #               }
5994
5995 # warn about spacing in #ifdefs
5996                 if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5997                         if (ERROR("SPACING",
5998                                   "exactly one space required after that #$1\n" . $herecurr) &&
5999                             $fix) {
6000                                 $fixed[$fixlinenr] =~
6001                                     s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6002                         }
6003
6004                 }
6005
6006 # check for spinlock_t definitions without a comment.
6007                 if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6008                     $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6009                         my $which = $1;
6010                         if (!ctx_has_comment($first_line, $linenr)) {
6011                                 CHK("UNCOMMENTED_DEFINITION",
6012                                     "$1 definition without comment\n" . $herecurr);
6013                         }
6014                 }
6015 # check for memory barriers without a comment.
6016
6017                 my $barriers = qr{
6018                         mb|
6019                         rmb|
6020                         wmb
6021                 }x;
6022                 my $barrier_stems = qr{
6023                         mb__before_atomic|
6024                         mb__after_atomic|
6025                         store_release|
6026                         load_acquire|
6027                         store_mb|
6028                         (?:$barriers)
6029                 }x;
6030                 my $all_barriers = qr{
6031                         (?:$barriers)|
6032                         smp_(?:$barrier_stems)|
6033                         virt_(?:$barrier_stems)
6034                 }x;
6035
6036                 if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6037                         if (!ctx_has_comment($first_line, $linenr)) {
6038                                 WARN("MEMORY_BARRIER",
6039                                      "memory barrier without comment\n" . $herecurr);
6040                         }
6041                 }
6042
6043                 my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6044
6045                 if ($realfile !~ m@^include/asm-generic/@ &&
6046                     $realfile !~ m@/barrier\.h$@ &&
6047                     $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6048                     $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6049                         WARN("MEMORY_BARRIER",
6050                              "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6051                 }
6052
6053 # check for waitqueue_active without a comment.
6054                 if ($line =~ /\bwaitqueue_active\s*\(/) {
6055                         if (!ctx_has_comment($first_line, $linenr)) {
6056                                 WARN("WAITQUEUE_ACTIVE",
6057                                      "waitqueue_active without comment\n" . $herecurr);
6058                         }
6059                 }
6060
6061 # check for data_race without a comment.
6062                 if ($line =~ /\bdata_race\s*\(/) {
6063                         if (!ctx_has_comment($first_line, $linenr)) {
6064                                 WARN("DATA_RACE",
6065                                      "data_race without comment\n" . $herecurr);
6066                         }
6067                 }
6068
6069 # check of hardware specific defines
6070                 if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6071                         CHK("ARCH_DEFINES",
6072                             "architecture specific defines should be avoided\n" .  $herecurr);
6073                 }
6074
6075 # check that the storage class is not after a type
6076                 if ($line =~ /\b($Type)\s+($Storage)\b/) {
6077                         WARN("STORAGE_CLASS",
6078                              "storage class '$2' should be located before type '$1'\n" . $herecurr);
6079                 }
6080 # Check that the storage class is at the beginning of a declaration
6081                 if ($line =~ /\b$Storage\b/ &&
6082                     $line !~ /^.\s*$Storage/ &&
6083                     $line =~ /^.\s*(.+?)\$Storage\s/ &&
6084                     $1 !~ /[\,\)]\s*$/) {
6085                         WARN("STORAGE_CLASS",
6086                              "storage class should be at the beginning of the declaration\n" . $herecurr);
6087                 }
6088
6089 # check the location of the inline attribute, that it is between
6090 # storage class and type.
6091                 if ($line =~ /\b$Type\s+$Inline\b/ ||
6092                     $line =~ /\b$Inline\s+$Storage\b/) {
6093                         ERROR("INLINE_LOCATION",
6094                               "inline keyword should sit between storage class and type\n" . $herecurr);
6095                 }
6096
6097 # Check for __inline__ and __inline, prefer inline
6098                 if ($realfile !~ m@\binclude/uapi/@ &&
6099                     $line =~ /\b(__inline__|__inline)\b/) {
6100                         if (WARN("INLINE",
6101                                  "plain inline is preferred over $1\n" . $herecurr) &&
6102                             $fix) {
6103                                 $fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6104
6105                         }
6106                 }
6107
6108 # Check for __attribute__ packed, prefer __packed
6109                 if ($realfile !~ m@\binclude/uapi/@ &&
6110                     $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
6111                         WARN("PREFER_PACKED",
6112                              "__packed is preferred over __attribute__((packed))\n" . $herecurr);
6113                 }
6114
6115 # Check for __attribute__ aligned, prefer __aligned
6116                 if ($realfile !~ m@\binclude/uapi/@ &&
6117                     $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
6118                         WARN("PREFER_ALIGNED",
6119                              "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
6120                 }
6121
6122 # Check for __attribute__ section, prefer __section
6123                 if ($realfile !~ m@\binclude/uapi/@ &&
6124                     $line =~ /\b__attribute__\s*\(\s*\(.*_*section_*\s*\(\s*("[^"]*")/) {
6125                         my $old = substr($rawline, $-[1], $+[1] - $-[1]);
6126                         my $new = substr($old, 1, -1);
6127                         if (WARN("PREFER_SECTION",
6128                                  "__section($new) is preferred over __attribute__((section($old)))\n" . $herecurr) &&
6129                             $fix) {
6130                                 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*_*section_*\s*\(\s*\Q$old\E\s*\)\s*\)\s*\)/__section($new)/;
6131                         }
6132                 }
6133
6134 # Check for __attribute__ format(printf, prefer __printf
6135                 if ($realfile !~ m@\binclude/uapi/@ &&
6136                     $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
6137                         if (WARN("PREFER_PRINTF",
6138                                  "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
6139                             $fix) {
6140                                 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
6141
6142                         }
6143                 }
6144
6145 # Check for __attribute__ format(scanf, prefer __scanf
6146                 if ($realfile !~ m@\binclude/uapi/@ &&
6147                     $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
6148                         if (WARN("PREFER_SCANF",
6149                                  "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
6150                             $fix) {
6151                                 $fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
6152                         }
6153                 }
6154
6155 # Check for __attribute__ weak, or __weak declarations (may have link issues)
6156                 if ($perl_version_ok &&
6157                     $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6158                     ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6159                      $line =~ /\b__weak\b/)) {
6160                         ERROR("WEAK_DECLARATION",
6161                               "Using weak declarations can have unintended link defects\n" . $herecurr);
6162                 }
6163
6164 # check for c99 types like uint8_t used outside of uapi/ and tools/
6165                 if ($realfile !~ m@\binclude/uapi/@ &&
6166                     $realfile !~ m@\btools/@ &&
6167                     $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6168                         my $type = $1;
6169                         if ($type =~ /\b($typeC99Typedefs)\b/) {
6170                                 $type = $1;
6171                                 my $kernel_type = 'u';
6172                                 $kernel_type = 's' if ($type =~ /^_*[si]/);
6173                                 $type =~ /(\d+)/;
6174                                 $kernel_type .= $1;
6175                                 if (CHK("PREFER_KERNEL_TYPES",
6176                                         "Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6177                                     $fix) {
6178                                         $fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6179                                 }
6180                         }
6181                 }
6182
6183 # check for cast of C90 native int or longer types constants
6184                 if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6185                         my $cast = $1;
6186                         my $const = $2;
6187                         if (WARN("TYPECAST_INT_CONSTANT",
6188                                  "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
6189                             $fix) {
6190                                 my $suffix = "";
6191                                 my $newconst = $const;
6192                                 $newconst =~ s/${Int_type}$//;
6193                                 $suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6194                                 if ($cast =~ /\blong\s+long\b/) {
6195                                         $suffix .= 'LL';
6196                                 } elsif ($cast =~ /\blong\b/) {
6197                                         $suffix .= 'L';
6198                                 }
6199                                 $fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6200                         }
6201                 }
6202
6203 # check for sizeof(&)
6204                 if ($line =~ /\bsizeof\s*\(\s*\&/) {
6205                         WARN("SIZEOF_ADDRESS",
6206                              "sizeof(& should be avoided\n" . $herecurr);
6207                 }
6208
6209 # check for sizeof without parenthesis
6210                 if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6211                         if (WARN("SIZEOF_PARENTHESIS",
6212                                  "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6213                             $fix) {
6214                                 $fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6215                         }
6216                 }
6217
6218 # check for struct spinlock declarations
6219                 if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6220                         WARN("USE_SPINLOCK_T",
6221                              "struct spinlock should be spinlock_t\n" . $herecurr);
6222                 }
6223
6224 # check for seq_printf uses that could be seq_puts
6225                 if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6226                         my $fmt = get_quoted_string($line, $rawline);
6227                         $fmt =~ s/%%//g;
6228                         if ($fmt !~ /%/) {
6229                                 if (WARN("PREFER_SEQ_PUTS",
6230                                          "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6231                                     $fix) {
6232                                         $fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6233                                 }
6234                         }
6235                 }
6236
6237 # check for vsprintf extension %p<foo> misuses
6238                 if ($perl_version_ok &&
6239                     defined $stat &&
6240                     $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6241                     $1 !~ /^_*volatile_*$/) {
6242                         my $stat_real;
6243
6244                         my $lc = $stat =~ tr@\n@@;
6245                         $lc = $lc + $linenr;
6246                         for (my $count = $linenr; $count <= $lc; $count++) {
6247                                 my $specifier;
6248                                 my $extension;
6249                                 my $qualifier;
6250                                 my $bad_specifier = "";
6251                                 my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6252                                 $fmt =~ s/%%//g;
6253
6254                                 while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6255                                         $specifier = $1;
6256                                         $extension = $2;
6257                                         $qualifier = $3;
6258                                         if ($extension !~ /[SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6259                                             ($extension eq "f" &&
6260                                              defined $qualifier && $qualifier !~ /^w/)) {
6261                                                 $bad_specifier = $specifier;
6262                                                 last;
6263                                         }
6264                                         if ($extension eq "x" && !defined($stat_real)) {
6265                                                 if (!defined($stat_real)) {
6266                                                         $stat_real = get_stat_real($linenr, $lc);
6267                                                 }
6268                                                 WARN("VSPRINTF_SPECIFIER_PX",
6269                                                      "Using vsprintf specifier '\%px' potentially exposes the kernel memory layout, if you don't really need the address please consider using '\%p'.\n" . "$here\n$stat_real\n");
6270                                         }
6271                                 }
6272                                 if ($bad_specifier ne "") {
6273                                         my $stat_real = get_stat_real($linenr, $lc);
6274                                         my $ext_type = "Invalid";
6275                                         my $use = "";
6276                                         if ($bad_specifier =~ /p[Ff]/) {
6277                                                 $use = " - use %pS instead";
6278                                                 $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6279                                         }
6280
6281                                         WARN("VSPRINTF_POINTER_EXTENSION",
6282                                              "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6283                                 }
6284                         }
6285                 }
6286
6287 # Check for misused memsets
6288                 if ($perl_version_ok &&
6289                     defined $stat &&
6290                     $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6291
6292                         my $ms_addr = $2;
6293                         my $ms_val = $7;
6294                         my $ms_size = $12;
6295
6296                         if ($ms_size =~ /^(0x|)0$/i) {
6297                                 ERROR("MEMSET",
6298                                       "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6299                         } elsif ($ms_size =~ /^(0x|)1$/i) {
6300                                 WARN("MEMSET",
6301                                      "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6302                         }
6303                 }
6304
6305 # Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6306 #               if ($perl_version_ok &&
6307 #                   defined $stat &&
6308 #                   $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6309 #                       if (WARN("PREFER_ETHER_ADDR_COPY",
6310 #                                "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6311 #                           $fix) {
6312 #                               $fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6313 #                       }
6314 #               }
6315
6316 # Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6317 #               if ($perl_version_ok &&
6318 #                   defined $stat &&
6319 #                   $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6320 #                       WARN("PREFER_ETHER_ADDR_EQUAL",
6321 #                            "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6322 #               }
6323
6324 # check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6325 # check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6326 #               if ($perl_version_ok &&
6327 #                   defined $stat &&
6328 #                   $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6329 #
6330 #                       my $ms_val = $7;
6331 #
6332 #                       if ($ms_val =~ /^(?:0x|)0+$/i) {
6333 #                               if (WARN("PREFER_ETH_ZERO_ADDR",
6334 #                                        "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6335 #                                   $fix) {
6336 #                                       $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6337 #                               }
6338 #                       } elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6339 #                               if (WARN("PREFER_ETH_BROADCAST_ADDR",
6340 #                                        "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6341 #                                   $fix) {
6342 #                                       $fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6343 #                               }
6344 #                       }
6345 #               }
6346
6347 # typecasts on min/max could be min_t/max_t
6348                 if ($perl_version_ok &&
6349                     defined $stat &&
6350                     $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6351                         if (defined $2 || defined $7) {
6352                                 my $call = $1;
6353                                 my $cast1 = deparenthesize($2);
6354                                 my $arg1 = $3;
6355                                 my $cast2 = deparenthesize($7);
6356                                 my $arg2 = $8;
6357                                 my $cast;
6358
6359                                 if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6360                                         $cast = "$cast1 or $cast2";
6361                                 } elsif ($cast1 ne "") {
6362                                         $cast = $cast1;
6363                                 } else {
6364                                         $cast = $cast2;
6365                                 }
6366                                 WARN("MINMAX",
6367                                      "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6368                         }
6369                 }
6370
6371 # check usleep_range arguments
6372                 if ($perl_version_ok &&
6373                     defined $stat &&
6374                     $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6375                         my $min = $1;
6376                         my $max = $7;
6377                         if ($min eq $max) {
6378                                 WARN("USLEEP_RANGE",
6379                                      "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6380                         } elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6381                                  $min > $max) {
6382                                 WARN("USLEEP_RANGE",
6383                                      "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6384                         }
6385                 }
6386
6387 # check for naked sscanf
6388                 if ($perl_version_ok &&
6389                     defined $stat &&
6390                     $line =~ /\bsscanf\b/ &&
6391                     ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6392                      $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6393                      $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6394                         my $lc = $stat =~ tr@\n@@;
6395                         $lc = $lc + $linenr;
6396                         my $stat_real = get_stat_real($linenr, $lc);
6397                         WARN("NAKED_SSCANF",
6398                              "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6399                 }
6400
6401 # check for simple sscanf that should be kstrto<foo>
6402                 if ($perl_version_ok &&
6403                     defined $stat &&
6404                     $line =~ /\bsscanf\b/) {
6405                         my $lc = $stat =~ tr@\n@@;
6406                         $lc = $lc + $linenr;
6407                         my $stat_real = get_stat_real($linenr, $lc);
6408                         if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6409                                 my $format = $6;
6410                                 my $count = $format =~ tr@%@%@;
6411                                 if ($count == 1 &&
6412                                     $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6413                                         WARN("SSCANF_TO_KSTRTO",
6414                                              "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6415                                 }
6416                         }
6417                 }
6418
6419 # check for new externs in .h files.
6420                 if ($realfile =~ /\.h$/ &&
6421                     $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6422                         if (CHK("AVOID_EXTERNS",
6423                                 "extern prototypes should be avoided in .h files\n" . $herecurr) &&
6424                             $fix) {
6425                                 $fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6426                         }
6427                 }
6428
6429 # check for new externs in .c files.
6430                 if ($realfile =~ /\.c$/ && defined $stat &&
6431                     $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6432                 {
6433                         my $function_name = $1;
6434                         my $paren_space = $2;
6435
6436                         my $s = $stat;
6437                         if (defined $cond) {
6438                                 substr($s, 0, length($cond), '');
6439                         }
6440                         if ($s =~ /^\s*;/)
6441                         {
6442                                 WARN("AVOID_EXTERNS",
6443                                      "externs should be avoided in .c files\n" .  $herecurr);
6444                         }
6445
6446                         if ($paren_space =~ /\n/) {
6447                                 WARN("FUNCTION_ARGUMENTS",
6448                                      "arguments for function declarations should follow identifier\n" . $herecurr);
6449                         }
6450
6451                 } elsif ($realfile =~ /\.c$/ && defined $stat &&
6452                     $stat =~ /^.\s*extern\s+/)
6453                 {
6454                         WARN("AVOID_EXTERNS",
6455                              "externs should be avoided in .c files\n" .  $herecurr);
6456                 }
6457
6458 # check for function declarations that have arguments without identifier names
6459                 if (defined $stat &&
6460                     $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6461                     $1 ne "void") {
6462                         my $args = trim($1);
6463                         while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6464                                 my $arg = trim($1);
6465                                 if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6466                                         WARN("FUNCTION_ARGUMENTS",
6467                                              "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6468                                 }
6469                         }
6470                 }
6471
6472 # check for function definitions
6473                 if ($perl_version_ok &&
6474                     defined $stat &&
6475                     $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6476                         $context_function = $1;
6477
6478 # check for multiline function definition with misplaced open brace
6479                         my $ok = 0;
6480                         my $cnt = statement_rawlines($stat);
6481                         my $herectx = $here . "\n";
6482                         for (my $n = 0; $n < $cnt; $n++) {
6483                                 my $rl = raw_line($linenr, $n);
6484                                 $herectx .=  $rl . "\n";
6485                                 $ok = 1 if ($rl =~ /^[ \+]\{/);
6486                                 $ok = 1 if ($rl =~ /\{/ && $n == 0);
6487                                 last if $rl =~ /^[ \+].*\{/;
6488                         }
6489                         if (!$ok) {
6490                                 ERROR("OPEN_BRACE",
6491                                       "open brace '{' following function definitions go on the next line\n" . $herectx);
6492                         }
6493                 }
6494
6495 # checks for new __setup's
6496                 if ($rawline =~ /\b__setup\("([^"]*)"/) {
6497                         my $name = $1;
6498
6499                         if (!grep(/$name/, @setup_docs)) {
6500                                 CHK("UNDOCUMENTED_SETUP",
6501                                     "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
6502                         }
6503                 }
6504
6505 # check for pointless casting of alloc functions
6506                 if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6507                         WARN("UNNECESSARY_CASTS",
6508                              "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6509                 }
6510
6511 # alloc style
6512 # p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6513                 if ($perl_version_ok &&
6514                     $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6515                         CHK("ALLOC_SIZEOF_STRUCT",
6516                             "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6517                 }
6518
6519 # check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6520                 if ($perl_version_ok &&
6521                     defined $stat &&
6522                     $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6523                         my $oldfunc = $3;
6524                         my $a1 = $4;
6525                         my $a2 = $10;
6526                         my $newfunc = "kmalloc_array";
6527                         $newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6528                         my $r1 = $a1;
6529                         my $r2 = $a2;
6530                         if ($a1 =~ /^sizeof\s*\S/) {
6531                                 $r1 = $a2;
6532                                 $r2 = $a1;
6533                         }
6534                         if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6535                             !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6536                                 my $cnt = statement_rawlines($stat);
6537                                 my $herectx = get_stat_here($linenr, $cnt, $here);
6538
6539                                 if (WARN("ALLOC_WITH_MULTIPLY",
6540                                          "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6541                                     $cnt == 1 &&
6542                                     $fix) {
6543                                         $fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
6544                                 }
6545                         }
6546                 }
6547
6548 # check for krealloc arg reuse
6549                 if ($perl_version_ok &&
6550                     $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6551                     $1 eq $3) {
6552                         WARN("KREALLOC_ARG_REUSE",
6553                              "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6554                 }
6555
6556 # check for alloc argument mismatch
6557                 if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6558                         WARN("ALLOC_ARRAY_ARGS",
6559                              "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6560                 }
6561
6562 # check for multiple semicolons
6563                 if ($line =~ /;\s*;\s*$/) {
6564                         if (WARN("ONE_SEMICOLON",
6565                                  "Statements terminations use 1 semicolon\n" . $herecurr) &&
6566                             $fix) {
6567                                 $fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6568                         }
6569                 }
6570
6571 # check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6572                 if ($realfile !~ m@^include/uapi/@ &&
6573                     $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6574                         my $ull = "";
6575                         $ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6576                         if (CHK("BIT_MACRO",
6577                                 "Prefer using the BIT$ull macro\n" . $herecurr) &&
6578                             $fix) {
6579                                 $fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6580                         }
6581                 }
6582
6583 # check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
6584                 if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
6585                         WARN("IS_ENABLED_CONFIG",
6586                              "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
6587                 }
6588
6589 # check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6590                 if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6591                         my $config = $1;
6592                         if (WARN("PREFER_IS_ENABLED",
6593                                  "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
6594                             $fix) {
6595                                 $fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6596                         }
6597                 }
6598
6599 # check for /* fallthrough */ like comment, prefer fallthrough;
6600                 my @fallthroughs = (
6601                         'fallthrough',
6602                         '@fallthrough@',
6603                         'lint -fallthrough[ \t]*',
6604                         'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
6605                         '(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
6606                         'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6607                         'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
6608                     );
6609                 if ($raw_comment ne '') {
6610                         foreach my $ft (@fallthroughs) {
6611                                 if ($raw_comment =~ /$ft/) {
6612                                         my $msg_level = \&WARN;
6613                                         $msg_level = \&CHK if ($file);
6614                                         &{$msg_level}("PREFER_FALLTHROUGH",
6615                                                       "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
6616                                         last;
6617                                 }
6618                         }
6619                 }
6620
6621 # check for switch/default statements without a break;
6622                 if ($perl_version_ok &&
6623                     defined $stat &&
6624                     $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6625                         my $cnt = statement_rawlines($stat);
6626                         my $herectx = get_stat_here($linenr, $cnt, $here);
6627
6628                         WARN("DEFAULT_NO_BREAK",
6629                              "switch default: should use break\n" . $herectx);
6630                 }
6631
6632 # check for gcc specific __FUNCTION__
6633                 if ($line =~ /\b__FUNCTION__\b/) {
6634                         if (WARN("USE_FUNC",
6635                                  "__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr) &&
6636                             $fix) {
6637                                 $fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6638                         }
6639                 }
6640
6641 # check for uses of __DATE__, __TIME__, __TIMESTAMP__
6642                 while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6643                         ERROR("DATE_TIME",
6644                               "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6645                 }
6646
6647 # check for use of yield()
6648                 if ($line =~ /\byield\s*\(\s*\)/) {
6649                         WARN("YIELD",
6650                              "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n"  . $herecurr);
6651                 }
6652
6653 # check for comparisons against true and false
6654                 if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6655                         my $lead = $1;
6656                         my $arg = $2;
6657                         my $test = $3;
6658                         my $otype = $4;
6659                         my $trail = $5;
6660                         my $op = "!";
6661
6662                         ($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6663
6664                         my $type = lc($otype);
6665                         if ($type =~ /^(?:true|false)$/) {
6666                                 if (("$test" eq "==" && "$type" eq "true") ||
6667                                     ("$test" eq "!=" && "$type" eq "false")) {
6668                                         $op = "";
6669                                 }
6670
6671                                 CHK("BOOL_COMPARISON",
6672                                     "Using comparison to $otype is error prone\n" . $herecurr);
6673
6674 ## maybe suggesting a correct construct would better
6675 ##                                  "Using comparison to $otype is error prone.  Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6676
6677                         }
6678                 }
6679
6680 # check for semaphores initialized locked
6681                 if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6682                         WARN("CONSIDER_COMPLETION",
6683                              "consider using a completion\n" . $herecurr);
6684                 }
6685
6686 # recommend kstrto* over simple_strto* and strict_strto*
6687                 if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6688                         WARN("CONSIDER_KSTRTO",
6689                              "$1 is obsolete, use k$3 instead\n" . $herecurr);
6690                 }
6691
6692 # check for __initcall(), use device_initcall() explicitly or more appropriate function please
6693                 if ($line =~ /^.\s*__initcall\s*\(/) {
6694                         WARN("USE_DEVICE_INITCALL",
6695                              "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6696                 }
6697
6698 # check for spin_is_locked(), suggest lockdep instead
6699                 if ($line =~ /\bspin_is_locked\(/) {
6700                         WARN("USE_LOCKDEP",
6701                              "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
6702                 }
6703
6704 # check for deprecated apis
6705                 if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
6706                         my $deprecated_api = $1;
6707                         my $new_api = $deprecated_apis{$deprecated_api};
6708                         WARN("DEPRECATED_API",
6709                              "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
6710                 }
6711
6712 # check for various structs that are normally const (ops, kgdb, device_tree)
6713 # and avoid what seem like struct definitions 'struct foo {'
6714                 if (defined($const_structs) &&
6715                     $line !~ /\bconst\b/ &&
6716                     $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6717                         WARN("CONST_STRUCT",
6718                              "struct $1 should normally be const\n" . $herecurr);
6719                 }
6720
6721 # use of NR_CPUS is usually wrong
6722 # ignore definitions of NR_CPUS and usage to define arrays as likely right
6723                 if ($line =~ /\bNR_CPUS\b/ &&
6724                     $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6725                     $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6726                     $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6727                     $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6728                     $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6729                 {
6730                         WARN("NR_CPUS",
6731                              "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6732                 }
6733
6734 # Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6735                 if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6736                         ERROR("DEFINE_ARCH_HAS",
6737                               "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6738                 }
6739
6740 # likely/unlikely comparisons similar to "(likely(foo) > 0)"
6741                 if ($perl_version_ok &&
6742                     $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6743                         WARN("LIKELY_MISUSE",
6744                              "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6745                 }
6746
6747 # nested likely/unlikely calls
6748                 if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
6749                         WARN("LIKELY_MISUSE",
6750                              "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
6751                 }
6752
6753 # whine mightly about in_atomic
6754                 if ($line =~ /\bin_atomic\s*\(/) {
6755                         if ($realfile =~ m@^drivers/@) {
6756                                 ERROR("IN_ATOMIC",
6757                                       "do not use in_atomic in drivers\n" . $herecurr);
6758                         } elsif ($realfile !~ m@^kernel/@) {
6759                                 WARN("IN_ATOMIC",
6760                                      "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6761                         }
6762                 }
6763
6764 # check for mutex_trylock_recursive usage
6765                 if ($line =~ /mutex_trylock_recursive/) {
6766                         ERROR("LOCKING",
6767                               "recursive locking is bad, do not use this ever.\n" . $herecurr);
6768                 }
6769
6770 # check for lockdep_set_novalidate_class
6771                 if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6772                     $line =~ /__lockdep_no_validate__\s*\)/ ) {
6773                         if ($realfile !~ m@^kernel/lockdep@ &&
6774                             $realfile !~ m@^include/linux/lockdep@ &&
6775                             $realfile !~ m@^drivers/base/core@) {
6776                                 ERROR("LOCKDEP",
6777                                       "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6778                         }
6779                 }
6780
6781                 if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6782                     $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6783                         WARN("EXPORTED_WORLD_WRITABLE",
6784                              "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6785                 }
6786
6787 # check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6788 # and whether or not function naming is typical and if
6789 # DEVICE_ATTR permissions uses are unusual too
6790                 if ($perl_version_ok &&
6791                     defined $stat &&
6792                     $stat =~ /\bDEVICE_ATTR\s*\(\s*(\w+)\s*,\s*\(?\s*(\s*(?:${multi_mode_perms_string_search}|0[0-7]{3,3})\s*)\s*\)?\s*,\s*(\w+)\s*,\s*(\w+)\s*\)/) {
6793                         my $var = $1;
6794                         my $perms = $2;
6795                         my $show = $3;
6796                         my $store = $4;
6797                         my $octal_perms = perms_to_octal($perms);
6798                         if ($show =~ /^${var}_show$/ &&
6799                             $store =~ /^${var}_store$/ &&
6800                             $octal_perms eq "0644") {
6801                                 if (WARN("DEVICE_ATTR_RW",
6802                                          "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6803                                     $fix) {
6804                                         $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6805                                 }
6806                         } elsif ($show =~ /^${var}_show$/ &&
6807                                  $store =~ /^NULL$/ &&
6808                                  $octal_perms eq "0444") {
6809                                 if (WARN("DEVICE_ATTR_RO",
6810                                          "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6811                                     $fix) {
6812                                         $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6813                                 }
6814                         } elsif ($show =~ /^NULL$/ &&
6815                                  $store =~ /^${var}_store$/ &&
6816                                  $octal_perms eq "0200") {
6817                                 if (WARN("DEVICE_ATTR_WO",
6818                                          "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6819                                     $fix) {
6820                                         $fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6821                                 }
6822                         } elsif ($octal_perms eq "0644" ||
6823                                  $octal_perms eq "0444" ||
6824                                  $octal_perms eq "0200") {
6825                                 my $newshow = "$show";
6826                                 $newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6827                                 my $newstore = $store;
6828                                 $newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6829                                 my $rename = "";
6830                                 if ($show ne $newshow) {
6831                                         $rename .= " '$show' to '$newshow'";
6832                                 }
6833                                 if ($store ne $newstore) {
6834                                         $rename .= " '$store' to '$newstore'";
6835                                 }
6836                                 WARN("DEVICE_ATTR_FUNCTIONS",
6837                                      "Consider renaming function(s)$rename\n" . $herecurr);
6838                         } else {
6839                                 WARN("DEVICE_ATTR_PERMS",
6840                                      "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6841                         }
6842                 }
6843
6844 # Mode permission misuses where it seems decimal should be octal
6845 # This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6846 # o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6847 #   specific definition of not visible in sysfs.
6848 # o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6849 #   use the default permissions
6850                 if ($perl_version_ok &&
6851                     defined $stat &&
6852                     $line =~ /$mode_perms_search/) {
6853                         foreach my $entry (@mode_permission_funcs) {
6854                                 my $func = $entry->[0];
6855                                 my $arg_pos = $entry->[1];
6856
6857                                 my $lc = $stat =~ tr@\n@@;
6858                                 $lc = $lc + $linenr;
6859                                 my $stat_real = get_stat_real($linenr, $lc);
6860
6861                                 my $skip_args = "";
6862                                 if ($arg_pos > 1) {
6863                                         $arg_pos--;
6864                                         $skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6865                                 }
6866                                 my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6867                                 if ($stat =~ /$test/) {
6868                                         my $val = $1;
6869                                         $val = $6 if ($skip_args ne "");
6870                                         if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6871                                             (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6872                                              ($val =~ /^$Octal$/ && length($val) ne 4))) {
6873                                                 ERROR("NON_OCTAL_PERMISSIONS",
6874                                                       "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6875                                         }
6876                                         if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6877                                                 ERROR("EXPORTED_WORLD_WRITABLE",
6878                                                       "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6879                                         }
6880                                 }
6881                         }
6882                 }
6883
6884 # check for uses of S_<PERMS> that could be octal for readability
6885                 while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6886                         my $oval = $1;
6887                         my $octal = perms_to_octal($oval);
6888                         if (WARN("SYMBOLIC_PERMS",
6889                                  "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6890                             $fix) {
6891                                 $fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6892                         }
6893                 }
6894
6895 # validate content of MODULE_LICENSE against list from include/linux/module.h
6896                 if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6897                         my $extracted_string = get_quoted_string($line, $rawline);
6898                         my $valid_licenses = qr{
6899                                                 GPL|
6900                                                 GPL\ v2|
6901                                                 GPL\ and\ additional\ rights|
6902                                                 Dual\ BSD/GPL|
6903                                                 Dual\ MIT/GPL|
6904                                                 Dual\ MPL/GPL|
6905                                                 Proprietary
6906                                         }x;
6907                         if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6908                                 WARN("MODULE_LICENSE",
6909                                      "unknown module license " . $extracted_string . "\n" . $herecurr);
6910                         }
6911                 }
6912
6913 # check for sysctl duplicate constants
6914                 if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
6915                         WARN("DUPLICATED_SYSCTL_CONST",
6916                                 "duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
6917                 }
6918         }
6919
6920         # If we have no input at all, then there is nothing to report on
6921         # so just keep quiet.
6922         if ($#rawlines == -1) {
6923                 exit(0);
6924         }
6925
6926         # In mailback mode only produce a report in the negative, for
6927         # things that appear to be patches.
6928         if ($mailback && ($clean == 1 || !$is_patch)) {
6929                 exit(0);
6930         }
6931
6932         # This is not a patch, and we are are in 'no-patch' mode so
6933         # just keep quiet.
6934         if (!$chk_patch && !$is_patch) {
6935                 exit(0);
6936         }
6937
6938         if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6939                 ERROR("NOT_UNIFIED_DIFF",
6940                       "Does not appear to be a unified-diff format patch\n");
6941         }
6942         if ($is_patch && $has_commit_log && $chk_signoff) {
6943                 if ($signoff == 0) {
6944                         ERROR("MISSING_SIGN_OFF",
6945                               "Missing Signed-off-by: line(s)\n");
6946                 } elsif (!$authorsignoff) {
6947                         WARN("NO_AUTHOR_SIGN_OFF",
6948                              "Missing Signed-off-by: line by nominal patch author '$author'\n");
6949                 }
6950         }
6951
6952         print report_dump();
6953         if ($summary && !($clean == 1 && $quiet == 1)) {
6954                 print "$filename " if ($summary_file);
6955                 print "total: $cnt_error errors, $cnt_warn warnings, " .
6956                         (($check)? "$cnt_chk checks, " : "") .
6957                         "$cnt_lines lines checked\n";
6958         }
6959
6960         if ($quiet == 0) {
6961                 # If there were any defects found and not already fixing them
6962                 if (!$clean and !$fix) {
6963                         print << "EOM"
6964
6965 NOTE: For some of the reported defects, checkpatch may be able to
6966       mechanically convert to the typical style using --fix or --fix-inplace.
6967 EOM
6968                 }
6969                 # If there were whitespace errors which cleanpatch can fix
6970                 # then suggest that.
6971                 if ($rpt_cleaners) {
6972                         $rpt_cleaners = 0;
6973                         print << "EOM"
6974
6975 NOTE: Whitespace errors detected.
6976       You may wish to use scripts/cleanpatch or scripts/cleanfile
6977 EOM
6978                 }
6979         }
6980
6981         if ($clean == 0 && $fix &&
6982             ("@rawlines" ne "@fixed" ||
6983              $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6984                 my $newfile = $filename;
6985                 $newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6986                 my $linecount = 0;
6987                 my $f;
6988
6989                 @fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6990
6991                 open($f, '>', $newfile)
6992                     or die "$P: Can't open $newfile for write\n";
6993                 foreach my $fixed_line (@fixed) {
6994                         $linecount++;
6995                         if ($file) {
6996                                 if ($linecount > 3) {
6997                                         $fixed_line =~ s/^\+//;
6998                                         print $f $fixed_line . "\n";
6999                                 }
7000                         } else {
7001                                 print $f $fixed_line . "\n";
7002                         }
7003                 }
7004                 close($f);
7005
7006                 if (!$quiet) {
7007                         print << "EOM";
7008
7009 Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7010
7011 Do _NOT_ trust the results written to this file.
7012 Do _NOT_ submit these changes without inspecting them for correctness.
7013
7014 This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7015 No warranties, expressed or implied...
7016 EOM
7017                 }
7018         }
7019
7020         if ($quiet == 0) {
7021                 print "\n";
7022                 if ($clean == 1) {
7023                         print "$vname has no obvious style problems and is ready for submission.\n";
7024                 } else {
7025                         print "$vname has style problems, please review.\n";
7026                 }
7027         }
7028         return $clean;
7029 }