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