xref: /openbmc/qemu/scripts/checkpatch.pl (revision bfb27e60)
1#!/usr/bin/perl -w
2# (c) 2001, Dave Jones. (the file handling bit)
3# (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
4# (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
5# (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
6# Licensed under the terms of the GNU GPL License version 2
7
8use strict;
9
10my $P = $0;
11$P =~ s@.*/@@g;
12
13my $V = '0.31';
14
15use Getopt::Long qw(:config no_auto_abbrev);
16
17my $quiet = 0;
18my $tree = 1;
19my $chk_signoff = 1;
20my $chk_patch = 1;
21my $tst_only;
22my $emacs = 0;
23my $terse = 0;
24my $file = 0;
25my $check = 0;
26my $summary = 1;
27my $mailback = 0;
28my $summary_file = 0;
29my $root;
30my %debug;
31my $help = 0;
32
33sub help {
34	my ($exitcode) = @_;
35
36	print << "EOM";
37Usage: $P [OPTION]... [FILE]...
38Version: $V
39
40Options:
41  -q, --quiet                quiet
42  --no-tree                  run without a kernel tree
43  --no-signoff               do not check for 'Signed-off-by' line
44  --patch                    treat FILE as patchfile (default)
45  --emacs                    emacs compile window format
46  --terse                    one line per report
47  -f, --file                 treat FILE as regular source file
48  --subjective, --strict     enable more subjective tests
49  --root=PATH                PATH to the kernel tree root
50  --no-summary               suppress the per-file summary
51  --mailback                 only produce a report in case of warnings/errors
52  --summary-file             include the filename in summary
53  --debug KEY=[0|1]          turn on/off debugging of KEY, where KEY is one of
54                             'values', 'possible', 'type', and 'attr' (default
55                             is all off)
56  --test-only=WORD           report only warnings/errors containing WORD
57                             literally
58  -h, --help, --version      display this help and exit
59
60When FILE is - read standard input.
61EOM
62
63	exit($exitcode);
64}
65
66GetOptions(
67	'q|quiet+'	=> \$quiet,
68	'tree!'		=> \$tree,
69	'signoff!'	=> \$chk_signoff,
70	'patch!'	=> \$chk_patch,
71	'emacs!'	=> \$emacs,
72	'terse!'	=> \$terse,
73	'f|file!'	=> \$file,
74	'subjective!'	=> \$check,
75	'strict!'	=> \$check,
76	'root=s'	=> \$root,
77	'summary!'	=> \$summary,
78	'mailback!'	=> \$mailback,
79	'summary-file!'	=> \$summary_file,
80
81	'debug=s'	=> \%debug,
82	'test-only=s'	=> \$tst_only,
83	'h|help'	=> \$help,
84	'version'	=> \$help
85) or help(1);
86
87help(0) if ($help);
88
89my $exit = 0;
90
91if ($#ARGV < 0) {
92	print "$P: no input files\n";
93	exit(1);
94}
95
96my $dbg_values = 0;
97my $dbg_possible = 0;
98my $dbg_type = 0;
99my $dbg_attr = 0;
100my $dbg_adv_dcs = 0;
101my $dbg_adv_checking = 0;
102my $dbg_adv_apw = 0;
103for my $key (keys %debug) {
104	## no critic
105	eval "\${dbg_$key} = '$debug{$key}';";
106	die "$@" if ($@);
107}
108
109my $rpt_cleaners = 0;
110
111if ($terse) {
112	$emacs = 1;
113	$quiet++;
114}
115
116if ($tree) {
117	if (defined $root) {
118		if (!top_of_kernel_tree($root)) {
119			die "$P: $root: --root does not point at a valid tree\n";
120		}
121	} else {
122		if (top_of_kernel_tree('.')) {
123			$root = '.';
124		} elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
125						top_of_kernel_tree($1)) {
126			$root = $1;
127		}
128	}
129
130	if (!defined $root) {
131		print "Must be run from the top-level dir. of a kernel tree\n";
132		exit(2);
133	}
134}
135
136my $emitted_corrupt = 0;
137
138our $Ident	= qr{
139			[A-Za-z_][A-Za-z\d_]*
140			(?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
141		}x;
142our $Storage	= qr{extern|static|asmlinkage};
143our $Sparse	= qr{
144			__user|
145			__kernel|
146			__force|
147			__iomem|
148			__must_check|
149			__init_refok|
150			__kprobes|
151			__ref
152		}x;
153
154# Notes to $Attribute:
155# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
156our $Attribute	= qr{
157			const|
158			__percpu|
159			__nocast|
160			__safe|
161			__bitwise__|
162			__packed__|
163			__packed2__|
164			__naked|
165			__maybe_unused|
166			__always_unused|
167			__noreturn|
168			__used|
169			__cold|
170			__noclone|
171			__deprecated|
172			__read_mostly|
173			__kprobes|
174			__(?:mem|cpu|dev|)(?:initdata|initconst|init\b)|
175			____cacheline_aligned|
176			____cacheline_aligned_in_smp|
177			____cacheline_internodealigned_in_smp|
178			__weak
179		  }x;
180our $Modifier;
181our $Inline	= qr{inline|__always_inline|noinline};
182our $Member	= qr{->$Ident|\.$Ident|\[[^]]*\]};
183our $Lval	= qr{$Ident(?:$Member)*};
184
185our $Constant	= qr{(?:[0-9]+|0x[0-9a-fA-F]+)[UL]*};
186our $Assignment	= qr{(?:\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=)};
187our $Compare    = qr{<=|>=|==|!=|<|>};
188our $Operators	= qr{
189			<=|>=|==|!=|
190			=>|->|<<|>>|<|>|!|~|
191			&&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%
192		  }x;
193
194our $NonptrType;
195our $Type;
196our $Declare;
197
198our $UTF8	= qr {
199	[\x09\x0A\x0D\x20-\x7E]              # ASCII
200	| [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
201	|  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
202	| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
203	|  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
204	|  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
205	| [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
206	|  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
207}x;
208
209# There are still some false positives, but this catches most
210# common cases.
211our $typeTypedefs = qr{(?x:
212        [A-Z][A-Z\d_]*[a-z][A-Za-z\d_]*     # camelcase
213        | [A-Z][A-Z\d_]*AIOCB               # all uppercase
214        | [A-Z][A-Z\d_]*CPU                 # all uppercase
215        | QEMUBH                            # all uppercase
216)};
217
218our $logFunctions = qr{(?x:
219	printk|
220	pr_(debug|dbg|vdbg|devel|info|warning|err|notice|alert|crit|emerg|cont)|
221	(dev|netdev|netif)_(printk|dbg|vdbg|info|warn|err|notice|alert|crit|emerg|WARN)|
222	WARN|
223	panic
224)};
225
226our @typeList = (
227	qr{void},
228	qr{(?:unsigned\s+)?char},
229	qr{(?:unsigned\s+)?short},
230	qr{(?:unsigned\s+)?int},
231	qr{(?:unsigned\s+)?long},
232	qr{(?:unsigned\s+)?long\s+int},
233	qr{(?:unsigned\s+)?long\s+long},
234	qr{(?:unsigned\s+)?long\s+long\s+int},
235	qr{unsigned},
236	qr{float},
237	qr{double},
238	qr{bool},
239	qr{struct\s+$Ident},
240	qr{union\s+$Ident},
241	qr{enum\s+$Ident},
242	qr{${Ident}_t},
243	qr{${Ident}_handler},
244	qr{${Ident}_handler_fn},
245);
246our @modifierList = (
247	qr{fastcall},
248);
249
250our $allowed_asm_includes = qr{(?x:
251	irq|
252	memory
253)};
254# memory.h: ARM has a custom one
255
256sub build_types {
257	my $mods = "(?x:  \n" . join("|\n  ", @modifierList) . "\n)";
258	my $all = "(?x:  \n" . join("|\n  ", @typeList) . "\n)";
259	$Modifier	= qr{(?:$Attribute|$Sparse|$mods)};
260	$NonptrType	= qr{
261			(?:$Modifier\s+|const\s+)*
262			(?:
263				(?:typeof|__typeof__)\s*\(\s*\**\s*$Ident\s*\)|
264				(?:$typeTypedefs\b)|
265				(?:${all}\b)
266			)
267			(?:\s+$Modifier|\s+const)*
268		  }x;
269	$Type	= qr{
270			$NonptrType
271			(?:[\s\*]+\s*const|[\s\*]+|(?:\s*\[\s*\])+)?
272			(?:\s+$Inline|\s+$Modifier)*
273		  }x;
274	$Declare	= qr{(?:$Storage\s+)?$Type};
275}
276build_types();
277
278$chk_signoff = 0 if ($file);
279
280my @dep_includes = ();
281my @dep_functions = ();
282my $removal = "Documentation/feature-removal-schedule.txt";
283if ($tree && -f "$root/$removal") {
284	open(my $REMOVE, '<', "$root/$removal") ||
285				die "$P: $removal: open failed - $!\n";
286	while (<$REMOVE>) {
287		if (/^Check:\s+(.*\S)/) {
288			for my $entry (split(/[, ]+/, $1)) {
289				if ($entry =~ m@include/(.*)@) {
290					push(@dep_includes, $1);
291
292				} elsif ($entry !~ m@/@) {
293					push(@dep_functions, $entry);
294				}
295			}
296		}
297	}
298	close($REMOVE);
299}
300
301my @rawlines = ();
302my @lines = ();
303my $vname;
304for my $filename (@ARGV) {
305	my $FILE;
306	if ($file) {
307		open($FILE, '-|', "diff -u /dev/null $filename") ||
308			die "$P: $filename: diff failed - $!\n";
309	} elsif ($filename eq '-') {
310		open($FILE, '<&STDIN');
311	} else {
312		open($FILE, '<', "$filename") ||
313			die "$P: $filename: open failed - $!\n";
314	}
315	if ($filename eq '-') {
316		$vname = 'Your patch';
317	} else {
318		$vname = $filename;
319	}
320	while (<$FILE>) {
321		chomp;
322		push(@rawlines, $_);
323	}
324	close($FILE);
325	if (!process($filename)) {
326		$exit = 1;
327	}
328	@rawlines = ();
329	@lines = ();
330}
331
332exit($exit);
333
334sub top_of_kernel_tree {
335	my ($root) = @_;
336
337	my @tree_check = (
338		"COPYING", "MAINTAINERS", "Makefile",
339		"README", "docs", "VERSION",
340		"vl.c"
341	);
342
343	foreach my $check (@tree_check) {
344		if (! -e $root . '/' . $check) {
345			return 0;
346		}
347	}
348	return 1;
349}
350
351sub expand_tabs {
352	my ($str) = @_;
353
354	my $res = '';
355	my $n = 0;
356	for my $c (split(//, $str)) {
357		if ($c eq "\t") {
358			$res .= ' ';
359			$n++;
360			for (; ($n % 8) != 0; $n++) {
361				$res .= ' ';
362			}
363			next;
364		}
365		$res .= $c;
366		$n++;
367	}
368
369	return $res;
370}
371sub copy_spacing {
372	(my $res = shift) =~ tr/\t/ /c;
373	return $res;
374}
375
376sub line_stats {
377	my ($line) = @_;
378
379	# Drop the diff line leader and expand tabs
380	$line =~ s/^.//;
381	$line = expand_tabs($line);
382
383	# Pick the indent from the front of the line.
384	my ($white) = ($line =~ /^(\s*)/);
385
386	return (length($line), length($white));
387}
388
389my $sanitise_quote = '';
390
391sub sanitise_line_reset {
392	my ($in_comment) = @_;
393
394	if ($in_comment) {
395		$sanitise_quote = '*/';
396	} else {
397		$sanitise_quote = '';
398	}
399}
400sub sanitise_line {
401	my ($line) = @_;
402
403	my $res = '';
404	my $l = '';
405
406	my $qlen = 0;
407	my $off = 0;
408	my $c;
409
410	# Always copy over the diff marker.
411	$res = substr($line, 0, 1);
412
413	for ($off = 1; $off < length($line); $off++) {
414		$c = substr($line, $off, 1);
415
416		# Comments we are wacking completly including the begin
417		# and end, all to $;.
418		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
419			$sanitise_quote = '*/';
420
421			substr($res, $off, 2, "$;$;");
422			$off++;
423			next;
424		}
425		if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
426			$sanitise_quote = '';
427			substr($res, $off, 2, "$;$;");
428			$off++;
429			next;
430		}
431		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
432			$sanitise_quote = '//';
433
434			substr($res, $off, 2, $sanitise_quote);
435			$off++;
436			next;
437		}
438
439		# A \ in a string means ignore the next character.
440		if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
441		    $c eq "\\") {
442			substr($res, $off, 2, 'XX');
443			$off++;
444			next;
445		}
446		# Regular quotes.
447		if ($c eq "'" || $c eq '"') {
448			if ($sanitise_quote eq '') {
449				$sanitise_quote = $c;
450
451				substr($res, $off, 1, $c);
452				next;
453			} elsif ($sanitise_quote eq $c) {
454				$sanitise_quote = '';
455			}
456		}
457
458		#print "c<$c> SQ<$sanitise_quote>\n";
459		if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
460			substr($res, $off, 1, $;);
461		} elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
462			substr($res, $off, 1, $;);
463		} elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
464			substr($res, $off, 1, 'X');
465		} else {
466			substr($res, $off, 1, $c);
467		}
468	}
469
470	if ($sanitise_quote eq '//') {
471		$sanitise_quote = '';
472	}
473
474	# The pathname on a #include may be surrounded by '<' and '>'.
475	if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
476		my $clean = 'X' x length($1);
477		$res =~ s@\<.*\>@<$clean>@;
478
479	# The whole of a #error is a string.
480	} elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
481		my $clean = 'X' x length($1);
482		$res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
483	}
484
485	return $res;
486}
487
488sub ctx_statement_block {
489	my ($linenr, $remain, $off) = @_;
490	my $line = $linenr - 1;
491	my $blk = '';
492	my $soff = $off;
493	my $coff = $off - 1;
494	my $coff_set = 0;
495
496	my $loff = 0;
497
498	my $type = '';
499	my $level = 0;
500	my @stack = ();
501	my $p;
502	my $c;
503	my $len = 0;
504
505	my $remainder;
506	while (1) {
507		@stack = (['', 0]) if ($#stack == -1);
508
509		#warn "CSB: blk<$blk> remain<$remain>\n";
510		# If we are about to drop off the end, pull in more
511		# context.
512		if ($off >= $len) {
513			for (; $remain > 0; $line++) {
514				last if (!defined $lines[$line]);
515				next if ($lines[$line] =~ /^-/);
516				$remain--;
517				$loff = $len;
518				$blk .= $lines[$line] . "\n";
519				$len = length($blk);
520				$line++;
521				last;
522			}
523			# Bail if there is no further context.
524			#warn "CSB: blk<$blk> off<$off> len<$len>\n";
525			if ($off >= $len) {
526				last;
527			}
528		}
529		$p = $c;
530		$c = substr($blk, $off, 1);
531		$remainder = substr($blk, $off);
532
533		#warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
534
535		# Handle nested #if/#else.
536		if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
537			push(@stack, [ $type, $level ]);
538		} elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
539			($type, $level) = @{$stack[$#stack - 1]};
540		} elsif ($remainder =~ /^#\s*endif\b/) {
541			($type, $level) = @{pop(@stack)};
542		}
543
544		# Statement ends at the ';' or a close '}' at the
545		# outermost level.
546		if ($level == 0 && $c eq ';') {
547			last;
548		}
549
550		# An else is really a conditional as long as its not else if
551		if ($level == 0 && $coff_set == 0 &&
552				(!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
553				$remainder =~ /^(else)(?:\s|{)/ &&
554				$remainder !~ /^else\s+if\b/) {
555			$coff = $off + length($1) - 1;
556			$coff_set = 1;
557			#warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
558			#warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
559		}
560
561		if (($type eq '' || $type eq '(') && $c eq '(') {
562			$level++;
563			$type = '(';
564		}
565		if ($type eq '(' && $c eq ')') {
566			$level--;
567			$type = ($level != 0)? '(' : '';
568
569			if ($level == 0 && $coff < $soff) {
570				$coff = $off;
571				$coff_set = 1;
572				#warn "CSB: mark coff<$coff>\n";
573			}
574		}
575		if (($type eq '' || $type eq '{') && $c eq '{') {
576			$level++;
577			$type = '{';
578		}
579		if ($type eq '{' && $c eq '}') {
580			$level--;
581			$type = ($level != 0)? '{' : '';
582
583			if ($level == 0) {
584				if (substr($blk, $off + 1, 1) eq ';') {
585					$off++;
586				}
587				last;
588			}
589		}
590		$off++;
591	}
592	# We are truly at the end, so shuffle to the next line.
593	if ($off == $len) {
594		$loff = $len + 1;
595		$line++;
596		$remain--;
597	}
598
599	my $statement = substr($blk, $soff, $off - $soff + 1);
600	my $condition = substr($blk, $soff, $coff - $soff + 1);
601
602	#warn "STATEMENT<$statement>\n";
603	#warn "CONDITION<$condition>\n";
604
605	#print "coff<$coff> soff<$off> loff<$loff>\n";
606
607	return ($statement, $condition,
608			$line, $remain + 1, $off - $loff + 1, $level);
609}
610
611sub statement_lines {
612	my ($stmt) = @_;
613
614	# Strip the diff line prefixes and rip blank lines at start and end.
615	$stmt =~ s/(^|\n)./$1/g;
616	$stmt =~ s/^\s*//;
617	$stmt =~ s/\s*$//;
618
619	my @stmt_lines = ($stmt =~ /\n/g);
620
621	return $#stmt_lines + 2;
622}
623
624sub statement_rawlines {
625	my ($stmt) = @_;
626
627	my @stmt_lines = ($stmt =~ /\n/g);
628
629	return $#stmt_lines + 2;
630}
631
632sub statement_block_size {
633	my ($stmt) = @_;
634
635	$stmt =~ s/(^|\n)./$1/g;
636	$stmt =~ s/^\s*{//;
637	$stmt =~ s/}\s*$//;
638	$stmt =~ s/^\s*//;
639	$stmt =~ s/\s*$//;
640
641	my @stmt_lines = ($stmt =~ /\n/g);
642	my @stmt_statements = ($stmt =~ /;/g);
643
644	my $stmt_lines = $#stmt_lines + 2;
645	my $stmt_statements = $#stmt_statements + 1;
646
647	if ($stmt_lines > $stmt_statements) {
648		return $stmt_lines;
649	} else {
650		return $stmt_statements;
651	}
652}
653
654sub ctx_statement_full {
655	my ($linenr, $remain, $off) = @_;
656	my ($statement, $condition, $level);
657
658	my (@chunks);
659
660	# Grab the first conditional/block pair.
661	($statement, $condition, $linenr, $remain, $off, $level) =
662				ctx_statement_block($linenr, $remain, $off);
663	#print "F: c<$condition> s<$statement> remain<$remain>\n";
664	push(@chunks, [ $condition, $statement ]);
665	if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
666		return ($level, $linenr, @chunks);
667	}
668
669	# Pull in the following conditional/block pairs and see if they
670	# could continue the statement.
671	for (;;) {
672		($statement, $condition, $linenr, $remain, $off, $level) =
673				ctx_statement_block($linenr, $remain, $off);
674		#print "C: c<$condition> s<$statement> remain<$remain>\n";
675		last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
676		#print "C: push\n";
677		push(@chunks, [ $condition, $statement ]);
678	}
679
680	return ($level, $linenr, @chunks);
681}
682
683sub ctx_block_get {
684	my ($linenr, $remain, $outer, $open, $close, $off) = @_;
685	my $line;
686	my $start = $linenr - 1;
687	my $blk = '';
688	my @o;
689	my @c;
690	my @res = ();
691
692	my $level = 0;
693	my @stack = ($level);
694	for ($line = $start; $remain > 0; $line++) {
695		next if ($rawlines[$line] =~ /^-/);
696		$remain--;
697
698		$blk .= $rawlines[$line];
699
700		# Handle nested #if/#else.
701		if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
702			push(@stack, $level);
703		} elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
704			$level = $stack[$#stack - 1];
705		} elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
706			$level = pop(@stack);
707		}
708
709		foreach my $c (split(//, $lines[$line])) {
710			##print "C<$c>L<$level><$open$close>O<$off>\n";
711			if ($off > 0) {
712				$off--;
713				next;
714			}
715
716			if ($c eq $close && $level > 0) {
717				$level--;
718				last if ($level == 0);
719			} elsif ($c eq $open) {
720				$level++;
721			}
722		}
723
724		if (!$outer || $level <= 1) {
725			push(@res, $rawlines[$line]);
726		}
727
728		last if ($level == 0);
729	}
730
731	return ($level, @res);
732}
733sub ctx_block_outer {
734	my ($linenr, $remain) = @_;
735
736	my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
737	return @r;
738}
739sub ctx_block {
740	my ($linenr, $remain) = @_;
741
742	my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
743	return @r;
744}
745sub ctx_statement {
746	my ($linenr, $remain, $off) = @_;
747
748	my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
749	return @r;
750}
751sub ctx_block_level {
752	my ($linenr, $remain) = @_;
753
754	return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
755}
756sub ctx_statement_level {
757	my ($linenr, $remain, $off) = @_;
758
759	return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
760}
761
762sub ctx_locate_comment {
763	my ($first_line, $end_line) = @_;
764
765	# Catch a comment on the end of the line itself.
766	my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
767	return $current_comment if (defined $current_comment);
768
769	# Look through the context and try and figure out if there is a
770	# comment.
771	my $in_comment = 0;
772	$current_comment = '';
773	for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
774		my $line = $rawlines[$linenr - 1];
775		#warn "           $line\n";
776		if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
777			$in_comment = 1;
778		}
779		if ($line =~ m@/\*@) {
780			$in_comment = 1;
781		}
782		if (!$in_comment && $current_comment ne '') {
783			$current_comment = '';
784		}
785		$current_comment .= $line . "\n" if ($in_comment);
786		if ($line =~ m@\*/@) {
787			$in_comment = 0;
788		}
789	}
790
791	chomp($current_comment);
792	return($current_comment);
793}
794sub ctx_has_comment {
795	my ($first_line, $end_line) = @_;
796	my $cmt = ctx_locate_comment($first_line, $end_line);
797
798	##print "LINE: $rawlines[$end_line - 1 ]\n";
799	##print "CMMT: $cmt\n";
800
801	return ($cmt ne '');
802}
803
804sub raw_line {
805	my ($linenr, $cnt) = @_;
806
807	my $offset = $linenr - 1;
808	$cnt++;
809
810	my $line;
811	while ($cnt) {
812		$line = $rawlines[$offset++];
813		next if (defined($line) && $line =~ /^-/);
814		$cnt--;
815	}
816
817	return $line;
818}
819
820sub cat_vet {
821	my ($vet) = @_;
822	my ($res, $coded);
823
824	$res = '';
825	while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
826		$res .= $1;
827		if ($2 ne '') {
828			$coded = sprintf("^%c", unpack('C', $2) + 64);
829			$res .= $coded;
830		}
831	}
832	$res =~ s/$/\$/;
833
834	return $res;
835}
836
837my $av_preprocessor = 0;
838my $av_pending;
839my @av_paren_type;
840my $av_pend_colon;
841
842sub annotate_reset {
843	$av_preprocessor = 0;
844	$av_pending = '_';
845	@av_paren_type = ('E');
846	$av_pend_colon = 'O';
847}
848
849sub annotate_values {
850	my ($stream, $type) = @_;
851
852	my $res;
853	my $var = '_' x length($stream);
854	my $cur = $stream;
855
856	print "$stream\n" if ($dbg_values > 1);
857
858	while (length($cur)) {
859		@av_paren_type = ('E') if ($#av_paren_type < 0);
860		print " <" . join('', @av_paren_type) .
861				"> <$type> <$av_pending>" if ($dbg_values > 1);
862		if ($cur =~ /^(\s+)/o) {
863			print "WS($1)\n" if ($dbg_values > 1);
864			if ($1 =~ /\n/ && $av_preprocessor) {
865				$type = pop(@av_paren_type);
866				$av_preprocessor = 0;
867			}
868
869		} elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
870			print "CAST($1)\n" if ($dbg_values > 1);
871			push(@av_paren_type, $type);
872			$type = 'C';
873
874		} elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
875			print "DECLARE($1)\n" if ($dbg_values > 1);
876			$type = 'T';
877
878		} elsif ($cur =~ /^($Modifier)\s*/) {
879			print "MODIFIER($1)\n" if ($dbg_values > 1);
880			$type = 'T';
881
882		} elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
883			print "DEFINE($1,$2)\n" if ($dbg_values > 1);
884			$av_preprocessor = 1;
885			push(@av_paren_type, $type);
886			if ($2 ne '') {
887				$av_pending = 'N';
888			}
889			$type = 'E';
890
891		} elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
892			print "UNDEF($1)\n" if ($dbg_values > 1);
893			$av_preprocessor = 1;
894			push(@av_paren_type, $type);
895
896		} elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
897			print "PRE_START($1)\n" if ($dbg_values > 1);
898			$av_preprocessor = 1;
899
900			push(@av_paren_type, $type);
901			push(@av_paren_type, $type);
902			$type = 'E';
903
904		} elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
905			print "PRE_RESTART($1)\n" if ($dbg_values > 1);
906			$av_preprocessor = 1;
907
908			push(@av_paren_type, $av_paren_type[$#av_paren_type]);
909
910			$type = 'E';
911
912		} elsif ($cur =~ /^(\#\s*(?:endif))/o) {
913			print "PRE_END($1)\n" if ($dbg_values > 1);
914
915			$av_preprocessor = 1;
916
917			# Assume all arms of the conditional end as this
918			# one does, and continue as if the #endif was not here.
919			pop(@av_paren_type);
920			push(@av_paren_type, $type);
921			$type = 'E';
922
923		} elsif ($cur =~ /^(\\\n)/o) {
924			print "PRECONT($1)\n" if ($dbg_values > 1);
925
926		} elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
927			print "ATTR($1)\n" if ($dbg_values > 1);
928			$av_pending = $type;
929			$type = 'N';
930
931		} elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
932			print "SIZEOF($1)\n" if ($dbg_values > 1);
933			if (defined $2) {
934				$av_pending = 'V';
935			}
936			$type = 'N';
937
938		} elsif ($cur =~ /^(if|while|for)\b/o) {
939			print "COND($1)\n" if ($dbg_values > 1);
940			$av_pending = 'E';
941			$type = 'N';
942
943		} elsif ($cur =~/^(case)/o) {
944			print "CASE($1)\n" if ($dbg_values > 1);
945			$av_pend_colon = 'C';
946			$type = 'N';
947
948		} elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
949			print "KEYWORD($1)\n" if ($dbg_values > 1);
950			$type = 'N';
951
952		} elsif ($cur =~ /^(\()/o) {
953			print "PAREN('$1')\n" if ($dbg_values > 1);
954			push(@av_paren_type, $av_pending);
955			$av_pending = '_';
956			$type = 'N';
957
958		} elsif ($cur =~ /^(\))/o) {
959			my $new_type = pop(@av_paren_type);
960			if ($new_type ne '_') {
961				$type = $new_type;
962				print "PAREN('$1') -> $type\n"
963							if ($dbg_values > 1);
964			} else {
965				print "PAREN('$1')\n" if ($dbg_values > 1);
966			}
967
968		} elsif ($cur =~ /^($Ident)\s*\(/o) {
969			print "FUNC($1)\n" if ($dbg_values > 1);
970			$type = 'V';
971			$av_pending = 'V';
972
973		} elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
974			if (defined $2 && $type eq 'C' || $type eq 'T') {
975				$av_pend_colon = 'B';
976			} elsif ($type eq 'E') {
977				$av_pend_colon = 'L';
978			}
979			print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
980			$type = 'V';
981
982		} elsif ($cur =~ /^($Ident|$Constant)/o) {
983			print "IDENT($1)\n" if ($dbg_values > 1);
984			$type = 'V';
985
986		} elsif ($cur =~ /^($Assignment)/o) {
987			print "ASSIGN($1)\n" if ($dbg_values > 1);
988			$type = 'N';
989
990		} elsif ($cur =~/^(;|{|})/) {
991			print "END($1)\n" if ($dbg_values > 1);
992			$type = 'E';
993			$av_pend_colon = 'O';
994
995		} elsif ($cur =~/^(,)/) {
996			print "COMMA($1)\n" if ($dbg_values > 1);
997			$type = 'C';
998
999		} elsif ($cur =~ /^(\?)/o) {
1000			print "QUESTION($1)\n" if ($dbg_values > 1);
1001			$type = 'N';
1002
1003		} elsif ($cur =~ /^(:)/o) {
1004			print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1005
1006			substr($var, length($res), 1, $av_pend_colon);
1007			if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1008				$type = 'E';
1009			} else {
1010				$type = 'N';
1011			}
1012			$av_pend_colon = 'O';
1013
1014		} elsif ($cur =~ /^(\[)/o) {
1015			print "CLOSE($1)\n" if ($dbg_values > 1);
1016			$type = 'N';
1017
1018		} elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1019			my $variant;
1020
1021			print "OPV($1)\n" if ($dbg_values > 1);
1022			if ($type eq 'V') {
1023				$variant = 'B';
1024			} else {
1025				$variant = 'U';
1026			}
1027
1028			substr($var, length($res), 1, $variant);
1029			$type = 'N';
1030
1031		} elsif ($cur =~ /^($Operators)/o) {
1032			print "OP($1)\n" if ($dbg_values > 1);
1033			if ($1 ne '++' && $1 ne '--') {
1034				$type = 'N';
1035			}
1036
1037		} elsif ($cur =~ /(^.)/o) {
1038			print "C($1)\n" if ($dbg_values > 1);
1039		}
1040		if (defined $1) {
1041			$cur = substr($cur, length($1));
1042			$res .= $type x length($1);
1043		}
1044	}
1045
1046	return ($res, $var);
1047}
1048
1049sub possible {
1050	my ($possible, $line) = @_;
1051	my $notPermitted = qr{(?:
1052		^(?:
1053			$Modifier|
1054			$Storage|
1055			$Type|
1056			DEFINE_\S+
1057		)$|
1058		^(?:
1059			goto|
1060			return|
1061			case|
1062			else|
1063			asm|__asm__|
1064			do
1065		)(?:\s|$)|
1066		^(?:typedef|struct|enum)\b
1067	    )}x;
1068	warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1069	if ($possible !~ $notPermitted) {
1070		# Check for modifiers.
1071		$possible =~ s/\s*$Storage\s*//g;
1072		$possible =~ s/\s*$Sparse\s*//g;
1073		if ($possible =~ /^\s*$/) {
1074
1075		} elsif ($possible =~ /\s/) {
1076			$possible =~ s/\s*$Type\s*//g;
1077			for my $modifier (split(' ', $possible)) {
1078				if ($modifier !~ $notPermitted) {
1079					warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1080					push(@modifierList, $modifier);
1081				}
1082			}
1083
1084		} else {
1085			warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
1086			push(@typeList, $possible);
1087		}
1088		build_types();
1089	} else {
1090		warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
1091	}
1092}
1093
1094my $prefix = '';
1095
1096sub report {
1097	if (defined $tst_only && $_[0] !~ /\Q$tst_only\E/) {
1098		return 0;
1099	}
1100	my $line = $prefix . $_[0];
1101
1102	$line = (split('\n', $line))[0] . "\n" if ($terse);
1103
1104	push(our @report, $line);
1105
1106	return 1;
1107}
1108sub report_dump {
1109	our @report;
1110}
1111sub ERROR {
1112	if (report("ERROR: $_[0]\n")) {
1113		our $clean = 0;
1114		our $cnt_error++;
1115	}
1116}
1117sub WARN {
1118	if (report("WARNING: $_[0]\n")) {
1119		our $clean = 0;
1120		our $cnt_warn++;
1121	}
1122}
1123sub CHK {
1124	if ($check && report("CHECK: $_[0]\n")) {
1125		our $clean = 0;
1126		our $cnt_chk++;
1127	}
1128}
1129
1130sub check_absolute_file {
1131	my ($absolute, $herecurr) = @_;
1132	my $file = $absolute;
1133
1134	##print "absolute<$absolute>\n";
1135
1136	# See if any suffix of this path is a path within the tree.
1137	while ($file =~ s@^[^/]*/@@) {
1138		if (-f "$root/$file") {
1139			##print "file<$file>\n";
1140			last;
1141		}
1142	}
1143	if (! -f _)  {
1144		return 0;
1145	}
1146
1147	# It is, so see if the prefix is acceptable.
1148	my $prefix = $absolute;
1149	substr($prefix, -length($file)) = '';
1150
1151	##print "prefix<$prefix>\n";
1152	if ($prefix ne ".../") {
1153		WARN("use relative pathname instead of absolute in changelog text\n" . $herecurr);
1154	}
1155}
1156
1157sub process {
1158	my $filename = shift;
1159
1160	my $linenr=0;
1161	my $prevline="";
1162	my $prevrawline="";
1163	my $stashline="";
1164	my $stashrawline="";
1165
1166	my $length;
1167	my $indent;
1168	my $previndent=0;
1169	my $stashindent=0;
1170
1171	our $clean = 1;
1172	my $signoff = 0;
1173	my $is_patch = 0;
1174
1175	our @report = ();
1176	our $cnt_lines = 0;
1177	our $cnt_error = 0;
1178	our $cnt_warn = 0;
1179	our $cnt_chk = 0;
1180
1181	# Trace the real file/line as we go.
1182	my $realfile = '';
1183	my $realline = 0;
1184	my $realcnt = 0;
1185	my $here = '';
1186	my $in_comment = 0;
1187	my $comment_edge = 0;
1188	my $first_line = 0;
1189	my $p1_prefix = '';
1190
1191	my $prev_values = 'E';
1192
1193	# suppression flags
1194	my %suppress_ifbraces;
1195	my %suppress_whiletrailers;
1196	my %suppress_export;
1197
1198	# Pre-scan the patch sanitizing the lines.
1199	# Pre-scan the patch looking for any __setup documentation.
1200	#
1201	my @setup_docs = ();
1202	my $setup_docs = 0;
1203
1204	sanitise_line_reset();
1205	my $line;
1206	foreach my $rawline (@rawlines) {
1207		$linenr++;
1208		$line = $rawline;
1209
1210		if ($rawline=~/^\+\+\+\s+(\S+)/) {
1211			$setup_docs = 0;
1212			if ($1 =~ m@Documentation/kernel-parameters.txt$@) {
1213				$setup_docs = 1;
1214			}
1215			#next;
1216		}
1217		if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1218			$realline=$1-1;
1219			if (defined $2) {
1220				$realcnt=$3+1;
1221			} else {
1222				$realcnt=1+1;
1223			}
1224			$in_comment = 0;
1225
1226			# Guestimate if this is a continuing comment.  Run
1227			# the context looking for a comment "edge".  If this
1228			# edge is a close comment then we must be in a comment
1229			# at context start.
1230			my $edge;
1231			my $cnt = $realcnt;
1232			for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
1233				next if (defined $rawlines[$ln - 1] &&
1234					 $rawlines[$ln - 1] =~ /^-/);
1235				$cnt--;
1236				#print "RAW<$rawlines[$ln - 1]>\n";
1237				last if (!defined $rawlines[$ln - 1]);
1238				if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
1239				    $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
1240					($edge) = $1;
1241					last;
1242				}
1243			}
1244			if (defined $edge && $edge eq '*/') {
1245				$in_comment = 1;
1246			}
1247
1248			# Guestimate if this is a continuing comment.  If this
1249			# is the start of a diff block and this line starts
1250			# ' *' then it is very likely a comment.
1251			if (!defined $edge &&
1252			    $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
1253			{
1254				$in_comment = 1;
1255			}
1256
1257			##print "COMMENT:$in_comment edge<$edge> $rawline\n";
1258			sanitise_line_reset($in_comment);
1259
1260		} elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
1261			# Standardise the strings and chars within the input to
1262			# simplify matching -- only bother with positive lines.
1263			$line = sanitise_line($rawline);
1264		}
1265		push(@lines, $line);
1266
1267		if ($realcnt > 1) {
1268			$realcnt-- if ($line =~ /^(?:\+| |$)/);
1269		} else {
1270			$realcnt = 0;
1271		}
1272
1273		#print "==>$rawline\n";
1274		#print "-->$line\n";
1275
1276		if ($setup_docs && $line =~ /^\+/) {
1277			push(@setup_docs, $line);
1278		}
1279	}
1280
1281	$prefix = '';
1282
1283	$realcnt = 0;
1284	$linenr = 0;
1285	foreach my $line (@lines) {
1286		$linenr++;
1287
1288		my $rawline = $rawlines[$linenr - 1];
1289
1290#extract the line range in the file after the patch is applied
1291		if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
1292			$is_patch = 1;
1293			$first_line = $linenr + 1;
1294			$realline=$1-1;
1295			if (defined $2) {
1296				$realcnt=$3+1;
1297			} else {
1298				$realcnt=1+1;
1299			}
1300			annotate_reset();
1301			$prev_values = 'E';
1302
1303			%suppress_ifbraces = ();
1304			%suppress_whiletrailers = ();
1305			%suppress_export = ();
1306			next;
1307
1308# track the line number as we move through the hunk, note that
1309# new versions of GNU diff omit the leading space on completely
1310# blank context lines so we need to count that too.
1311		} elsif ($line =~ /^( |\+|$)/) {
1312			$realline++;
1313			$realcnt-- if ($realcnt != 0);
1314
1315			# Measure the line length and indent.
1316			($length, $indent) = line_stats($rawline);
1317
1318			# Track the previous line.
1319			($prevline, $stashline) = ($stashline, $line);
1320			($previndent, $stashindent) = ($stashindent, $indent);
1321			($prevrawline, $stashrawline) = ($stashrawline, $rawline);
1322
1323			#warn "line<$line>\n";
1324
1325		} elsif ($realcnt == 1) {
1326			$realcnt--;
1327		}
1328
1329		my $hunk_line = ($realcnt != 0);
1330
1331#make up the handle for any error we report on this line
1332		$prefix = "$filename:$realline: " if ($emacs && $file);
1333		$prefix = "$filename:$linenr: " if ($emacs && !$file);
1334
1335		$here = "#$linenr: " if (!$file);
1336		$here = "#$realline: " if ($file);
1337
1338		# extract the filename as it passes
1339		if ($line =~ /^diff --git.*?(\S+)$/) {
1340			$realfile = $1;
1341			$realfile =~ s@^([^/]*)/@@;
1342
1343		} elsif ($line =~ /^\+\+\+\s+(\S+)/) {
1344			$realfile = $1;
1345			$realfile =~ s@^([^/]*)/@@;
1346
1347			$p1_prefix = $1;
1348			if (!$file && $tree && $p1_prefix ne '' &&
1349			    -e "$root/$p1_prefix") {
1350				WARN("patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
1351			}
1352
1353			if ($realfile =~ m@^include/asm/@) {
1354				ERROR("do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
1355			}
1356			next;
1357		}
1358
1359		$here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
1360
1361		my $hereline = "$here\n$rawline\n";
1362		my $herecurr = "$here\n$rawline\n";
1363		my $hereprev = "$here\n$prevrawline\n$rawline\n";
1364
1365		$cnt_lines++ if ($realcnt != 0);
1366
1367# Check for incorrect file permissions
1368		if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
1369			my $permhere = $here . "FILE: $realfile\n";
1370			if ($realfile =~ /(Makefile|Kconfig|\.c|\.cpp|\.h|\.S|\.tmpl)$/) {
1371				ERROR("do not set execute permissions for source files\n" . $permhere);
1372			}
1373		}
1374
1375#check the patch for a signoff:
1376		if ($line =~ /^\s*signed-off-by:/i) {
1377			# This is a signoff, if ugly, so do not double report.
1378			$signoff++;
1379			if (!($line =~ /^\s*Signed-off-by:/)) {
1380				WARN("Signed-off-by: is the preferred form\n" .
1381					$herecurr);
1382			}
1383			if ($line =~ /^\s*signed-off-by:\S/i) {
1384				WARN("space required after Signed-off-by:\n" .
1385					$herecurr);
1386			}
1387		}
1388
1389# Check for wrappage within a valid hunk of the file
1390		if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
1391			ERROR("patch seems to be corrupt (line wrapped?)\n" .
1392				$herecurr) if (!$emitted_corrupt++);
1393		}
1394
1395# Check for absolute kernel paths.
1396		if ($tree) {
1397			while ($line =~ m{(?:^|\s)(/\S*)}g) {
1398				my $file = $1;
1399
1400				if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
1401				    check_absolute_file($1, $herecurr)) {
1402					#
1403				} else {
1404					check_absolute_file($file, $herecurr);
1405				}
1406			}
1407		}
1408
1409# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
1410		if (($realfile =~ /^$/ || $line =~ /^\+/) &&
1411		    $rawline !~ m/^$UTF8*$/) {
1412			my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
1413
1414			my $blank = copy_spacing($rawline);
1415			my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
1416			my $hereptr = "$hereline$ptr\n";
1417
1418			ERROR("Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
1419		}
1420
1421# ignore non-hunk lines and lines being removed
1422		next if (!$hunk_line || $line =~ /^-/);
1423
1424#trailing whitespace
1425		if ($line =~ /^\+.*\015/) {
1426			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1427			ERROR("DOS line endings\n" . $herevet);
1428
1429		} elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
1430			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1431			ERROR("trailing whitespace\n" . $herevet);
1432			$rpt_cleaners = 1;
1433		}
1434
1435# check for Kconfig help text having a real description
1436# Only applies when adding the entry originally, after that we do not have
1437# sufficient context to determine whether it is indeed long enough.
1438		if ($realfile =~ /Kconfig/ &&
1439		    $line =~ /\+\s*(?:---)?help(?:---)?$/) {
1440			my $length = 0;
1441			my $cnt = $realcnt;
1442			my $ln = $linenr + 1;
1443			my $f;
1444			my $is_end = 0;
1445			while ($cnt > 0 && defined $lines[$ln - 1]) {
1446				$f = $lines[$ln - 1];
1447				$cnt-- if ($lines[$ln - 1] !~ /^-/);
1448				$is_end = $lines[$ln - 1] =~ /^\+/;
1449				$ln++;
1450
1451				next if ($f =~ /^-/);
1452				$f =~ s/^.//;
1453				$f =~ s/#.*//;
1454				$f =~ s/^\s+//;
1455				next if ($f =~ /^$/);
1456				if ($f =~ /^\s*config\s/) {
1457					$is_end = 1;
1458					last;
1459				}
1460				$length++;
1461			}
1462			WARN("please write a paragraph that describes the config symbol fully\n" . $herecurr) if ($is_end && $length < 4);
1463			#print "is_end<$is_end> length<$length>\n";
1464		}
1465
1466# check we are in a valid source file if not then ignore this hunk
1467		next if ($realfile !~ /\.(h|c|cpp|s|S|pl|sh)$/);
1468
1469#80 column limit
1470		if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ &&
1471		    $rawline !~ /^.\s*\*\s*\@$Ident\s/ &&
1472		    !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:,|\)\s*;)\s*$/ ||
1473		    $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) &&
1474		    $length > 80)
1475		{
1476			WARN("line over 80 characters\n" . $herecurr);
1477		}
1478
1479# check for spaces before a quoted newline
1480		if ($rawline =~ /^.*\".*\s\\n/) {
1481			WARN("unnecessary whitespace before a quoted newline\n" . $herecurr);
1482		}
1483
1484# check for adding lines without a newline.
1485		if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
1486			WARN("adding a line without newline at end of file\n" . $herecurr);
1487		}
1488
1489# Blackfin: use hi/lo macros
1490		if ($realfile =~ m@arch/blackfin/.*\.S$@) {
1491			if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) {
1492				my $herevet = "$here\n" . cat_vet($line) . "\n";
1493				ERROR("use the LO() macro, not (... & 0xFFFF)\n" . $herevet);
1494			}
1495			if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) {
1496				my $herevet = "$here\n" . cat_vet($line) . "\n";
1497				ERROR("use the HI() macro, not (... >> 16)\n" . $herevet);
1498			}
1499		}
1500
1501# check we are in a valid source file C or perl if not then ignore this hunk
1502		next if ($realfile !~ /\.(h|c|cpp|pl)$/);
1503
1504# in QEMU, no tabs are allowed
1505		if ($rawline =~ /^\+.*\t/) {
1506			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
1507			ERROR("code indent should never use tabs\n" . $herevet);
1508			$rpt_cleaners = 1;
1509		}
1510
1511# check we are in a valid C source file if not then ignore this hunk
1512		next if ($realfile !~ /\.(h|c|cpp)$/);
1513
1514# check for RCS/CVS revision markers
1515		if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
1516			WARN("CVS style keyword markers, these will _not_ be updated\n". $herecurr);
1517		}
1518
1519# Blackfin: don't use __builtin_bfin_[cs]sync
1520		if ($line =~ /__builtin_bfin_csync/) {
1521			my $herevet = "$here\n" . cat_vet($line) . "\n";
1522			ERROR("use the CSYNC() macro in asm/blackfin.h\n" . $herevet);
1523		}
1524		if ($line =~ /__builtin_bfin_ssync/) {
1525			my $herevet = "$here\n" . cat_vet($line) . "\n";
1526			ERROR("use the SSYNC() macro in asm/blackfin.h\n" . $herevet);
1527		}
1528
1529# Check for potential 'bare' types
1530		my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
1531		    $realline_next);
1532		if ($realcnt && $line =~ /.\s*\S/) {
1533			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
1534				ctx_statement_block($linenr, $realcnt, 0);
1535			$stat =~ s/\n./\n /g;
1536			$cond =~ s/\n./\n /g;
1537
1538			# Find the real next line.
1539			$realline_next = $line_nr_next;
1540			if (defined $realline_next &&
1541			    (!defined $lines[$realline_next - 1] ||
1542			     substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
1543				$realline_next++;
1544			}
1545
1546			my $s = $stat;
1547			$s =~ s/{.*$//s;
1548
1549			# Ignore goto labels.
1550			if ($s =~ /$Ident:\*$/s) {
1551
1552			# Ignore functions being called
1553			} elsif ($s =~ /^.\s*$Ident\s*\(/s) {
1554
1555			} elsif ($s =~ /^.\s*else\b/s) {
1556
1557			# declarations always start with types
1558			} 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) {
1559				my $type = $1;
1560				$type =~ s/\s+/ /g;
1561				possible($type, "A:" . $s);
1562
1563			# definitions in global scope can only start with types
1564			} elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
1565				possible($1, "B:" . $s);
1566			}
1567
1568			# any (foo ... *) is a pointer cast, and foo is a type
1569			while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
1570				possible($1, "C:" . $s);
1571			}
1572
1573			# Check for any sort of function declaration.
1574			# int foo(something bar, other baz);
1575			# void (*store_gdt)(x86_descr_ptr *);
1576			if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
1577				my ($name_len) = length($1);
1578
1579				my $ctx = $s;
1580				substr($ctx, 0, $name_len + 1, '');
1581				$ctx =~ s/\)[^\)]*$//;
1582
1583				for my $arg (split(/\s*,\s*/, $ctx)) {
1584					if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
1585
1586						possible($1, "D:" . $s);
1587					}
1588				}
1589			}
1590
1591		}
1592
1593#
1594# Checks which may be anchored in the context.
1595#
1596
1597# Check for switch () and associated case and default
1598# statements should be at the same indent.
1599		if ($line=~/\bswitch\s*\(.*\)/) {
1600			my $err = '';
1601			my $sep = '';
1602			my @ctx = ctx_block_outer($linenr, $realcnt);
1603			shift(@ctx);
1604			for my $ctx (@ctx) {
1605				my ($clen, $cindent) = line_stats($ctx);
1606				if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
1607							$indent != $cindent) {
1608					$err .= "$sep$ctx\n";
1609					$sep = '';
1610				} else {
1611					$sep = "[...]\n";
1612				}
1613			}
1614			if ($err ne '') {
1615				ERROR("switch and case should be at the same indent\n$hereline$err");
1616			}
1617		}
1618
1619# if/while/etc brace do not go on next line, unless defining a do while loop,
1620# or if that brace on the next line is for something else
1621		if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
1622			my $pre_ctx = "$1$2";
1623
1624			my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
1625			my $ctx_cnt = $realcnt - $#ctx - 1;
1626			my $ctx = join("\n", @ctx);
1627
1628			my $ctx_ln = $linenr;
1629			my $ctx_skip = $realcnt;
1630
1631			while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
1632					defined $lines[$ctx_ln - 1] &&
1633					$lines[$ctx_ln - 1] =~ /^-/)) {
1634				##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
1635				$ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
1636				$ctx_ln++;
1637			}
1638
1639			#print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
1640			#print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
1641
1642			if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln -1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
1643				ERROR("that open brace { should be on the previous line\n" .
1644					"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1645			}
1646			if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
1647			    $ctx =~ /\)\s*\;\s*$/ &&
1648			    defined $lines[$ctx_ln - 1])
1649			{
1650				my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
1651				if ($nindent > $indent) {
1652					WARN("trailing semicolon indicates no statements, indent implies otherwise\n" .
1653						"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
1654				}
1655			}
1656		}
1657
1658# Check relative indent for conditionals and blocks.
1659		if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
1660			my ($s, $c) = ($stat, $cond);
1661
1662			substr($s, 0, length($c), '');
1663
1664			# Make sure we remove the line prefixes as we have
1665			# none on the first line, and are going to readd them
1666			# where necessary.
1667			$s =~ s/\n./\n/gs;
1668
1669			# Find out how long the conditional actually is.
1670			my @newlines = ($c =~ /\n/gs);
1671			my $cond_lines = 1 + $#newlines;
1672
1673			# We want to check the first line inside the block
1674			# starting at the end of the conditional, so remove:
1675			#  1) any blank line termination
1676			#  2) any opening brace { on end of the line
1677			#  3) any do (...) {
1678			my $continuation = 0;
1679			my $check = 0;
1680			$s =~ s/^.*\bdo\b//;
1681			$s =~ s/^\s*{//;
1682			if ($s =~ s/^\s*\\//) {
1683				$continuation = 1;
1684			}
1685			if ($s =~ s/^\s*?\n//) {
1686				$check = 1;
1687				$cond_lines++;
1688			}
1689
1690			# Also ignore a loop construct at the end of a
1691			# preprocessor statement.
1692			if (($prevline =~ /^.\s*#\s*define\s/ ||
1693			    $prevline =~ /\\\s*$/) && $continuation == 0) {
1694				$check = 0;
1695			}
1696
1697			my $cond_ptr = -1;
1698			$continuation = 0;
1699			while ($cond_ptr != $cond_lines) {
1700				$cond_ptr = $cond_lines;
1701
1702				# If we see an #else/#elif then the code
1703				# is not linear.
1704				if ($s =~ /^\s*\#\s*(?:else|elif)/) {
1705					$check = 0;
1706				}
1707
1708				# Ignore:
1709				#  1) blank lines, they should be at 0,
1710				#  2) preprocessor lines, and
1711				#  3) labels.
1712				if ($continuation ||
1713				    $s =~ /^\s*?\n/ ||
1714				    $s =~ /^\s*#\s*?/ ||
1715				    $s =~ /^\s*$Ident\s*:/) {
1716					$continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
1717					if ($s =~ s/^.*?\n//) {
1718						$cond_lines++;
1719					}
1720				}
1721			}
1722
1723			my (undef, $sindent) = line_stats("+" . $s);
1724			my $stat_real = raw_line($linenr, $cond_lines);
1725
1726			# Check if either of these lines are modified, else
1727			# this is not this patch's fault.
1728			if (!defined($stat_real) ||
1729			    $stat !~ /^\+/ && $stat_real !~ /^\+/) {
1730				$check = 0;
1731			}
1732			if (defined($stat_real) && $cond_lines > 1) {
1733				$stat_real = "[...]\n$stat_real";
1734			}
1735
1736			#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";
1737
1738			if ($check && (($sindent % 4) != 0 ||
1739			    ($sindent <= $indent && $s ne ''))) {
1740				WARN("suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
1741			}
1742		}
1743
1744		# Track the 'values' across context and added lines.
1745		my $opline = $line; $opline =~ s/^./ /;
1746		my ($curr_values, $curr_vars) =
1747				annotate_values($opline . "\n", $prev_values);
1748		$curr_values = $prev_values . $curr_values;
1749		if ($dbg_values) {
1750			my $outline = $opline; $outline =~ s/\t/ /g;
1751			print "$linenr > .$outline\n";
1752			print "$linenr > $curr_values\n";
1753			print "$linenr >  $curr_vars\n";
1754		}
1755		$prev_values = substr($curr_values, -1);
1756
1757#ignore lines not being added
1758		if ($line=~/^[^\+]/) {next;}
1759
1760# TEST: allow direct testing of the type matcher.
1761		if ($dbg_type) {
1762			if ($line =~ /^.\s*$Declare\s*$/) {
1763				ERROR("TEST: is type\n" . $herecurr);
1764			} elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
1765				ERROR("TEST: is not type ($1 is)\n". $herecurr);
1766			}
1767			next;
1768		}
1769# TEST: allow direct testing of the attribute matcher.
1770		if ($dbg_attr) {
1771			if ($line =~ /^.\s*$Modifier\s*$/) {
1772				ERROR("TEST: is attr\n" . $herecurr);
1773			} elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
1774				ERROR("TEST: is not attr ($1 is)\n". $herecurr);
1775			}
1776			next;
1777		}
1778
1779# check for initialisation to aggregates open brace on the next line
1780		if ($line =~ /^.\s*{/ &&
1781		    $prevline =~ /(?:^|[^=])=\s*$/) {
1782			ERROR("that open brace { should be on the previous line\n" . $hereprev);
1783		}
1784
1785#
1786# Checks which are anchored on the added line.
1787#
1788
1789# check for malformed paths in #include statements (uses RAW line)
1790		if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
1791			my $path = $1;
1792			if ($path =~ m{//}) {
1793				ERROR("malformed #include filename\n" .
1794					$herecurr);
1795			}
1796		}
1797
1798# no C99 // comments
1799		if ($line =~ m{//}) {
1800			ERROR("do not use C99 // comments\n" . $herecurr);
1801		}
1802		# Remove C99 comments.
1803		$line =~ s@//.*@@;
1804		$opline =~ s@//.*@@;
1805
1806# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
1807# the whole statement.
1808#print "APW <$lines[$realline_next - 1]>\n";
1809		if (defined $realline_next &&
1810		    exists $lines[$realline_next - 1] &&
1811		    !defined $suppress_export{$realline_next} &&
1812		    ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
1813		     $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
1814			# Handle definitions which produce identifiers with
1815			# a prefix:
1816			#   XXX(foo);
1817			#   EXPORT_SYMBOL(something_foo);
1818			my $name = $1;
1819			if ($stat =~ /^.([A-Z_]+)\s*\(\s*($Ident)/ &&
1820			    $name =~ /^${Ident}_$2/) {
1821#print "FOO C name<$name>\n";
1822				$suppress_export{$realline_next} = 1;
1823
1824			} elsif ($stat !~ /(?:
1825				\n.}\s*$|
1826				^.DEFINE_$Ident\(\Q$name\E\)|
1827				^.DECLARE_$Ident\(\Q$name\E\)|
1828				^.LIST_HEAD\(\Q$name\E\)|
1829				^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
1830				\b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
1831			    )/x) {
1832#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
1833				$suppress_export{$realline_next} = 2;
1834			} else {
1835				$suppress_export{$realline_next} = 1;
1836			}
1837		}
1838		if (!defined $suppress_export{$linenr} &&
1839		    $prevline =~ /^.\s*$/ &&
1840		    ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
1841		     $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
1842#print "FOO B <$lines[$linenr - 1]>\n";
1843			$suppress_export{$linenr} = 2;
1844		}
1845		if (defined $suppress_export{$linenr} &&
1846		    $suppress_export{$linenr} == 2) {
1847			WARN("EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
1848		}
1849
1850# check for global initialisers.
1851		if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) {
1852			ERROR("do not initialise globals to 0 or NULL\n" .
1853				$herecurr);
1854		}
1855# check for static initialisers.
1856		if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) {
1857			ERROR("do not initialise statics to 0 or NULL\n" .
1858				$herecurr);
1859		}
1860
1861# * goes on variable not on type
1862		# (char*[ const])
1863		if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) {
1864			my ($from, $to) = ($1, $1);
1865
1866			# Should start with a space.
1867			$to =~ s/^(\S)/ $1/;
1868			# Should not end with a space.
1869			$to =~ s/\s+$//;
1870			# '*'s should not have spaces between.
1871			while ($to =~ s/\*\s+\*/\*\*/) {
1872			}
1873
1874			#print "from<$from> to<$to>\n";
1875			if ($from ne $to) {
1876				ERROR("\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr);
1877			}
1878		} elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) {
1879			my ($from, $to, $ident) = ($1, $1, $2);
1880
1881			# Should start with a space.
1882			$to =~ s/^(\S)/ $1/;
1883			# Should not end with a space.
1884			$to =~ s/\s+$//;
1885			# '*'s should not have spaces between.
1886			while ($to =~ s/\*\s+\*/\*\*/) {
1887			}
1888			# Modifiers should have spaces.
1889			$to =~ s/(\b$Modifier$)/$1 /;
1890
1891			#print "from<$from> to<$to> ident<$ident>\n";
1892			if ($from ne $to && $ident !~ /^$Modifier$/) {
1893				ERROR("\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr);
1894			}
1895		}
1896
1897# # no BUG() or BUG_ON()
1898# 		if ($line =~ /\b(BUG|BUG_ON)\b/) {
1899# 			print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n";
1900# 			print "$herecurr";
1901# 			$clean = 0;
1902# 		}
1903
1904		if ($line =~ /\bLINUX_VERSION_CODE\b/) {
1905			WARN("LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
1906		}
1907
1908# printk should use KERN_* levels.  Note that follow on printk's on the
1909# same line do not need a level, so we use the current block context
1910# to try and find and validate the current printk.  In summary the current
1911# printk includes all preceding printk's which have no newline on the end.
1912# we assume the first bad printk is the one to report.
1913		if ($line =~ /\bprintk\((?!KERN_)\s*"/) {
1914			my $ok = 0;
1915			for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) {
1916				#print "CHECK<$lines[$ln - 1]\n";
1917				# we have a preceding printk if it ends
1918				# with "\n" ignore it, else it is to blame
1919				if ($lines[$ln - 1] =~ m{\bprintk\(}) {
1920					if ($rawlines[$ln - 1] !~ m{\\n"}) {
1921						$ok = 1;
1922					}
1923					last;
1924				}
1925			}
1926			if ($ok == 0) {
1927				WARN("printk() should include KERN_ facility level\n" . $herecurr);
1928			}
1929		}
1930
1931# function brace can't be on same line, except for #defines of do while,
1932# or if closed on same line
1933		if (($line=~/$Type\s*$Ident\(.*\).*\s{/) and
1934		    !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) {
1935			ERROR("open brace '{' following function declarations go on the next line\n" . $herecurr);
1936		}
1937
1938# open braces for enum, union and struct go on the same line.
1939		if ($line =~ /^.\s*{/ &&
1940		    $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
1941			ERROR("open brace '{' following $1 go on the same line\n" . $hereprev);
1942		}
1943
1944# missing space after union, struct or enum definition
1945		if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) {
1946		    WARN("missing space after $1 definition\n" . $herecurr);
1947		}
1948
1949# check for spacing round square brackets; allowed:
1950#  1. with a type on the left -- int [] a;
1951#  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
1952#  3. inside a curly brace -- = { [0...10] = 5 }
1953		while ($line =~ /(.*?\s)\[/g) {
1954			my ($where, $prefix) = ($-[1], $1);
1955			if ($prefix !~ /$Type\s+$/ &&
1956			    ($where != 0 || $prefix !~ /^.\s+$/) &&
1957			    $prefix !~ /{\s+$/) {
1958				ERROR("space prohibited before open square bracket '['\n" . $herecurr);
1959			}
1960		}
1961
1962# check for spaces between functions and their parentheses.
1963		while ($line =~ /($Ident)\s+\(/g) {
1964			my $name = $1;
1965			my $ctx_before = substr($line, 0, $-[1]);
1966			my $ctx = "$ctx_before$name";
1967
1968			# Ignore those directives where spaces _are_ permitted.
1969			if ($name =~ /^(?:
1970				if|for|while|switch|return|case|
1971				volatile|__volatile__|
1972				__attribute__|format|__extension__|
1973				asm|__asm__)$/x)
1974			{
1975
1976			# Ignore 'catch (...)' in C++
1977			} elsif ($name =~ /^catch$/ && $realfile =~ /(\.cpp|\.h)$/) {
1978
1979			# cpp #define statements have non-optional spaces, ie
1980			# if there is a space between the name and the open
1981			# parenthesis it is simply not a parameter group.
1982			} elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
1983
1984			# cpp #elif statement condition may start with a (
1985			} elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
1986
1987			# If this whole things ends with a type its most
1988			# likely a typedef for a function.
1989			} elsif ($ctx =~ /$Type$/) {
1990
1991			} else {
1992				WARN("space prohibited between function name and open parenthesis '('\n" . $herecurr);
1993			}
1994		}
1995# Check operator spacing.
1996		if (!($line=~/\#\s*include/)) {
1997			my $ops = qr{
1998				<<=|>>=|<=|>=|==|!=|
1999				\+=|-=|\*=|\/=|%=|\^=|\|=|&=|
2000				=>|->|<<|>>|<|>|=|!|~|
2001				&&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
2002				\?|::|:
2003			}x;
2004			my @elements = split(/($ops|;)/, $opline);
2005			my $off = 0;
2006
2007			my $blank = copy_spacing($opline);
2008
2009			for (my $n = 0; $n < $#elements; $n += 2) {
2010				$off += length($elements[$n]);
2011
2012				# Pick up the preceding and succeeding characters.
2013				my $ca = substr($opline, 0, $off);
2014				my $cc = '';
2015				if (length($opline) >= ($off + length($elements[$n + 1]))) {
2016					$cc = substr($opline, $off + length($elements[$n + 1]));
2017				}
2018				my $cb = "$ca$;$cc";
2019
2020				my $a = '';
2021				$a = 'V' if ($elements[$n] ne '');
2022				$a = 'W' if ($elements[$n] =~ /\s$/);
2023				$a = 'C' if ($elements[$n] =~ /$;$/);
2024				$a = 'B' if ($elements[$n] =~ /(\[|\()$/);
2025				$a = 'O' if ($elements[$n] eq '');
2026				$a = 'E' if ($ca =~ /^\s*$/);
2027
2028				my $op = $elements[$n + 1];
2029
2030				my $c = '';
2031				if (defined $elements[$n + 2]) {
2032					$c = 'V' if ($elements[$n + 2] ne '');
2033					$c = 'W' if ($elements[$n + 2] =~ /^\s/);
2034					$c = 'C' if ($elements[$n + 2] =~ /^$;/);
2035					$c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
2036					$c = 'O' if ($elements[$n + 2] eq '');
2037					$c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
2038				} else {
2039					$c = 'E';
2040				}
2041
2042				my $ctx = "${a}x${c}";
2043
2044				my $at = "(ctx:$ctx)";
2045
2046				my $ptr = substr($blank, 0, $off) . "^";
2047				my $hereptr = "$hereline$ptr\n";
2048
2049				# Pull out the value of this operator.
2050				my $op_type = substr($curr_values, $off + 1, 1);
2051
2052				# Get the full operator variant.
2053				my $opv = $op . substr($curr_vars, $off, 1);
2054
2055				# Ignore operators passed as parameters.
2056				if ($op_type ne 'V' &&
2057				    $ca =~ /\s$/ && $cc =~ /^\s*,/) {
2058
2059#				# Ignore comments
2060#				} elsif ($op =~ /^$;+$/) {
2061
2062				# ; should have either the end of line or a space or \ after it
2063				} elsif ($op eq ';') {
2064					if ($ctx !~ /.x[WEBC]/ &&
2065					    $cc !~ /^\\/ && $cc !~ /^;/) {
2066						ERROR("space required after that '$op' $at\n" . $hereptr);
2067					}
2068
2069				# // is a comment
2070				} elsif ($op eq '//') {
2071
2072				# Ignore : used in class declaration in C++
2073				} elsif ($opv eq ':B' && $ctx =~ /Wx[WE]/ &&
2074						 $line =~ /class/ && $realfile =~ /(\.cpp|\.h)$/) {
2075
2076				# No spaces for:
2077				#   ->
2078				#   :   when part of a bitfield
2079				} elsif ($op eq '->' || $opv eq ':B') {
2080					if ($ctx =~ /Wx.|.xW/) {
2081						ERROR("spaces prohibited around that '$op' $at\n" . $hereptr);
2082					}
2083
2084				# , must have a space on the right.
2085                                # not required when having a single },{ on one line
2086				} elsif ($op eq ',') {
2087					if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/ &&
2088                                            ($elements[$n] . $elements[$n + 2]) !~ " *}{") {
2089						ERROR("space required after that '$op' $at\n" . $hereptr);
2090					}
2091
2092				# '*' as part of a type definition -- reported already.
2093				} elsif ($opv eq '*_') {
2094					#warn "'*' is part of type\n";
2095
2096				# unary operators should have a space before and
2097				# none after.  May be left adjacent to another
2098				# unary operator, or a cast
2099				} elsif ($op eq '!' || $op eq '~' ||
2100					 $opv eq '*U' || $opv eq '-U' ||
2101					 $opv eq '&U' || $opv eq '&&U') {
2102					if ($op eq '~' && $ca =~ /::$/ && $realfile =~ /(\.cpp|\.h)$/) {
2103						# '~' used as a name of Destructor
2104
2105					} elsif ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
2106						ERROR("space required before that '$op' $at\n" . $hereptr);
2107					}
2108					if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
2109						# A unary '*' may be const
2110
2111					} elsif ($ctx =~ /.xW/) {
2112						ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2113					}
2114
2115				# unary ++ and unary -- are allowed no space on one side.
2116				} elsif ($op eq '++' or $op eq '--') {
2117					if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
2118						ERROR("space required one side of that '$op' $at\n" . $hereptr);
2119					}
2120					if ($ctx =~ /Wx[BE]/ ||
2121					    ($ctx =~ /Wx./ && $cc =~ /^;/)) {
2122						ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2123					}
2124					if ($ctx =~ /ExW/) {
2125						ERROR("space prohibited after that '$op' $at\n" . $hereptr);
2126					}
2127
2128
2129				# << and >> may either have or not have spaces both sides
2130				} elsif ($op eq '<<' or $op eq '>>' or
2131					 $op eq '&' or $op eq '^' or $op eq '|' or
2132					 $op eq '+' or $op eq '-' or
2133					 $op eq '*' or $op eq '/' or
2134					 $op eq '%')
2135				{
2136					if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
2137						ERROR("need consistent spacing around '$op' $at\n" .
2138							$hereptr);
2139					}
2140
2141				# A colon needs no spaces before when it is
2142				# terminating a case value or a label.
2143				} elsif ($opv eq ':C' || $opv eq ':L') {
2144					if ($ctx =~ /Wx./) {
2145						ERROR("space prohibited before that '$op' $at\n" . $hereptr);
2146					}
2147
2148				# All the others need spaces both sides.
2149				} elsif ($ctx !~ /[EWC]x[CWE]/) {
2150					my $ok = 0;
2151
2152					if ($realfile =~ /\.cpp|\.h$/) {
2153						# Ignore template arguments <...> in C++
2154						if (($op eq '<' || $op eq '>') && $line =~ /<.*>/) {
2155							$ok = 1;
2156						}
2157
2158						# Ignore :: in C++
2159						if ($op eq '::') {
2160							$ok = 1;
2161						}
2162					}
2163
2164					# Ignore email addresses <foo@bar>
2165					if (($op eq '<' &&
2166					     $cc =~ /^\S+\@\S+>/) ||
2167					    ($op eq '>' &&
2168					     $ca =~ /<\S+\@\S+$/))
2169					{
2170						$ok = 1;
2171					}
2172
2173					# Ignore ?:
2174					if (($opv eq ':O' && $ca =~ /\?$/) ||
2175					    ($op eq '?' && $cc =~ /^:/)) {
2176						$ok = 1;
2177					}
2178
2179					if ($ok == 0) {
2180						ERROR("spaces required around that '$op' $at\n" . $hereptr);
2181					}
2182				}
2183				$off += length($elements[$n + 1]);
2184			}
2185		}
2186
2187# check for multiple assignments
2188		if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
2189			CHK("multiple assignments should be avoided\n" . $herecurr);
2190		}
2191
2192## # check for multiple declarations, allowing for a function declaration
2193## # continuation.
2194## 		if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
2195## 		    $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
2196##
2197## 			# Remove any bracketed sections to ensure we do not
2198## 			# falsly report the parameters of functions.
2199## 			my $ln = $line;
2200## 			while ($ln =~ s/\([^\(\)]*\)//g) {
2201## 			}
2202## 			if ($ln =~ /,/) {
2203## 				WARN("declaring multiple variables together should be avoided\n" . $herecurr);
2204## 			}
2205## 		}
2206
2207#need space before brace following if, while, etc
2208		if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) ||
2209		    $line =~ /do{/) {
2210			ERROR("space required before the open brace '{'\n" . $herecurr);
2211		}
2212
2213# closing brace should have a space following it when it has anything
2214# on the line
2215		if ($line =~ /}(?!(?:,|;|\)))\S/) {
2216			ERROR("space required after that close brace '}'\n" . $herecurr);
2217		}
2218
2219# check spacing on square brackets
2220		if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
2221			ERROR("space prohibited after that open square bracket '['\n" . $herecurr);
2222		}
2223		if ($line =~ /\s\]/) {
2224			ERROR("space prohibited before that close square bracket ']'\n" . $herecurr);
2225		}
2226
2227# check spacing on parentheses
2228		if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
2229		    $line !~ /for\s*\(\s+;/) {
2230			ERROR("space prohibited after that open parenthesis '('\n" . $herecurr);
2231		}
2232		if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
2233		    $line !~ /for\s*\(.*;\s+\)/ &&
2234		    $line !~ /:\s+\)/) {
2235			ERROR("space prohibited before that close parenthesis ')'\n" . $herecurr);
2236		}
2237
2238# Return is not a function.
2239		if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) {
2240			my $spacing = $1;
2241			my $value = $2;
2242
2243			# Flatten any parentheses
2244			$value =~ s/\(/ \(/g;
2245			$value =~ s/\)/\) /g;
2246			while ($value =~ s/\[[^\{\}]*\]/1/ ||
2247			       $value !~ /(?:$Ident|-?$Constant)\s*
2248					     $Compare\s*
2249					     (?:$Ident|-?$Constant)/x &&
2250			       $value =~ s/\([^\(\)]*\)/1/) {
2251			}
2252#print "value<$value>\n";
2253			if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/) {
2254				ERROR("return is not a function, parentheses are not required\n" . $herecurr);
2255
2256			} elsif ($spacing !~ /\s+/) {
2257				ERROR("space required before the open parenthesis '('\n" . $herecurr);
2258			}
2259		}
2260# Return of what appears to be an errno should normally be -'ve
2261		if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) {
2262			my $name = $1;
2263			if ($name ne 'EOF' && $name ne 'ERROR') {
2264				CHK("return of an errno should typically be -ve (return -$1)\n" . $herecurr);
2265			}
2266		}
2267
2268# Need a space before open parenthesis after if, while etc
2269		if ($line=~/\b(if|while|for|switch)\(/) {
2270			ERROR("space required before the open parenthesis '('\n" . $herecurr);
2271		}
2272
2273# Check for illegal assignment in if conditional -- and check for trailing
2274# statements after the conditional.
2275		if ($line =~ /do\s*(?!{)/) {
2276			my ($stat_next) = ctx_statement_block($line_nr_next,
2277						$remain_next, $off_next);
2278			$stat_next =~ s/\n./\n /g;
2279			##print "stat<$stat> stat_next<$stat_next>\n";
2280
2281			if ($stat_next =~ /^\s*while\b/) {
2282				# If the statement carries leading newlines,
2283				# then count those as offsets.
2284				my ($whitespace) =
2285					($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
2286				my $offset =
2287					statement_rawlines($whitespace) - 1;
2288
2289				$suppress_whiletrailers{$line_nr_next +
2290								$offset} = 1;
2291			}
2292		}
2293		if (!defined $suppress_whiletrailers{$linenr} &&
2294		    $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
2295			my ($s, $c) = ($stat, $cond);
2296
2297			if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
2298				ERROR("do not use assignment in if condition\n" . $herecurr);
2299			}
2300
2301			# Find out what is on the end of the line after the
2302			# conditional.
2303			substr($s, 0, length($c), '');
2304			$s =~ s/\n.*//g;
2305			$s =~ s/$;//g; 	# Remove any comments
2306			if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
2307			    $c !~ /}\s*while\s*/)
2308			{
2309				# Find out how long the conditional actually is.
2310				my @newlines = ($c =~ /\n/gs);
2311				my $cond_lines = 1 + $#newlines;
2312				my $stat_real = '';
2313
2314				$stat_real = raw_line($linenr, $cond_lines)
2315							. "\n" if ($cond_lines);
2316				if (defined($stat_real) && $cond_lines > 1) {
2317					$stat_real = "[...]\n$stat_real";
2318				}
2319
2320				ERROR("trailing statements should be on next line\n" . $herecurr . $stat_real);
2321			}
2322		}
2323
2324# Check for bitwise tests written as boolean
2325		if ($line =~ /
2326			(?:
2327				(?:\[|\(|\&\&|\|\|)
2328				\s*0[xX][0-9]+\s*
2329				(?:\&\&|\|\|)
2330			|
2331				(?:\&\&|\|\|)
2332				\s*0[xX][0-9]+\s*
2333				(?:\&\&|\|\||\)|\])
2334			)/x)
2335		{
2336			WARN("boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
2337		}
2338
2339# if and else should not have general statements after it
2340		if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
2341			my $s = $1;
2342			$s =~ s/$;//g; 	# Remove any comments
2343			if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
2344				ERROR("trailing statements should be on next line\n" . $herecurr);
2345			}
2346		}
2347# if should not continue a brace
2348		if ($line =~ /}\s*if\b/) {
2349			ERROR("trailing statements should be on next line\n" .
2350				$herecurr);
2351		}
2352# case and default should not have general statements after them
2353		if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
2354		    $line !~ /\G(?:
2355			(?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
2356			\s*return\s+
2357		    )/xg)
2358		{
2359			ERROR("trailing statements should be on next line\n" . $herecurr);
2360		}
2361
2362		# Check for }<nl>else {, these must be at the same
2363		# indent level to be relevant to each other.
2364		if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and
2365						$previndent == $indent) {
2366			ERROR("else should follow close brace '}'\n" . $hereprev);
2367		}
2368
2369		if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and
2370						$previndent == $indent) {
2371			my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
2372
2373			# Find out what is on the end of the line after the
2374			# conditional.
2375			substr($s, 0, length($c), '');
2376			$s =~ s/\n.*//g;
2377
2378			if ($s =~ /^\s*;/) {
2379				ERROR("while should follow close brace '}'\n" . $hereprev);
2380			}
2381		}
2382
2383#studly caps, commented out until figure out how to distinguish between use of existing and adding new
2384#		if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) {
2385#		    print "No studly caps, use _\n";
2386#		    print "$herecurr";
2387#		    $clean = 0;
2388#		}
2389
2390#no spaces allowed after \ in define
2391		if ($line=~/\#\s*define.*\\\s$/) {
2392			WARN("Whitepspace after \\ makes next lines useless\n" . $herecurr);
2393		}
2394
2395#warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line)
2396		if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
2397			my $file = "$1.h";
2398			my $checkfile = "include/linux/$file";
2399			if (-f "$root/$checkfile" &&
2400			    $realfile ne $checkfile &&
2401			    $1 !~ /$allowed_asm_includes/)
2402			{
2403				if ($realfile =~ m{^arch/}) {
2404					CHK("Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
2405				} else {
2406					WARN("Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
2407				}
2408			}
2409		}
2410
2411# multi-statement macros should be enclosed in a do while loop, grab the
2412# first statement and ensure its the whole macro if its not enclosed
2413# in a known good container
2414		if ($realfile !~ m@/vmlinux.lds.h$@ &&
2415		    $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
2416			my $ln = $linenr;
2417			my $cnt = $realcnt;
2418			my ($off, $dstat, $dcond, $rest);
2419			my $ctx = '';
2420
2421			my $args = defined($1);
2422
2423			# Find the end of the macro and limit our statement
2424			# search to that.
2425			while ($cnt > 0 && defined $lines[$ln - 1] &&
2426				$lines[$ln - 1] =~ /^(?:-|..*\\$)/)
2427			{
2428				$ctx .= $rawlines[$ln - 1] . "\n";
2429				$cnt-- if ($lines[$ln - 1] !~ /^-/);
2430				$ln++;
2431			}
2432			$ctx .= $rawlines[$ln - 1];
2433
2434			($dstat, $dcond, $ln, $cnt, $off) =
2435				ctx_statement_block($linenr, $ln - $linenr + 1, 0);
2436			#print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
2437			#print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
2438
2439			# Extract the remainder of the define (if any) and
2440			# rip off surrounding spaces, and trailing \'s.
2441			$rest = '';
2442			while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) {
2443				#print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n";
2444				if ($off != 0 || $lines[$ln - 1] !~ /^-/) {
2445					$rest .= substr($lines[$ln - 1], $off) . "\n";
2446					$cnt--;
2447				}
2448				$ln++;
2449				$off = 0;
2450			}
2451			$rest =~ s/\\\n.//g;
2452			$rest =~ s/^\s*//s;
2453			$rest =~ s/\s*$//s;
2454
2455			# Clean up the original statement.
2456			if ($args) {
2457				substr($dstat, 0, length($dcond), '');
2458			} else {
2459				$dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//;
2460			}
2461			$dstat =~ s/$;//g;
2462			$dstat =~ s/\\\n.//g;
2463			$dstat =~ s/^\s*//s;
2464			$dstat =~ s/\s*$//s;
2465
2466			# Flatten any parentheses and braces
2467			while ($dstat =~ s/\([^\(\)]*\)/1/ ||
2468			       $dstat =~ s/\{[^\{\}]*\}/1/ ||
2469			       $dstat =~ s/\[[^\{\}]*\]/1/)
2470			{
2471			}
2472
2473			my $exceptions = qr{
2474				$Declare|
2475				module_param_named|
2476				MODULE_PARAM_DESC|
2477				DECLARE_PER_CPU|
2478				DEFINE_PER_CPU|
2479				__typeof__\(|
2480				union|
2481				struct|
2482				\.$Ident\s*=\s*|
2483				^\"|\"$
2484			}x;
2485			#print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
2486			if ($rest ne '' && $rest ne ',') {
2487				if ($rest !~ /while\s*\(/ &&
2488				    $dstat !~ /$exceptions/)
2489				{
2490					ERROR("Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n");
2491				}
2492
2493			} elsif ($ctx !~ /;/) {
2494				if ($dstat ne '' &&
2495				    $dstat !~ /^(?:$Ident|-?$Constant)$/ &&
2496				    $dstat !~ /$exceptions/ &&
2497				    $dstat !~ /^\.$Ident\s*=/ &&
2498				    $dstat =~ /$Operators/)
2499				{
2500					ERROR("Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n");
2501				}
2502			}
2503		}
2504
2505# make sure symbols are always wrapped with VMLINUX_SYMBOL() ...
2506# all assignments may have only one of the following with an assignment:
2507#	.
2508#	ALIGN(...)
2509#	VMLINUX_SYMBOL(...)
2510		if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) {
2511			WARN("vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr);
2512		}
2513
2514# check for missing bracing round if etc
2515		if ($line =~ /(^.*)\bif\b/ && $line !~ /\#\s*if/) {
2516			my ($level, $endln, @chunks) =
2517				ctx_statement_full($linenr, $realcnt, 1);
2518                        if ($dbg_adv_apw) {
2519                            print "APW: chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
2520                            print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"
2521                                if $#chunks >= 1;
2522                        }
2523			if ($#chunks >= 0 && $level == 0) {
2524				my $allowed = 0;
2525				my $seen = 0;
2526				my $herectx = $here . "\n";
2527				my $ln = $linenr - 1;
2528				for my $chunk (@chunks) {
2529					my ($cond, $block) = @{$chunk};
2530
2531					# If the condition carries leading newlines, then count those as offsets.
2532					my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
2533					my $offset = statement_rawlines($whitespace) - 1;
2534
2535					#print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
2536
2537					# We have looked at and allowed this specific line.
2538					$suppress_ifbraces{$ln + $offset} = 1;
2539
2540					$herectx .= "$rawlines[$ln + $offset]\n[...]\n";
2541					$ln += statement_rawlines($block) - 1;
2542
2543					substr($block, 0, length($cond), '');
2544
2545					$seen++ if ($block =~ /^\s*{/);
2546
2547                                        print "APW: cond<$cond> block<$block> allowed<$allowed>\n"
2548                                            if $dbg_adv_apw;
2549					if (statement_lines($cond) > 1) {
2550                                            print "APW: ALLOWED: cond<$cond>\n"
2551                                                if $dbg_adv_apw;
2552                                            $allowed = 1;
2553					}
2554					if ($block =~/\b(?:if|for|while)\b/) {
2555                                            print "APW: ALLOWED: block<$block>\n"
2556                                                if $dbg_adv_apw;
2557                                            $allowed = 1;
2558					}
2559					if (statement_block_size($block) > 1) {
2560                                            print "APW: ALLOWED: lines block<$block>\n"
2561                                                if $dbg_adv_apw;
2562                                            $allowed = 1;
2563					}
2564				}
2565				if ($seen != ($#chunks + 1)) {
2566					WARN("braces {} are necessary for all arms of this statement\n" . $herectx);
2567				}
2568			}
2569		}
2570		if (!defined $suppress_ifbraces{$linenr - 1} &&
2571					$line =~ /\b(if|while|for|else)\b/ &&
2572					$line !~ /\#\s*if/ &&
2573					$line !~ /\#\s*else/) {
2574			my $allowed = 0;
2575
2576                        # Check the pre-context.
2577                        if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
2578                            my $pre = $1;
2579
2580                            if ($line !~ /else/) {
2581                                print "APW: ALLOWED: pre<$pre> line<$line>\n"
2582                                    if $dbg_adv_apw;
2583                                $allowed = 1;
2584                            }
2585                        }
2586
2587			my ($level, $endln, @chunks) =
2588				ctx_statement_full($linenr, $realcnt, $-[0]);
2589
2590			# Check the condition.
2591			my ($cond, $block) = @{$chunks[0]};
2592                        print "CHECKING<$linenr> cond<$cond> block<$block>\n"
2593                            if $dbg_adv_checking;
2594			if (defined $cond) {
2595				substr($block, 0, length($cond), '');
2596			}
2597			if (statement_lines($cond) > 1) {
2598                            print "APW: ALLOWED: cond<$cond>\n"
2599                                if $dbg_adv_apw;
2600                            $allowed = 1;
2601			}
2602			if ($block =~/\b(?:if|for|while)\b/) {
2603                            print "APW: ALLOWED: block<$block>\n"
2604                                if $dbg_adv_apw;
2605                            $allowed = 1;
2606			}
2607			if (statement_block_size($block) > 1) {
2608                            print "APW: ALLOWED: lines block<$block>\n"
2609                                if $dbg_adv_apw;
2610                            $allowed = 1;
2611			}
2612			# Check the post-context.
2613			if (defined $chunks[1]) {
2614				my ($cond, $block) = @{$chunks[1]};
2615				if (defined $cond) {
2616					substr($block, 0, length($cond), '');
2617				}
2618				if ($block =~ /^\s*\{/) {
2619                                    print "APW: ALLOWED: chunk-1 block<$block>\n"
2620                                        if $dbg_adv_apw;
2621                                    $allowed = 1;
2622				}
2623			}
2624                        print "DCS: level=$level block<$block> allowed=$allowed\n"
2625                            if $dbg_adv_dcs;
2626			if ($level == 0 && $block !~ /^\s*\{/ && !$allowed) {
2627				my $herectx = $here . "\n";;
2628				my $cnt = statement_rawlines($block);
2629
2630				for (my $n = 0; $n < $cnt; $n++) {
2631					$herectx .= raw_line($linenr, $n) . "\n";;
2632				}
2633
2634				WARN("braces {} are necessary even for single statement blocks\n" . $herectx);
2635			}
2636		}
2637
2638# don't include deprecated include files (uses RAW line)
2639		for my $inc (@dep_includes) {
2640			if ($rawline =~ m@^.\s*\#\s*include\s*\<$inc>@) {
2641				ERROR("Don't use <$inc>: see Documentation/feature-removal-schedule.txt\n" . $herecurr);
2642			}
2643		}
2644
2645# don't use deprecated functions
2646		for my $func (@dep_functions) {
2647			if ($line =~ /\b$func\b/) {
2648				ERROR("Don't use $func(): see Documentation/feature-removal-schedule.txt\n" . $herecurr);
2649			}
2650		}
2651
2652# no volatiles please
2653		my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
2654		if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
2655			WARN("Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr);
2656		}
2657
2658# SPIN_LOCK_UNLOCKED & RW_LOCK_UNLOCKED are deprecated
2659		if ($line =~ /\b(SPIN_LOCK_UNLOCKED|RW_LOCK_UNLOCKED)/) {
2660			ERROR("Use of $1 is deprecated: see Documentation/spinlocks.txt\n" . $herecurr);
2661		}
2662
2663# warn about #if 0
2664		if ($line =~ /^.\s*\#\s*if\s+0\b/) {
2665			CHK("if this code is redundant consider removing it\n" .
2666				$herecurr);
2667		}
2668
2669# check for needless kfree() checks
2670		if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
2671			my $expr = $1;
2672			if ($line =~ /\bkfree\(\Q$expr\E\);/) {
2673				WARN("kfree(NULL) is safe this check is probably not required\n" . $hereprev);
2674			}
2675		}
2676# check for needless usb_free_urb() checks
2677		if ($prevline =~ /\bif\s*\(([^\)]*)\)/) {
2678			my $expr = $1;
2679			if ($line =~ /\busb_free_urb\(\Q$expr\E\);/) {
2680				WARN("usb_free_urb(NULL) is safe this check is probably not required\n" . $hereprev);
2681			}
2682		}
2683
2684# prefer usleep_range over udelay
2685		if ($line =~ /\budelay\s*\(\s*(\w+)\s*\)/) {
2686			# ignore udelay's < 10, however
2687			if (! (($1 =~ /(\d+)/) && ($1 < 10)) ) {
2688				CHK("usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $line);
2689			}
2690		}
2691
2692# warn about unexpectedly long msleep's
2693		if ($line =~ /\bmsleep\s*\((\d+)\);/) {
2694			if ($1 < 20) {
2695				WARN("msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $line);
2696			}
2697		}
2698
2699# warn about #ifdefs in C files
2700#		if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
2701#			print "#ifdef in C files should be avoided\n";
2702#			print "$herecurr";
2703#			$clean = 0;
2704#		}
2705
2706# warn about spacing in #ifdefs
2707		if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
2708			ERROR("exactly one space required after that #$1\n" . $herecurr);
2709		}
2710
2711# check for spinlock_t definitions without a comment.
2712		if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
2713		    $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
2714			my $which = $1;
2715			if (!ctx_has_comment($first_line, $linenr)) {
2716				CHK("$1 definition without comment\n" . $herecurr);
2717			}
2718		}
2719# check for memory barriers without a comment.
2720		if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) {
2721			if (!ctx_has_comment($first_line, $linenr)) {
2722				CHK("memory barrier without comment\n" . $herecurr);
2723			}
2724		}
2725# check of hardware specific defines
2726		if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
2727			CHK("architecture specific defines should be avoided\n" .  $herecurr);
2728		}
2729
2730# Check that the storage class is at the beginning of a declaration
2731		if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) {
2732			WARN("storage class should be at the beginning of the declaration\n" . $herecurr)
2733		}
2734
2735# check the location of the inline attribute, that it is between
2736# storage class and type.
2737		if ($line =~ /\b$Type\s+$Inline\b/ ||
2738		    $line =~ /\b$Inline\s+$Storage\b/) {
2739			ERROR("inline keyword should sit between storage class and type\n" . $herecurr);
2740		}
2741
2742# Check for __inline__ and __inline, prefer inline
2743		if ($line =~ /\b(__inline__|__inline)\b/) {
2744			WARN("plain inline is preferred over $1\n" . $herecurr);
2745		}
2746
2747# check for sizeof(&)
2748		if ($line =~ /\bsizeof\s*\(\s*\&/) {
2749			WARN("sizeof(& should be avoided\n" . $herecurr);
2750		}
2751
2752# check for new externs in .c files.
2753		if ($realfile =~ /\.c$/ && defined $stat &&
2754		    $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
2755		{
2756			my $function_name = $1;
2757			my $paren_space = $2;
2758
2759			my $s = $stat;
2760			if (defined $cond) {
2761				substr($s, 0, length($cond), '');
2762			}
2763			if ($s =~ /^\s*;/ &&
2764			    $function_name ne 'uninitialized_var')
2765			{
2766				WARN("externs should be avoided in .c files\n" .  $herecurr);
2767			}
2768
2769			if ($paren_space =~ /\n/) {
2770				WARN("arguments for function declarations should follow identifier\n" . $herecurr);
2771			}
2772
2773		} elsif ($realfile =~ /\.c$/ && defined $stat &&
2774		    $stat =~ /^.\s*extern\s+/)
2775		{
2776			WARN("externs should be avoided in .c files\n" .  $herecurr);
2777		}
2778
2779# checks for new __setup's
2780		if ($rawline =~ /\b__setup\("([^"]*)"/) {
2781			my $name = $1;
2782
2783			if (!grep(/$name/, @setup_docs)) {
2784				CHK("__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr);
2785			}
2786		}
2787
2788# check for pointless casting of kmalloc return
2789		if ($line =~ /\*\s*\)\s*k[czm]alloc\b/) {
2790			WARN("unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
2791		}
2792
2793# check for gcc specific __FUNCTION__
2794		if ($line =~ /__FUNCTION__/) {
2795			WARN("__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr);
2796		}
2797
2798# check for semaphores used as mutexes
2799		if ($line =~ /^.\s*(DECLARE_MUTEX|init_MUTEX)\s*\(/) {
2800			WARN("mutexes are preferred for single holder semaphores\n" . $herecurr);
2801		}
2802# check for semaphores used as mutexes
2803		if ($line =~ /^.\s*init_MUTEX_LOCKED\s*\(/) {
2804			WARN("consider using a completion\n" . $herecurr);
2805
2806		}
2807# recommend strict_strto* over simple_strto*
2808		if ($line =~ /\bsimple_(strto.*?)\s*\(/) {
2809			WARN("consider using strict_$1 in preference to simple_$1\n" . $herecurr);
2810		}
2811# check for __initcall(), use device_initcall() explicitly please
2812		if ($line =~ /^.\s*__initcall\s*\(/) {
2813			WARN("please use device_initcall() instead of __initcall()\n" . $herecurr);
2814		}
2815# check for various ops structs, ensure they are const.
2816		my $struct_ops = qr{acpi_dock_ops|
2817				address_space_operations|
2818				backlight_ops|
2819				block_device_operations|
2820				dentry_operations|
2821				dev_pm_ops|
2822				dma_map_ops|
2823				extent_io_ops|
2824				file_lock_operations|
2825				file_operations|
2826				hv_ops|
2827				ide_dma_ops|
2828				intel_dvo_dev_ops|
2829				item_operations|
2830				iwl_ops|
2831				kgdb_arch|
2832				kgdb_io|
2833				kset_uevent_ops|
2834				lock_manager_operations|
2835				microcode_ops|
2836				mtrr_ops|
2837				neigh_ops|
2838				nlmsvc_binding|
2839				pci_raw_ops|
2840				pipe_buf_operations|
2841				platform_hibernation_ops|
2842				platform_suspend_ops|
2843				proto_ops|
2844				rpc_pipe_ops|
2845				seq_operations|
2846				snd_ac97_build_ops|
2847				soc_pcmcia_socket_ops|
2848				stacktrace_ops|
2849				sysfs_ops|
2850				tty_operations|
2851				usb_mon_operations|
2852				wd_ops}x;
2853		if ($line !~ /\bconst\b/ &&
2854		    $line =~ /\bstruct\s+($struct_ops)\b/) {
2855			WARN("struct $1 should normally be const\n" .
2856				$herecurr);
2857		}
2858
2859# use of NR_CPUS is usually wrong
2860# ignore definitions of NR_CPUS and usage to define arrays as likely right
2861		if ($line =~ /\bNR_CPUS\b/ &&
2862		    $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
2863		    $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
2864		    $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
2865		    $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
2866		    $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
2867		{
2868			WARN("usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
2869		}
2870
2871# check for %L{u,d,i} in strings
2872		my $string;
2873		while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
2874			$string = substr($rawline, $-[1], $+[1] - $-[1]);
2875			$string =~ s/%%/__/g;
2876			if ($string =~ /(?<!%)%L[udi]/) {
2877				WARN("\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr);
2878				last;
2879			}
2880		}
2881
2882# whine mightly about in_atomic
2883		if ($line =~ /\bin_atomic\s*\(/) {
2884			if ($realfile =~ m@^drivers/@) {
2885				ERROR("do not use in_atomic in drivers\n" . $herecurr);
2886			} elsif ($realfile !~ m@^kernel/@) {
2887				WARN("use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
2888			}
2889		}
2890
2891# check for lockdep_set_novalidate_class
2892		if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
2893		    $line =~ /__lockdep_no_validate__\s*\)/ ) {
2894			if ($realfile !~ m@^kernel/lockdep@ &&
2895			    $realfile !~ m@^include/linux/lockdep@ &&
2896			    $realfile !~ m@^drivers/base/core@) {
2897				ERROR("lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
2898			}
2899		}
2900
2901# QEMU specific tests
2902		if ($rawline =~ /\b(?:Qemu|QEmu)\b/) {
2903			WARN("use QEMU instead of Qemu or QEmu\n" . $herecurr);
2904		}
2905	}
2906
2907	# If we have no input at all, then there is nothing to report on
2908	# so just keep quiet.
2909	if ($#rawlines == -1) {
2910		exit(0);
2911	}
2912
2913	# In mailback mode only produce a report in the negative, for
2914	# things that appear to be patches.
2915	if ($mailback && ($clean == 1 || !$is_patch)) {
2916		exit(0);
2917	}
2918
2919	# This is not a patch, and we are are in 'no-patch' mode so
2920	# just keep quiet.
2921	if (!$chk_patch && !$is_patch) {
2922		exit(0);
2923	}
2924
2925	if (!$is_patch) {
2926		ERROR("Does not appear to be a unified-diff format patch\n");
2927	}
2928	if ($is_patch && $chk_signoff && $signoff == 0) {
2929		ERROR("Missing Signed-off-by: line(s)\n");
2930	}
2931
2932	print report_dump();
2933	if ($summary && !($clean == 1 && $quiet == 1)) {
2934		print "$filename " if ($summary_file);
2935		print "total: $cnt_error errors, $cnt_warn warnings, " .
2936			(($check)? "$cnt_chk checks, " : "") .
2937			"$cnt_lines lines checked\n";
2938		print "\n" if ($quiet == 0);
2939	}
2940
2941	if ($quiet == 0) {
2942		# If there were whitespace errors which cleanpatch can fix
2943		# then suggest that.
2944#		if ($rpt_cleaners) {
2945#			print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n";
2946#			print "      scripts/cleanfile\n\n";
2947#		}
2948	}
2949
2950	if ($clean == 1 && $quiet == 0) {
2951		print "$vname has no obvious style problems and is ready for submission.\n"
2952	}
2953	if ($clean == 0 && $quiet == 0) {
2954		print "$vname has style problems, please review.  If any of these errors\n";
2955		print "are false positives report them to the maintainer, see\n";
2956		print "CHECKPATCH in MAINTAINERS.\n";
2957	}
2958
2959	return $clean;
2960}
2961