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