OSDN Git Service

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