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