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