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