aboutsummaryrefslogtreecommitdiffstats
path: root/init/main.c
blob: 34971becbd3c6f2db9e011c9c09f070e7eaf3c71 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
/*
 *  linux/init/main.c
 *
 *  Copyright (C) 1991, 1992  Linus Torvalds
 *
 *  GK 2/5/95  -  Changed to support mounting root fs via NFS
 *  Added initrd & change_root: Werner Almesberger & Hans Lermen, Feb '96
 *  Moan early if gcc is old, avoiding bogus kernels - Paul Gortmaker, May '96
 *  Simplified starting of init:  Michael A. Griffith <grif@acm.org> 
 */

#include <linux/types.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/kernel.h>
#include <linux/syscalls.h>
#include <linux/stackprotector.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/delay.h>
#include <linux/utsname.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/smp_lock.h>
#include <linux/initrd.h>
#include <linux/bootmem.h>
#include <linux/acpi.h>
#include <linux/tty.h>
#include <linux/gfp.h>
#include <linux/percpu.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/kernel_stat.h>
#include <linux/start_kernel.h>
#include <linux/security.h>
#include <linux/smp.h>
#include <linux/workqueue.h>
#include <linux/profile.h>
#include <linux/rcupdate.h>
#include <linux/moduleparam.h>
#include <linux/kallsyms.h>
#include <linux/writeback.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/cgroup.h>
#include <linux/efi.h>
#include <linux/tick.h>
#include <linux/interrupt.h>
#include <linux/taskstats_kern.h>
#include <linux/delayacct.h>
#include <linux/unistd.h>
#include <linux/rmap.h>
#include <linux/mempolicy.h>
#include <linux/key.h>
#include <linux/buffer_head.h>
#include <linux/page_cgroup.h>
#include <linux/debug_locks.h>
#include <linux/debugobjects.h>
#include <linux/lockdep.h>
#include <linux/kmemleak.h>
#include <linux/pid_namespace.h>
#include <linux/device.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/idr.h>
#include <linux/ftrace.h>
#include <linux/async.h>
#include <linux/kmemcheck.h>
#include <linux/kmemtrace.h>
#include <linux/shmem_fs.h>
#include <trace/boot.h>

#include <asm/io.h>
#include <asm/bugs.h>
#include <asm/setup.h>
#include <asm/sections.h>
#include <asm/cacheflush.h>

#ifdef CONFIG_X86_LOCAL_APIC
#include <asm/smp.h>
#endif

static int kernel_init(void *);

extern void init_IRQ(void);
extern void fork_init(unsigned long);
extern void mca_init(void);
extern void sbus_init(void);
extern void prio_tree_init(void);
extern void radix_tree_init(void);
extern void free_initmem(void);
#ifndef CONFIG_DEBUG_RODATA
static inline void mark_rodata_ro(void) { }
#endif

#ifdef CONFIG_TC
extern void tc_init(void);
#endif

enum system_states system_state __read_mostly;
EXPORT_SYMBOL(system_state);

/*
 * Boot command-line arguments
 */
#define MAX_INIT_ARGS CONFIG_INIT_ENV_ARG_LIMIT
#define MAX_INIT_ENVS CONFIG_INIT_ENV_ARG_LIMIT

extern void time_init(void);
/* Default late time init is NULL. archs can override this later. */
void (*__initdata late_time_init)(void);
extern void softirq_init(void);

/* Untouched command line saved by arch-specific code. */
char __initdata boot_command_line[COMMAND_LINE_SIZE];
/* Untouched saved command line (eg. for /proc) */
char *saved_command_line;
/* Command line for parameter parsing */
static char *static_command_line;

static char *execute_command;
static char *ramdisk_execute_command;

#ifdef CONFIG_SMP
/* Setup configured maximum number of CPUs to activate */
unsigned int __initdata setup_max_cpus = NR_CPUS;

/*
 * Setup routine for controlling SMP activation
 *
 * Command-line option of "nosmp" or "maxcpus=0" will disable SMP
 * activation entirely (the MPS table probe still happens, though).
 *
 * Command-line option of "maxcpus=<NUM>", where <NUM> is an integer
 * greater than 0, limits the maximum number of CPUs activated in
 * SMP mode to <NUM>.
 */

void __weak arch_disable_smp_support(void) { }

static int __init nosmp(char *str)
{
	setup_max_cpus = 0;
	arch_disable_smp_support();

	return 0;
}

early_param("nosmp", nosmp);

static int __init maxcpus(char *str)
{
	get_option(&str, &setup_max_cpus);
	if (setup_max_cpus == 0)
		arch_disable_smp_support();

	return 0;
}

early_param("maxcpus", maxcpus);
#else
const unsigned int setup_max_cpus = NR_CPUS;
#endif

/*
 * If set, this is an indication to the drivers that reset the underlying
 * device before going ahead with the initialization otherwise driver might
 * rely on the BIOS and skip the reset operation.
 *
 * This is useful if kernel is booting in an unreliable environment.
 * For ex. kdump situaiton where previous kernel has crashed, BIOS has been
 * skipped and devices will be in unknown state.
 */
unsigned int reset_devices;
EXPORT_SYMBOL(reset_devices);

static int __init set_reset_devices(char *str)
{
	reset_devices = 1;
	return 1;
}

__setup("reset_devices", set_reset_devices);

static char * argv_init[MAX_INIT_ARGS+2] = { "init", NULL, };
char * envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };
static const char *panic_later, *panic_param;

extern struct obs_kernel_param __setup_start[], __setup_end[];

static int __init obsolete_checksetup(char *line)
{
	struct obs_kernel_param *p;
	int had_early_param = 0;

	p = __setup_start;
	do {
		int n = strlen(p->str);
		if (!strncmp(line, p->str, n)) {
			if (p->early) {
				/* Already done in parse_early_param?
				 * (Needs exact match on param part).
				 * Keep iterating, as we can have early
				 * params and __setups of same names 8( */
				if (line[n] == '\0' || line[n] == '=')
					had_early_param = 1;
			} else if (!p->setup_func) {
				printk(KERN_WARNING "Parameter %s is obsolete,"
				       " ignored\n", p->str);
				return 1;
			} else if (p->setup_func(line + n))
				return 1;
		}
		p++;
	} while (p < __setup_end);

	return had_early_param;
}

/*
 * This should be approx 2 Bo*oMips to start (note initial shift), and will
 * still work even if initially too large, it will just take slightly longer
 */
unsigned long loops_per_jiffy = (1<<12);

EXPORT_SYMBOL(loops_per_jiffy);

static int __init debug_kernel(char *str)
{
	console_loglevel = 10;
	return 0;
}

static int __init quiet_kernel(char *str)
{
	console_loglevel = 4;
	return 0;
}

early_param("debug", debug_kernel);
early_param("quiet", quiet_kernel);

static int __init loglevel(char *str)
{
	get_option(&str, &console_loglevel);
	return 0;
}

early_param("loglevel", loglevel);

/*
 * Unknown boot options get handed to init, unless they look like
 * failed parameters
 */
static int __init unknown_bootoption(char *param, char *val)
{
	/* Change NUL term back to "=", to make "param" the whole string. */
	if (val) {
		/* param=val or param="val"? */
		if (val == param+strlen(param)+1)
			val[-1] = '=';
		else if (val == param+strlen(param)+2) {
			val[-2] = '=';
			memmove(val-1, val, strlen(val)+1);
			val--;
		} else
			BUG();
	}

	/* Handle obsolete-style parameters */
	if (obsolete_checksetup(param))
		return 0;

	/*
	 * Preemptive maintenance for "why didn't my misspelled command
	 * line work?"
	 */
	if (strchr(param, '.') && (!val || strchr(param, '.') < val)) {
		printk(KERN_ERR "Unknown boot option `%s': ignoring\n", param);
		return 0;
	}

	if (panic_later)
		return 0;

	if (val) {
		/* Environment option */
		unsigned int i;
		for (i = 0; envp_init[i]; i++) {
			if (i == MAX_INIT_ENVS) {
				panic_later = "Too many boot env vars at `%s'";
				panic_param = param;
			}
			if (!strncmp(param, envp_init[i], val - param))
				break;
		}
		envp_init[i] = param;
	} else {
		/* Command line option */
		unsigned int i;
		for (i = 0; argv_init[i]; i++) {
			if (i == MAX_INIT_ARGS) {
				panic_later = "Too many boot init vars at `%s'";
				panic_param = param;
			}
		}
		argv_init[i] = param;
	}
	return 0;
}

#ifdef CONFIG_DEBUG_PAGEALLOC
int __read_mostly debug_pagealloc_enabled = 0;
#endif

static int __init init_setup(char *str)
{
	unsigned int i;

	execute_command = str;
	/*
	 * In case LILO is going to boot us with default command line,
	 * it prepends "auto" before the whole cmdline which makes
	 * the shell think it should execute a script with such name.
	 * So we ignore all arguments entered _before_ init=... [MJ]
	 */
	for (i = 1; i < MAX_INIT_ARGS; i++)
		argv_init[i] = NULL;
	return 1;
}
__setup("init=", init_setup);

static int __init rdinit_setup(char *str)
{
	unsigned int i;

	ramdisk_execute_command = str;
	/* See "auto" comment in init_setup */
	for (i = 1; i < MAX_INIT_ARGS; i++)
		argv_init[i] = NULL;
	return 1;
}
__setup("rdinit=", rdinit_setup);

#ifndef CONFIG_SMP

#ifdef CONFIG_X86_LOCAL_APIC
static void __init smp_init(void)
{
	APIC_init_uniprocessor();
}
#else
#define smp_init()	do { } while (0)
#endif

static inline void setup_nr_cpu_ids(void) { }
static inline void smp_prepare_cpus(unsigned int maxcpus) { }

#else

#if NR_CPUS > BITS_PER_LONG
cpumask_t cpu_mask_all __read_mostly = CPU_MASK_ALL;
EXPORT_SYMBOL(cpu_mask_all);
#endif

/* Setup number of possible processor ids */
int nr_cpu_ids __read_mostly = NR_CPUS;
EXPORT_SYMBOL(nr_cpu_ids);

/* An arch may set nr_cpu_ids earlier if needed, so this would be redundant */
static void __init setup_nr_cpu_ids(void)
{
	nr_cpu_ids = find_last_bit(cpumask_bits(cpu_possible_mask),NR_CPUS) + 1;
}

/* Called by boot processor to activate the rest. */
static void __init smp_init(void)
{
	unsigned int cpu;

	/*
	 * Set up the current CPU as possible to migrate to.
	 * The other ones will be done by cpu_up/cpu_down()
	 */
	set_cpu_active(smp_processor_id(), true);

	/* FIXME: This should be done in userspace --RR */
	for_each_present_cpu(cpu) {
		if (num_online_cpus() >= setup_max_cpus)
			break;
		if (!cpu_online(cpu))
			cpu_up(cpu);
	}

	/* Any cleanup work */
	printk(KERN_INFO "Brought up %ld CPUs\n", (long)num_online_cpus());
	smp_cpus_done(setup_max_cpus);
}

#endif

/*
 * We need to store the untouched command line for future reference.
 * We also need to store the touched command line since the parameter
 * parsing is performed in place, and we should allow a component to
 * store reference of name/value for future reference.
 */
static void __init setup_command_line(char *command_line)
{
	saved_command_line = alloc_bootmem(strlen (boot_command_line)+1);
	static_command_line = alloc_bootmem(strlen (command_line)+1);
	strcpy (saved_command_line, boot_command_line);
	strcpy (static_command_line, command_line);
}

/*
 * We need to finalize in a non-__init function or else race conditions
 * between the root thread and the init thread may cause start_kernel to
 * be reaped by free_initmem before the root thread has proceeded to
 * cpu_idle.
 *
 * gcc-3.4 accidentally inlines this function, so use noinline.
 */

static noinline void __init_refok rest_init(void)
	__releases(kernel_lock)
{
	int pid;

	rcu_scheduler_starting();
	kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND);
	numa_default_policy();
	pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES);
	kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns);
	unlock_kernel();

	/*
	 * The boot idle thread must execute schedule()
	 * at least once to get things moving:
	 */
	init_idle_bootup_task(current);
	preempt_enable_no_resched();
	schedule();
	preempt_disable();

	/* Call into cpu_idle with preempt disabled */
	cpu_idle();
}

/* Check for early params. */
static int __init do_early_param(char *param, char *val)
{
	struct obs_kernel_param *p;

	for (p = __setup_start; p < __setup_end; p++) {
		if ((p->early && strcmp(param, p->str) == 0) ||
		    (strcmp(param, "console") == 0 &&
		     strcmp(p->str, "earlycon") == 0)
		) {
			if (p->setup_func(val) != 0)
				printk(KERN_WARNING
				       "Malformed early option '%s'\n", param);
		}
	}
	/* We accept everything at this stage. */
	return 0;
}

void __init parse_early_options(char *cmdline)
{
	parse_args("early options", cmdline, NULL, 0, do_early_param);
}

/* Arch code calls this early on, or if not, just before other parsing. */
void __init parse_early_param(void)
{
	static __initdata int done = 0;
	static __initdata char tmp_cmdline[COMMAND_LINE_SIZE];

	if (done)
		return;

	/* All fall through to do_early_param. */
	strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE);
	parse_early_options(tmp_cmdline);
	done = 1;
}

/*
 *	Activate the first processor.
 */

static void __init boot_cpu_init(void)
{
	int cpu = smp_processor_id();
	/* Mark the boot cpu "present", "online" etc for SMP and UP case */
	set_cpu_online(cpu, true);
	set_cpu_present(cpu, true);
	set_cpu_possible(cpu, true);
}

void __init __weak smp_setup_processor_id(void)
{
}

void __init __weak thread_info_cache_init(void)
{
}

/*
 * Set up kernel memory allocators
 */
static void __init mm_init(void)
{
	/*
	 * page_cgroup requires countinous pages as memmap
	 * and it's bigger than MAX_ORDER unless SPARSEMEM.
	 */
	page_cgroup_init_flatmem();
	mem_init();
	kmem_cache_init();
	pgtable_cache_init();
	vmalloc_init();
}

asmlinkage void __init start_kernel(void)
{
	char * command_line;
	extern struct kernel_param __start___param[], __stop___param[];

	smp_setup_processor_id();

	/*
	 * Need to run as early as possible, to initialize the
	 * lockdep hash:
	 */
	lockdep_init();
	debug_objects_early_init();

	/*
	 * Set up the the initial canary ASAP:
	 */
	boot_init_stack_canary();

	cgroup_init_early();

	local_irq_disable();
	early_boot_irqs_off();
	early_init_irq_lock_class();

/*
 * Interrupts are still disabled. Do necessary setups, then
 * enable them
 */
	lock_kernel();
	tick_init();
	boot_cpu_init();
	page_address_init();
	printk(KERN_NOTICE "%s", linux_banner);
	setup_arch(&command_line);
	mm_init_owner(&init_mm, &init_task);
	setup_command_line(command_line);
	setup_nr_cpu_ids();
	setup_per_cpu_areas();
	smp_prepare_boot_cpu();	/* arch-specific boot-cpu hooks */

	build_all_zonelists();
	page_alloc_init();

	printk(KERN_NOTICE "Kernel command line: %s\n", boot_command_line);
	parse_early_param();
	parse_args("Booting kernel", static_command_line, __start___param,
		   __stop___param - __start___param,
		   &unknown_bootoption);
	/*
	 * These use large bootmem allocations and must precede
	 * kmem_cache_init()
	 */
	pidhash_init();
	vfs_caches_init_early();
	sort_main_extable();
	trap_init();
	mm_init();
	/*
	 * Set up the scheduler prior starting any interrupts (such as the
	 * timer interrupt). Full topology setup happens at smp_init()
	 * time - but meanwhile we still have a functioning scheduler.
	 */
	sched_init();
	/*
	 * Disable preemption - early bootup scheduling is extremely
	 * fragile until we cpu_idle() for the first time.
	 */
	preempt_disable();
	if (!irqs_disabled()) {
		printk(KERN_WARNING "start_kernel(): bug: interrupts were "
				"enabled *very* early, fixing it\n");
		local_irq_disable();
	}
	rcu_init();
	/* init some links before init_ISA_irqs() */
	early_irq_init();
	init_IRQ();
	prio_tree_init();
	init_timers();
	hrtimers_init();
	softirq_init();
	timekeeping_init();
	time_init();
	profile_init();
	if (!irqs_disabled())
		printk(KERN_CRIT "start_kernel(): bug: interrupts were "
				 "enabled early\n");
	early_boot_irqs_on();
	local_irq_enable();

	/* Interrupts are enabled now so all GFP allocations are safe. */
	set_gfp_allowed_mask(__GFP_BITS_MASK);

	kmem_cache_init_late();

	/*
	 * HACK ALERT! This is early. We're enabling the console before
	 * we've done PCI setups etc, and console_init() must be aware of
	 * this. But we do want output early, in case something goes wrong.
	 */
	console_init();
	if (panic_later)
		panic(panic_later, panic_param);

	lockdep_info();

	/*
	 * Need to run this when irqs are enabled, because it wants
	 * to self-test [hard/soft]-irqs on/off lock inversion bugs
	 * too:
	 */
	locking_selftest();

#ifdef CONFIG_BLK_DEV_INITRD
	if (initrd_start && !initrd_below_start_ok &&
	    page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) {
		printk(KERN_CRIT "initrd overwritten (0x%08lx < 0x%08lx) - "
		    "disabling it.\n",
		    page_to_pfn(virt_to_page((void *)initrd_start)),
		    min_low_pfn);
		initrd_start = 0;
	}
#endif
	page_cgroup_init();
	enable_debug_pagealloc();
	kmemtrace_init();
	kmemleak_init();
	debug_objects_mem_init();
	idr_init_cache();
	setup_per_cpu_pageset();
	numa_policy_init();
	if (late_time_init)
		late_time_init();
	sched_clock_init();
	calibrate_delay();
	pidmap_init();
	anon_vma_init();
#ifdef CONFIG_X86
	if (efi_enabled)
		efi_enter_virtual_mode();
#endif
	thread_info_cache_init();
	cred_init();
	fork_init(num_physpages);
	proc_caches_init();
	buffer_init();
	key_init();
	security_init();
	vfs_caches_init(num_physpages);
	radix_tree_init();
	signals_init();
	/* rootfs populating might need page-writeback */
	page_writeback_init();
#ifdef CONFIG_PROC_FS
	proc_root_init();
#endif
	cgroup_init();
	cpuset_init();
	taskstats_init_early();
	delayacct_init();

	check_bugs();

	acpi_early_init(); /* before LAPIC and SMP init */

	ftrace_init();

	/* Do the rest non-__init'ed, we're now alive */
	rest_init();
}

/* Call all constructor functions linked into the kernel. */
static void __init do_ctors(void)
{
#ifdef CONFIG_CONSTRUCTORS
	ctor_fn_t *call = (ctor_fn_t *) __ctors_start;

	for (; call < (ctor_fn_t *) __ctors_end; call++)
		(*call)();
#endif
}

int initcall_debug;
core_param(initcall_debug, initcall_debug, bool, 0644);

static char msgbuf[64];
static struct boot_trace_call call;
static struct boot_trace_ret ret;

int do_one_initcall(initcall_t fn)
{
	int count = preempt_count();
	ktime_t calltime, delta, rettime;

	if (initcall_debug) {
		call.caller = task_pid_nr(current);
		printk("calling  %pF @ %i\n", fn, call.caller);
		calltime = ktime_get();
		trace_boot_call(&call, fn);
		enable_boot_trace();
	}

	ret.result = fn();

	if (initcall_debug) {
		disable_boot_trace();
		rettime = ktime_get();
		delta = ktime_sub(rettime, calltime);
		ret.duration = (unsigned long long) ktime_to_ns(delta) >> 10;
		trace_boot_ret(&ret, fn);
		printk("initcall %pF returned %d after %Ld usecs\n", fn,
			ret.result, ret.duration);
	}

	msgbuf[0] = 0;

	if (ret.result && ret.result != -ENODEV && initcall_debug)
		sprintf(msgbuf, "error code %d ", ret.result);

	if (preempt_count() != count) {
		strlcat(msgbuf, "preemption imbalance ", sizeof(msgbuf));
		preempt_count() = count;
	}
	if (irqs_disabled()) {
		strlcat(msgbuf, "disabled interrupts ", sizeof(msgbuf));
		local_irq_enable();
	}
	if (msgbuf[0]) {
		printk("initcall %pF returned with %s\n", fn, msgbuf);
	}

	return ret.result;
}


extern initcall_t __initcall_start[], __initcall_end[], __early_initcall_end[];

static void __init do_initcalls(void)
{
	initcall_t *call;

	for (call = __early_initcall_end; call < __initcall_end; call++)
		do_one_initcall(*call);

	/* Make sure there is no pending stuff from the initcall sequence */
	flush_scheduled_work();
}

/*
 * Ok, the machine is now initialized. None of the devices
 * have been touched yet, but the CPU subsystem is up and
 * running, and memory and process management works.
 *
 * Now we can finally start doing some real work..
 */
static void __init do_basic_setup(void)
{
	rcu_init_sched(); /* needed by module_init stage. */
	init_workqueues();
	cpuset_init_smp();
	usermodehelper_init();
	init_tmpfs();
	driver_init();
	init_irq_proc();
	do_ctors();
	do_initcalls();
}

static void __init do_pre_smp_initcalls(void)
{
	initcall_t *call;

	for (call = __initcall_start; call < __early_initcall_end; call++)
		do_one_initcall(*call);
}

static void run_init_process(char *init_filename)
{
	argv_init[0] = init_filename;
	kernel_execve(init_filename, argv_init, envp_init);
}

/* This is a non __init function. Force it to be noinline otherwise gcc
 * makes it inline to init() and it becomes part of init.text section
 */
static noinline int init_post(void)
	__releases(kernel_lock)
{
	/* need to finish all async __init code before freeing the memory */
	async_synchronize_full();
	free_initmem();
	unlock_kernel();
	mark_rodata_ro();
	system_state = SYSTEM_RUNNING;
	numa_default_policy();

	if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0)
		printk(KERN_WARNING "Warning: unable to open an initial console.\n");

	(void) sys_dup(0);
	(void) sys_dup(0);

	current->signal->flags |= SIGNAL_UNKILLABLE;

	if (ramdisk_execute_command) {
		run_init_process(ramdisk_execute_command);
		printk(KERN_WARNING "Failed to execute %s\n",
				ramdisk_execute_command);
	}

	/*
	 * We try each of these until one succeeds.
	 *
	 * The Bourne shell can be used instead of init if we are
	 * trying to recover a really broken machine.
	 */
	if (execute_command) {
		run_init_process(execute_command);
		printk(KERN_WARNING "Failed to execute %s.  Attempting "
					"defaults...\n", execute_command);
	}
	run_init_process("/sbin/init");
	run_init_process("/etc/init");
	run_init_process("/bin/init");
	run_init_process("/bin/sh");

	panic("No init found.  Try passing init= option to kernel.");
}

static int __init kernel_init(void * unused)
{
	lock_kernel();

	/*
	 * init can allocate pages on any node
	 */
	set_mems_allowed(node_possible_map);
	/*
	 * init can run on any cpu.
	 */
	set_cpus_allowed_ptr(current, cpu_all_mask);
	/*
	 * Tell the world that we're going to be the grim
	 * reaper of innocent orphaned children.
	 *
	 * We don't want people to have to make incorrect
	 * assumptions about where in the task array this
	 * can be found.
	 */
	init_pid_ns.child_reaper = current;

	cad_pid = task_pid(current);

	smp_prepare_cpus(setup_max_cpus);

	do_pre_smp_initcalls();
	start_boot_trace();

	smp_init();
	sched_init_smp();

	do_basic_setup();

	/*
	 * check if there is an early userspace init.  If yes, let it do all
	 * the work
	 */

	if (!ramdisk_execute_command)
		ramdisk_execute_command = "/init";

	if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) {
		ramdisk_execute_command = NULL;
		prepare_namespace();
	}

	/*
	 * Ok, we have completed the initial bootup, and
	 * we're essentially up and running. Get rid of the
	 * initmem segments and start the user-mode stuff..
	 */

	init_post();
	return 0;
}
e='author Mark M. Hoffman <mhoffman@lightlink.com> 2005-07-15 21:39:18 -0400 committer Greg Kroah-Hartman <gregkh@suse.de> 2005-09-05 12:14:08 -0400 [PATCH] I2C hwmon: add hwmon sysfs class to drivers' href='/cgit/cgit.cgi/litmus-rt-budgetable-locks.git/.git/commit/drivers/hwmon/pc87360.c?h=update_litmus_2019&id=943b0830cebe4711354945ed3cb44e84152aaca0'>943b0830cebe
f641b588fdfd




1da177e4c3f4

















9a61bf630053
1da177e4c3f4


9a61bf630053
1da177e4c3f4






9a61bf630053
1da177e4c3f4


9a61bf630053
1da177e4c3f4

28f74e71775b





b267e8cdc638



f641b588fdfd

1da177e4c3f4
f641b588fdfd
1da177e4c3f4







f641b588fdfd
1da177e4c3f4






dedc6a7803d9
8ca136741e15


1da177e4c3f4

28f74e71775b
f641b588fdfd
1da177e4c3f4









8ca136741e15
dedc6a7803d9
1da177e4c3f4

28f74e71775b
8ca136741e15

1da177e4c3f4
8ca136741e15
1da177e4c3f4

dedc6a7803d9
8ca136741e15


1da177e4c3f4

28f74e71775b
f641b588fdfd
1da177e4c3f4








dedc6a7803d9
1da177e4c3f4




28f74e71775b
f641b588fdfd
1da177e4c3f4







28f74e71775b
f641b588fdfd
1da177e4c3f4











8ca136741e15
28f74e71775b
f641b588fdfd
1da177e4c3f4









8ca136741e15
28f74e71775b
f641b588fdfd
1da177e4c3f4




















f641b588fdfd
1da177e4c3f4
f641b588fdfd
1da177e4c3f4








f641b588fdfd
1da177e4c3f4










f641b588fdfd
1da177e4c3f4















f641b588fdfd
1da177e4c3f4

9a61bf630053
1da177e4c3f4

f641b588fdfd
1da177e4c3f4












f641b588fdfd
1da177e4c3f4

















28f74e71775b
1da177e4c3f4


28f74e71775b
1da177e4c3f4































28f74e71775b
1da177e4c3f4



28f74e71775b
1da177e4c3f4




















9a61bf630053
1da177e4c3f4



f641b588fdfd

b9783dcebe95

f641b588fdfd



9e991c6fad46
f641b588fdfd


b9783dcebe95

f641b588fdfd


b9783dcebe95



b9acb64a385c
b9783dcebe95
b9acb64a385c


b9783dcebe95




9e991c6fad46
b9783dcebe95
f641b588fdfd



9e991c6fad46
f641b588fdfd










1da177e4c3f4

f641b588fdfd

1da177e4c3f4


9e991c6fad46
1da177e4c3f4





2d8672c5a6ba
1da177e4c3f4



2d8672c5a6ba
9e991c6fad46
1da177e4c3f4


f641b588fdfd














1da177e4c3f4



f641b588fdfd

1da177e4c3f4








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710


                                                        
                                                              






























                                                                         

                                           



                          
                                  
                        
                              
                            
                      
                        
                       
                     
 
                
                                    
                                   

                     








                                                                              



                                                              











                                                             

                                                      






































































































                                                                             
              


                     
                         
                                 

                                 



































                                                                             
                                                       
                                                                  




                                                                           

                                                             


                                                                      
              

   
                                                
                   
                                      

                                    

                                                      





              



                                                                                              

                                                                         




                                                                                            

                                                                            





                                                                                            
                                                                        





                                                                                               
                                                                           




                                                                                                 
                                                         

                                                    
                                       















                                                                                       
                                         

                     

 



















                                                                               
 





                                         




                                                                                        
                                                           
                                                                     
                                                                     




                                                                                             
                                                         

                                                
                                       



                                                                                
                                         


                     




                                                                   
 












                                                         






























                                                                                                
                                                         

                                                
                                       


                                                                         
                                         





                                                                                                
                                                         

                                                
                                       



                                                                         
                                         


                     



















































                                                                              
 




                                                                       















































                                                                            



                                         


                                         
 








                                                                                     
                                                         



                                                                                                        
                                                         











                                                                                           




















                                                         



                                                                                                
                                                                      





                                                                                              
                                                                          





                                                                                              
                                                                          





                                                                                               
                                                                              





                                                                                                 
                                                                  




                                                                                                   
                                                         

                                                
                                       


                                                                           
                                         





                                                                                                   
                                                         

                                                
                                       


                                                                           
                                         





                                                                                                    
                                                         

                                                
                                       


                                                                            
                                         


                     




































                                                                          
 




















































                                                                             




                                         



                                            










                                                           



                                                                                               
                                                                            




                                                                                             
                                                                                




                                                                                             
                                                                                




                                                                                              
                                                                                 




                                                                                                
                                                                    




                                                                                                  
                                                         

                                                
                                       


                                                                             
                                         





                                                                                                  
                                                         

                                                
                                       


                                                                             
                                         





                                                                                                   
                                                         

                                                
                                       


                                                                              
                                         


                     

































                                                                      
 
                                                                                             





                                                                 



























































                                                                               




                                         




                                            












                                                          

                                                                    





                                                         



                                            
                                                                                 







                                             
                                                                






















                                                      
                                                                            





                                                       

                                                                           


                                 
                                   




                                                                








                                                                              









                                                                            

                                                                            

                                                        

                                                                                








                                 
                                                                

              



                                     
                                        
 
                                                                       
                               
 

























                                                    
                          
                        
                                
                                       
                                         
 
                                        

                                                                 
                                                                  
                                                                












                                                                             










                                                                         
                                                            


                                                            
                                            













                                                                         
                                                           

         


                                                  
                                                 
                                                           
                            
 
                               
                                                 



                                                               

                           
                                                    








                                                                 








                                                                      
                                            
                 

                                                                           
         
 
                                           













                                                                         

         


                                                            


                                                     

                            

                 
       
                                                
                                                                           



                                                             









                                                                         
                                                                 
 
                                                               

              
                                                 
 




                                                                  

















                                                                         
                                  


                                                                    
                                    






                                                                           
                                  


                                                                    
                                    

 





                                                                             



                                                                           

                                                             
 
                                                               







                                                                            
                                                             






                                                            
                                  


                                                                         

                                                             
                                                
                                                               









                                                                          
                                                                      
                                           

                                                                  
                                                                      

                                                                             
         
                                                                       

                                    
                                       


                                                                             

                                                                 
                                                
                                                               








                                                                            
                                                   




                                                                         
                                                     
                                                                       







                                                                                
                                                        
                                                                       











                                                                           
                                                                  
                                     
                                                       









                                                                  
                                                                   
                                     
                                                                




















                                                                               
                                                       
 
                                                         








                                                             
                                                  










                                                                              
                                                  















                                                                       
                                                         

             
                                       

                                                                               
                                              












                                                                               
                                                        

















                                                                               
                                                                              


                                                                             
                                                            































                                                                               
                                                                                



                                                                        
                                                              




















                                                                             
                                         



                    

                                                            

                               



                                                         
                                                     


                          

                                                    


                                  



                                                                       
 
                                                                    


                                             




                                                                  
                                                                       
                                     



                                        
                                                             










                                     

                                    

                                   


                                                    
                                                                       





                                                   
                                               



                              
                                
                                                                           


                               














                                                        



                                     

                                                    








                                                   
/*
 *  pc87360.c - Part of lm_sensors, Linux kernel modules
 *              for hardware monitoring
 *  Copyright (C) 2004, 2007 Jean Delvare <khali@linux-fr.org>
 *
 *  Copied from smsc47m1.c:
 *  Copyright (C) 2002 Mark D. Studebaker <mdsxyz123@yahoo.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  Supports the following chips:
 *
 *  Chip        #vin    #fan    #pwm    #temp   devid
 *  PC87360     -       2       2       -       0xE1
 *  PC87363     -       2       2       -       0xE8
 *  PC87364     -       3       3       -       0xE4
 *  PC87365     11      3       3       2       0xE5
 *  PC87366     11      3       3       3-4     0xE9
 *
 *  This driver assumes that no more than one chip is present, and one of
 *  the standard Super-I/O addresses is used (0x2E/0x2F or 0x4E/0x4F).
 */

#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/hwmon-vid.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/acpi.h>
#include <linux/io.h>

static u8 devid;
static struct platform_device *pdev;
static unsigned short extra_isa[3];
static u8 confreg[4];

static int init = 1;
module_param(init, int, 0);
MODULE_PARM_DESC(init,
 "Chip initialization level:\n"
 " 0: None\n"
 "*1: Forcibly enable internal voltage and temperature channels, except in9\n"
 " 2: Forcibly enable all voltage and temperature channels, except in9\n"
 " 3: Forcibly enable all voltage and temperature channels, including in9");

static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");

/*
 * Super-I/O registers and operations
 */

#define DEV	0x07	/* Register: Logical device select */
#define DEVID	0x20	/* Register: Device ID */
#define ACT	0x30	/* Register: Device activation */
#define BASE	0x60	/* Register: Base address */

#define FSCM	0x09	/* Logical device: fans */
#define VLM	0x0d	/* Logical device: voltages */
#define TMS	0x0e	/* Logical device: temperatures */
#define LDNI_MAX 3
static const u8 logdev[LDNI_MAX] = { FSCM, VLM, TMS };

#define LD_FAN		0
#define LD_IN		1
#define LD_TEMP		2

static inline void superio_outb(int sioaddr, int reg, int val)
{
	outb(reg, sioaddr);
	outb(val, sioaddr+1);
}

static inline int superio_inb(int sioaddr, int reg)
{
	outb(reg, sioaddr);
	return inb(sioaddr+1);
}

static inline void superio_exit(int sioaddr)
{
	outb(0x02, sioaddr);
	outb(0x02, sioaddr+1);
}

/*
 * Logical devices
 */

#define PC87360_EXTENT		0x10
#define PC87365_REG_BANK	0x09
#define NO_BANK			0xff

/*
 * Fan registers and conversions
 */

/* nr has to be 0 or 1 (PC87360/87363) or 2 (PC87364/87365/87366) */
#define PC87360_REG_PRESCALE(nr)	(0x00 + 2 * (nr))
#define PC87360_REG_PWM(nr)		(0x01 + 2 * (nr))
#define PC87360_REG_FAN_MIN(nr)		(0x06 + 3 * (nr))
#define PC87360_REG_FAN(nr)		(0x07 + 3 * (nr))
#define PC87360_REG_FAN_STATUS(nr)	(0x08 + 3 * (nr))

#define FAN_FROM_REG(val,div)		((val) == 0 ? 0: \
					 480000 / ((val)*(div)))
#define FAN_TO_REG(val,div)		((val) <= 100 ? 0 : \
					 480000 / ((val)*(div)))
#define FAN_DIV_FROM_REG(val)		(1 << ((val >> 5) & 0x03))
#define FAN_STATUS_FROM_REG(val)	((val) & 0x07)

#define FAN_CONFIG_MONITOR(val,nr)	(((val) >> (2 + nr * 3)) & 1)
#define FAN_CONFIG_CONTROL(val,nr)	(((val) >> (3 + nr * 3)) & 1)
#define FAN_CONFIG_INVERT(val,nr)	(((val) >> (4 + nr * 3)) & 1)

#define PWM_FROM_REG(val,inv)		((inv) ? 255 - (val) : (val))
static inline u8 PWM_TO_REG(int val, int inv)
{
	if (inv)
		val = 255 - val;
	if (val < 0)
		return 0;
	if (val > 255)
		return 255;
	return val;
}

/*
 * Voltage registers and conversions
 */

#define PC87365_REG_IN_CONVRATE		0x07
#define PC87365_REG_IN_CONFIG		0x08
#define PC87365_REG_IN			0x0B
#define PC87365_REG_IN_MIN		0x0D
#define PC87365_REG_IN_MAX		0x0C
#define PC87365_REG_IN_STATUS		0x0A
#define PC87365_REG_IN_ALARMS1		0x00
#define PC87365_REG_IN_ALARMS2		0x01
#define PC87365_REG_VID			0x06

#define IN_FROM_REG(val,ref)		(((val) * (ref) + 128) / 256)
#define IN_TO_REG(val,ref)		((val) < 0 ? 0 : \
					 (val)*256 >= (ref)*255 ? 255: \
					 ((val) * 256 + (ref)/2) / (ref))

/*
 * Temperature registers and conversions
 */

#define PC87365_REG_TEMP_CONFIG		0x08
#define PC87365_REG_TEMP		0x0B
#define PC87365_REG_TEMP_MIN		0x0D
#define PC87365_REG_TEMP_MAX		0x0C
#define PC87365_REG_TEMP_CRIT		0x0E
#define PC87365_REG_TEMP_STATUS		0x0A
#define PC87365_REG_TEMP_ALARMS		0x00

#define TEMP_FROM_REG(val)		((val) * 1000)
#define TEMP_TO_REG(val)		((val) < -55000 ? -55 : \
					 (val) > 127000 ? 127 : \
					 (val) < 0 ? ((val) - 500) / 1000 : \
					 ((val) + 500) / 1000)

/*
 * Device data
 */

struct pc87360_data {
	const char *name;
	struct device *hwmon_dev;
	struct mutex lock;
	struct mutex update_lock;
	char valid;		/* !=0 if following fields are valid */
	unsigned long last_updated;	/* In jiffies */

	int address[3];

	u8 fannr, innr, tempnr;

	u8 fan[3];		/* Register value */
	u8 fan_min[3];		/* Register value */
	u8 fan_status[3];	/* Register value */
	u8 pwm[3];		/* Register value */
	u16 fan_conf;		/* Configuration register values, combined */

	u16 in_vref;		/* 1 mV/bit */
	u8 in[14];		/* Register value */
	u8 in_min[14];		/* Register value */
	u8 in_max[14];		/* Register value */
	u8 in_crit[3];		/* Register value */
	u8 in_status[14];	/* Register value */
	u16 in_alarms;		/* Register values, combined, masked */
	u8 vid_conf;		/* Configuration register value */
	u8 vrm;
	u8 vid;			/* Register value */

	s8 temp[3];		/* Register value */
	s8 temp_min[3];		/* Register value */
	s8 temp_max[3];		/* Register value */
	s8 temp_crit[3];	/* Register value */
	u8 temp_status[3];	/* Register value */
	u8 temp_alarms;		/* Register value, masked */
};

/*
 * Functions declaration
 */

static int pc87360_probe(struct platform_device *pdev);
static int __devexit pc87360_remove(struct platform_device *pdev);

static int pc87360_read_value(struct pc87360_data *data, u8 ldi, u8 bank,
			      u8 reg);
static void pc87360_write_value(struct pc87360_data *data, u8 ldi, u8 bank,
				u8 reg, u8 value);
static void pc87360_init_device(struct platform_device *pdev,
				int use_thermistors);
static struct pc87360_data *pc87360_update_device(struct device *dev);

/*
 * Driver data
 */

static struct platform_driver pc87360_driver = {
	.driver = {
		.owner	= THIS_MODULE,
		.name	= "pc87360",
	},
	.probe		= pc87360_probe,
	.remove		= __devexit_p(pc87360_remove),
};

/*
 * Sysfs stuff
 */

static ssize_t show_fan_input(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", FAN_FROM_REG(data->fan[attr->index],
		       FAN_DIV_FROM_REG(data->fan_status[attr->index])));
}
static ssize_t show_fan_min(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", FAN_FROM_REG(data->fan_min[attr->index],
		       FAN_DIV_FROM_REG(data->fan_status[attr->index])));
}
static ssize_t show_fan_div(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n",
		       FAN_DIV_FROM_REG(data->fan_status[attr->index]));
}
static ssize_t show_fan_status(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n",
		       FAN_STATUS_FROM_REG(data->fan_status[attr->index]));
}
static ssize_t set_fan_min(struct device *dev, struct device_attribute *devattr, const char *buf,
	size_t count)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = dev_get_drvdata(dev);
	long fan_min = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	fan_min = FAN_TO_REG(fan_min, FAN_DIV_FROM_REG(data->fan_status[attr->index]));

	/* If it wouldn't fit, change clock divisor */
	while (fan_min > 255
	    && (data->fan_status[attr->index] & 0x60) != 0x60) {
		fan_min >>= 1;
		data->fan[attr->index] >>= 1;
		data->fan_status[attr->index] += 0x20;
	}
	data->fan_min[attr->index] = fan_min > 255 ? 255 : fan_min;
	pc87360_write_value(data, LD_FAN, NO_BANK, PC87360_REG_FAN_MIN(attr->index),
			    data->fan_min[attr->index]);

	/* Write new divider, preserve alarm bits */
	pc87360_write_value(data, LD_FAN, NO_BANK, PC87360_REG_FAN_STATUS(attr->index),
			    data->fan_status[attr->index] & 0xF9);
	mutex_unlock(&data->update_lock);

	return count;
}

static struct sensor_device_attribute fan_input[] = {
	SENSOR_ATTR(fan1_input, S_IRUGO, show_fan_input, NULL, 0),
	SENSOR_ATTR(fan2_input, S_IRUGO, show_fan_input, NULL, 1),
	SENSOR_ATTR(fan3_input, S_IRUGO, show_fan_input, NULL, 2),
};
static struct sensor_device_attribute fan_status[] = {
	SENSOR_ATTR(fan1_status, S_IRUGO, show_fan_status, NULL, 0),
	SENSOR_ATTR(fan2_status, S_IRUGO, show_fan_status, NULL, 1),
	SENSOR_ATTR(fan3_status, S_IRUGO, show_fan_status, NULL, 2),
};
static struct sensor_device_attribute fan_div[] = {
	SENSOR_ATTR(fan1_div, S_IRUGO, show_fan_div, NULL, 0),
	SENSOR_ATTR(fan2_div, S_IRUGO, show_fan_div, NULL, 1),
	SENSOR_ATTR(fan3_div, S_IRUGO, show_fan_div, NULL, 2),
};
static struct sensor_device_attribute fan_min[] = {
	SENSOR_ATTR(fan1_min, S_IWUSR | S_IRUGO, show_fan_min, set_fan_min, 0),
	SENSOR_ATTR(fan2_min, S_IWUSR | S_IRUGO, show_fan_min, set_fan_min, 1),
	SENSOR_ATTR(fan3_min, S_IWUSR | S_IRUGO, show_fan_min, set_fan_min, 2),
};

#define FAN_UNIT_ATTRS(X)	\
	&fan_input[X].dev_attr.attr,	\
	&fan_status[X].dev_attr.attr,	\
	&fan_div[X].dev_attr.attr,	\
	&fan_min[X].dev_attr.attr

static ssize_t show_pwm(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n",
		       PWM_FROM_REG(data->pwm[attr->index],
				    FAN_CONFIG_INVERT(data->fan_conf,
						      attr->index)));
}
static ssize_t set_pwm(struct device *dev, struct device_attribute *devattr, const char *buf,
	size_t count)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = dev_get_drvdata(dev);
	long val = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	data->pwm[attr->index] = PWM_TO_REG(val,
			      FAN_CONFIG_INVERT(data->fan_conf, attr->index));
	pc87360_write_value(data, LD_FAN, NO_BANK, PC87360_REG_PWM(attr->index),
			    data->pwm[attr->index]);
	mutex_unlock(&data->update_lock);
	return count;
}

static struct sensor_device_attribute pwm[] = {
	SENSOR_ATTR(pwm1, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 0),
	SENSOR_ATTR(pwm2, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 1),
	SENSOR_ATTR(pwm3, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 2),
};

static struct attribute * pc8736x_fan_attr_array[] = {
	FAN_UNIT_ATTRS(0),
	FAN_UNIT_ATTRS(1),
	FAN_UNIT_ATTRS(2),
	&pwm[0].dev_attr.attr,
	&pwm[1].dev_attr.attr,
	&pwm[2].dev_attr.attr,
	NULL
};
static const struct attribute_group pc8736x_fan_group = {
	.attrs = pc8736x_fan_attr_array,
};

static ssize_t show_in_input(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", IN_FROM_REG(data->in[attr->index],
		       data->in_vref));
}
static ssize_t show_in_min(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", IN_FROM_REG(data->in_min[attr->index],
		       data->in_vref));
}
static ssize_t show_in_max(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", IN_FROM_REG(data->in_max[attr->index],
		       data->in_vref));
}
static ssize_t show_in_status(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", data->in_status[attr->index]);
}
static ssize_t set_in_min(struct device *dev, struct device_attribute *devattr, const char *buf,
	size_t count)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = dev_get_drvdata(dev);
	long val = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	data->in_min[attr->index] = IN_TO_REG(val, data->in_vref);
	pc87360_write_value(data, LD_IN, attr->index, PC87365_REG_IN_MIN,
			    data->in_min[attr->index]);
	mutex_unlock(&data->update_lock);
	return count;
}
static ssize_t set_in_max(struct device *dev, struct device_attribute *devattr, const char *buf,
	size_t count)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = dev_get_drvdata(dev);
	long val = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	data->in_max[attr->index] = IN_TO_REG(val,
			       data->in_vref);
	pc87360_write_value(data, LD_IN, attr->index, PC87365_REG_IN_MAX,
			    data->in_max[attr->index]);
	mutex_unlock(&data->update_lock);
	return count;
}

static struct sensor_device_attribute in_input[] = {
	SENSOR_ATTR(in0_input, S_IRUGO, show_in_input, NULL, 0),
	SENSOR_ATTR(in1_input, S_IRUGO, show_in_input, NULL, 1),
	SENSOR_ATTR(in2_input, S_IRUGO, show_in_input, NULL, 2),
	SENSOR_ATTR(in3_input, S_IRUGO, show_in_input, NULL, 3),
	SENSOR_ATTR(in4_input, S_IRUGO, show_in_input, NULL, 4),
	SENSOR_ATTR(in5_input, S_IRUGO, show_in_input, NULL, 5),
	SENSOR_ATTR(in6_input, S_IRUGO, show_in_input, NULL, 6),
	SENSOR_ATTR(in7_input, S_IRUGO, show_in_input, NULL, 7),
	SENSOR_ATTR(in8_input, S_IRUGO, show_in_input, NULL, 8),
	SENSOR_ATTR(in9_input, S_IRUGO, show_in_input, NULL, 9),
	SENSOR_ATTR(in10_input, S_IRUGO, show_in_input, NULL, 10),
};
static struct sensor_device_attribute in_status[] = {
	SENSOR_ATTR(in0_status, S_IRUGO, show_in_status, NULL, 0),
	SENSOR_ATTR(in1_status, S_IRUGO, show_in_status, NULL, 1),
	SENSOR_ATTR(in2_status, S_IRUGO, show_in_status, NULL, 2),
	SENSOR_ATTR(in3_status, S_IRUGO, show_in_status, NULL, 3),
	SENSOR_ATTR(in4_status, S_IRUGO, show_in_status, NULL, 4),
	SENSOR_ATTR(in5_status, S_IRUGO, show_in_status, NULL, 5),
	SENSOR_ATTR(in6_status, S_IRUGO, show_in_status, NULL, 6),
	SENSOR_ATTR(in7_status, S_IRUGO, show_in_status, NULL, 7),
	SENSOR_ATTR(in8_status, S_IRUGO, show_in_status, NULL, 8),
	SENSOR_ATTR(in9_status, S_IRUGO, show_in_status, NULL, 9),
	SENSOR_ATTR(in10_status, S_IRUGO, show_in_status, NULL, 10),
};
static struct sensor_device_attribute in_min[] = {
	SENSOR_ATTR(in0_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 0),
	SENSOR_ATTR(in1_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 1),
	SENSOR_ATTR(in2_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 2),
	SENSOR_ATTR(in3_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 3),
	SENSOR_ATTR(in4_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 4),
	SENSOR_ATTR(in5_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 5),
	SENSOR_ATTR(in6_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 6),
	SENSOR_ATTR(in7_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 7),
	SENSOR_ATTR(in8_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 8),
	SENSOR_ATTR(in9_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 9),
	SENSOR_ATTR(in10_min, S_IWUSR | S_IRUGO, show_in_min, set_in_min, 10),
};
static struct sensor_device_attribute in_max[] = {
	SENSOR_ATTR(in0_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 0),
	SENSOR_ATTR(in1_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 1),
	SENSOR_ATTR(in2_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 2),
	SENSOR_ATTR(in3_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 3),
	SENSOR_ATTR(in4_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 4),
	SENSOR_ATTR(in5_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 5),
	SENSOR_ATTR(in6_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 6),
	SENSOR_ATTR(in7_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 7),
	SENSOR_ATTR(in8_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 8),
	SENSOR_ATTR(in9_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 9),
	SENSOR_ATTR(in10_max, S_IWUSR | S_IRUGO, show_in_max, set_in_max, 10),
};

/* (temp & vin) channel status register alarm bits (pdf sec.11.5.12) */
#define CHAN_ALM_MIN	0x02	/* min limit crossed */
#define CHAN_ALM_MAX	0x04	/* max limit exceeded */
#define TEMP_ALM_CRIT	0x08	/* temp crit exceeded (temp only) */

/* show_in_min/max_alarm() reads data from the per-channel status
   register (sec 11.5.12), not the vin event status registers (sec
   11.5.2) that (legacy) show_in_alarm() resds (via data->in_alarms) */

static ssize_t show_in_min_alarm(struct device *dev,
			struct device_attribute *devattr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	unsigned nr = to_sensor_dev_attr(devattr)->index;

	return sprintf(buf, "%u\n", !!(data->in_status[nr] & CHAN_ALM_MIN));
}
static ssize_t show_in_max_alarm(struct device *dev,
			struct device_attribute *devattr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	unsigned nr = to_sensor_dev_attr(devattr)->index;

	return sprintf(buf, "%u\n", !!(data->in_status[nr] & CHAN_ALM_MAX));
}

static struct sensor_device_attribute in_min_alarm[] = {
	SENSOR_ATTR(in0_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 0),
	SENSOR_ATTR(in1_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 1),
	SENSOR_ATTR(in2_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 2),
	SENSOR_ATTR(in3_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 3),
	SENSOR_ATTR(in4_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 4),
	SENSOR_ATTR(in5_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 5),
	SENSOR_ATTR(in6_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 6),
	SENSOR_ATTR(in7_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 7),
	SENSOR_ATTR(in8_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 8),
	SENSOR_ATTR(in9_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 9),
	SENSOR_ATTR(in10_min_alarm, S_IRUGO, show_in_min_alarm, NULL, 10),
};
static struct sensor_device_attribute in_max_alarm[] = {
	SENSOR_ATTR(in0_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 0),
	SENSOR_ATTR(in1_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 1),
	SENSOR_ATTR(in2_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 2),
	SENSOR_ATTR(in3_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 3),
	SENSOR_ATTR(in4_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 4),
	SENSOR_ATTR(in5_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 5),
	SENSOR_ATTR(in6_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 6),
	SENSOR_ATTR(in7_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 7),
	SENSOR_ATTR(in8_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 8),
	SENSOR_ATTR(in9_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 9),
	SENSOR_ATTR(in10_max_alarm, S_IRUGO, show_in_max_alarm, NULL, 10),
};

#define VIN_UNIT_ATTRS(X) \
	&in_input[X].dev_attr.attr,	\
	&in_status[X].dev_attr.attr,	\
	&in_min[X].dev_attr.attr,	\
	&in_max[X].dev_attr.attr,	\
	&in_min_alarm[X].dev_attr.attr,	\
	&in_max_alarm[X].dev_attr.attr

static ssize_t show_vid(struct device *dev, struct device_attribute *attr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", vid_from_reg(data->vid, data->vrm));
}
static DEVICE_ATTR(cpu0_vid, S_IRUGO, show_vid, NULL);

static ssize_t show_vrm(struct device *dev, struct device_attribute *attr, char *buf)
{
	struct pc87360_data *data = dev_get_drvdata(dev);
	return sprintf(buf, "%u\n", data->vrm);
}
static ssize_t set_vrm(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
	struct pc87360_data *data = dev_get_drvdata(dev);
	data->vrm = simple_strtoul(buf, NULL, 10);
	return count;
}
static DEVICE_ATTR(vrm, S_IRUGO | S_IWUSR, show_vrm, set_vrm);

static ssize_t show_in_alarms(struct device *dev, struct device_attribute *attr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", data->in_alarms);
}
static DEVICE_ATTR(alarms_in, S_IRUGO, show_in_alarms, NULL);

static struct attribute *pc8736x_vin_attr_array[] = {
	VIN_UNIT_ATTRS(0),
	VIN_UNIT_ATTRS(1),
	VIN_UNIT_ATTRS(2),
	VIN_UNIT_ATTRS(3),
	VIN_UNIT_ATTRS(4),
	VIN_UNIT_ATTRS(5),
	VIN_UNIT_ATTRS(6),
	VIN_UNIT_ATTRS(7),
	VIN_UNIT_ATTRS(8),
	VIN_UNIT_ATTRS(9),
	VIN_UNIT_ATTRS(10),
	&dev_attr_cpu0_vid.attr,
	&dev_attr_vrm.attr,
	&dev_attr_alarms_in.attr,
	NULL
};
static const struct attribute_group pc8736x_vin_group = {
	.attrs = pc8736x_vin_attr_array,
};

static ssize_t show_therm_input(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", IN_FROM_REG(data->in[attr->index],
		       data->in_vref));
}
static ssize_t show_therm_min(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", IN_FROM_REG(data->in_min[attr->index],
		       data->in_vref));
}
static ssize_t show_therm_max(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", IN_FROM_REG(data->in_max[attr->index],
		       data->in_vref));
}
static ssize_t show_therm_crit(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", IN_FROM_REG(data->in_crit[attr->index-11],
		       data->in_vref));
}
static ssize_t show_therm_status(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", data->in_status[attr->index]);
}
static ssize_t set_therm_min(struct device *dev, struct device_attribute *devattr, const char *buf,
	size_t count)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = dev_get_drvdata(dev);
	long val = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	data->in_min[attr->index] = IN_TO_REG(val, data->in_vref);
	pc87360_write_value(data, LD_IN, attr->index, PC87365_REG_TEMP_MIN,
			    data->in_min[attr->index]);
	mutex_unlock(&data->update_lock);
	return count;
}
static ssize_t set_therm_max(struct device *dev, struct device_attribute *devattr, const char *buf,
	size_t count)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = dev_get_drvdata(dev);
	long val = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	data->in_max[attr->index] = IN_TO_REG(val, data->in_vref);
	pc87360_write_value(data, LD_IN, attr->index, PC87365_REG_TEMP_MAX,
			    data->in_max[attr->index]);
	mutex_unlock(&data->update_lock);
	return count;
}
static ssize_t set_therm_crit(struct device *dev, struct device_attribute *devattr, const char *buf,
	size_t count)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = dev_get_drvdata(dev);
	long val = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	data->in_crit[attr->index-11] = IN_TO_REG(val, data->in_vref);
	pc87360_write_value(data, LD_IN, attr->index, PC87365_REG_TEMP_CRIT,
			    data->in_crit[attr->index-11]);
	mutex_unlock(&data->update_lock);
	return count;
}

/* the +11 term below reflects the fact that VLM units 11,12,13 are
   used in the chip to measure voltage across the thermistors
*/
static struct sensor_device_attribute therm_input[] = {
	SENSOR_ATTR(temp4_input, S_IRUGO, show_therm_input, NULL, 0+11),
	SENSOR_ATTR(temp5_input, S_IRUGO, show_therm_input, NULL, 1+11),
	SENSOR_ATTR(temp6_input, S_IRUGO, show_therm_input, NULL, 2+11),
};
static struct sensor_device_attribute therm_status[] = {
	SENSOR_ATTR(temp4_status, S_IRUGO, show_therm_status, NULL, 0+11),
	SENSOR_ATTR(temp5_status, S_IRUGO, show_therm_status, NULL, 1+11),
	SENSOR_ATTR(temp6_status, S_IRUGO, show_therm_status, NULL, 2+11),
};
static struct sensor_device_attribute therm_min[] = {
	SENSOR_ATTR(temp4_min, S_IRUGO | S_IWUSR,
		    show_therm_min, set_therm_min, 0+11),
	SENSOR_ATTR(temp5_min, S_IRUGO | S_IWUSR,
		    show_therm_min, set_therm_min, 1+11),
	SENSOR_ATTR(temp6_min, S_IRUGO | S_IWUSR,
		    show_therm_min, set_therm_min, 2+11),
};
static struct sensor_device_attribute therm_max[] = {
	SENSOR_ATTR(temp4_max, S_IRUGO | S_IWUSR,
		    show_therm_max, set_therm_max, 0+11),
	SENSOR_ATTR(temp5_max, S_IRUGO | S_IWUSR,
		    show_therm_max, set_therm_max, 1+11),
	SENSOR_ATTR(temp6_max, S_IRUGO | S_IWUSR,
		    show_therm_max, set_therm_max, 2+11),
};
static struct sensor_device_attribute therm_crit[] = {
	SENSOR_ATTR(temp4_crit, S_IRUGO | S_IWUSR,
		    show_therm_crit, set_therm_crit, 0+11),
	SENSOR_ATTR(temp5_crit, S_IRUGO | S_IWUSR,
		    show_therm_crit, set_therm_crit, 1+11),
	SENSOR_ATTR(temp6_crit, S_IRUGO | S_IWUSR,
		    show_therm_crit, set_therm_crit, 2+11),
};

/* show_therm_min/max_alarm() reads data from the per-channel voltage
   status register (sec 11.5.12) */

static ssize_t show_therm_min_alarm(struct device *dev,
				struct device_attribute *devattr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	unsigned nr = to_sensor_dev_attr(devattr)->index;

	return sprintf(buf, "%u\n", !!(data->in_status[nr] & CHAN_ALM_MIN));
}
static ssize_t show_therm_max_alarm(struct device *dev,
				struct device_attribute *devattr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	unsigned nr = to_sensor_dev_attr(devattr)->index;

	return sprintf(buf, "%u\n", !!(data->in_status[nr] & CHAN_ALM_MAX));
}
static ssize_t show_therm_crit_alarm(struct device *dev,
				struct device_attribute *devattr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	unsigned nr = to_sensor_dev_attr(devattr)->index;

	return sprintf(buf, "%u\n", !!(data->in_status[nr] & TEMP_ALM_CRIT));
}

static struct sensor_device_attribute therm_min_alarm[] = {
	SENSOR_ATTR(temp4_min_alarm, S_IRUGO,
		    show_therm_min_alarm, NULL, 0+11),
	SENSOR_ATTR(temp5_min_alarm, S_IRUGO,
		    show_therm_min_alarm, NULL, 1+11),
	SENSOR_ATTR(temp6_min_alarm, S_IRUGO,
		    show_therm_min_alarm, NULL, 2+11),
};
static struct sensor_device_attribute therm_max_alarm[] = {
	SENSOR_ATTR(temp4_max_alarm, S_IRUGO,
		    show_therm_max_alarm, NULL, 0+11),
	SENSOR_ATTR(temp5_max_alarm, S_IRUGO,
		    show_therm_max_alarm, NULL, 1+11),
	SENSOR_ATTR(temp6_max_alarm, S_IRUGO,
		    show_therm_max_alarm, NULL, 2+11),
};
static struct sensor_device_attribute therm_crit_alarm[] = {
	SENSOR_ATTR(temp4_crit_alarm, S_IRUGO,
		    show_therm_crit_alarm, NULL, 0+11),
	SENSOR_ATTR(temp5_crit_alarm, S_IRUGO,
		    show_therm_crit_alarm, NULL, 1+11),
	SENSOR_ATTR(temp6_crit_alarm, S_IRUGO,
		    show_therm_crit_alarm, NULL, 2+11),
};

#define THERM_UNIT_ATTRS(X) \
	&therm_input[X].dev_attr.attr,	\
	&therm_status[X].dev_attr.attr,	\
	&therm_min[X].dev_attr.attr,	\
	&therm_max[X].dev_attr.attr,	\
	&therm_crit[X].dev_attr.attr,	\
	&therm_min_alarm[X].dev_attr.attr, \
	&therm_max_alarm[X].dev_attr.attr, \
	&therm_crit_alarm[X].dev_attr.attr

static struct attribute * pc8736x_therm_attr_array[] = {
	THERM_UNIT_ATTRS(0),
	THERM_UNIT_ATTRS(1),
	THERM_UNIT_ATTRS(2),
	NULL
};
static const struct attribute_group pc8736x_therm_group = {
	.attrs = pc8736x_therm_attr_array,
};

static ssize_t show_temp_input(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp[attr->index]));
}
static ssize_t show_temp_min(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_min[attr->index]));
}
static ssize_t show_temp_max(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_max[attr->index]));
}
static ssize_t show_temp_crit(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_crit[attr->index]));
}
static ssize_t show_temp_status(struct device *dev, struct device_attribute *devattr, char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%d\n", data->temp_status[attr->index]);
}
static ssize_t set_temp_min(struct device *dev, struct device_attribute *devattr, const char *buf,
	size_t count)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = dev_get_drvdata(dev);
	long val = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	data->temp_min[attr->index] = TEMP_TO_REG(val);
	pc87360_write_value(data, LD_TEMP, attr->index, PC87365_REG_TEMP_MIN,
			    data->temp_min[attr->index]);
	mutex_unlock(&data->update_lock);
	return count;
}
static ssize_t set_temp_max(struct device *dev, struct device_attribute *devattr, const char *buf,
	size_t count)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = dev_get_drvdata(dev);
	long val = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	data->temp_max[attr->index] = TEMP_TO_REG(val);
	pc87360_write_value(data, LD_TEMP, attr->index, PC87365_REG_TEMP_MAX,
			    data->temp_max[attr->index]);
	mutex_unlock(&data->update_lock);
	return count;
}
static ssize_t set_temp_crit(struct device *dev, struct device_attribute *devattr, const char *buf,
	size_t count)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct pc87360_data *data = dev_get_drvdata(dev);
	long val = simple_strtol(buf, NULL, 10);

	mutex_lock(&data->update_lock);
	data->temp_crit[attr->index] = TEMP_TO_REG(val);
	pc87360_write_value(data, LD_TEMP, attr->index, PC87365_REG_TEMP_CRIT,
			    data->temp_crit[attr->index]);
	mutex_unlock(&data->update_lock);
	return count;
}

static struct sensor_device_attribute temp_input[] = {
	SENSOR_ATTR(temp1_input, S_IRUGO, show_temp_input, NULL, 0),
	SENSOR_ATTR(temp2_input, S_IRUGO, show_temp_input, NULL, 1),
	SENSOR_ATTR(temp3_input, S_IRUGO, show_temp_input, NULL, 2),
};
static struct sensor_device_attribute temp_status[] = {
	SENSOR_ATTR(temp1_status, S_IRUGO, show_temp_status, NULL, 0),
	SENSOR_ATTR(temp2_status, S_IRUGO, show_temp_status, NULL, 1),
	SENSOR_ATTR(temp3_status, S_IRUGO, show_temp_status, NULL, 2),
};
static struct sensor_device_attribute temp_min[] = {
	SENSOR_ATTR(temp1_min, S_IRUGO | S_IWUSR,
		    show_temp_min, set_temp_min, 0),
	SENSOR_ATTR(temp2_min, S_IRUGO | S_IWUSR,
		    show_temp_min, set_temp_min, 1),
	SENSOR_ATTR(temp3_min, S_IRUGO | S_IWUSR,
		    show_temp_min, set_temp_min, 2),
};
static struct sensor_device_attribute temp_max[] = {
	SENSOR_ATTR(temp1_max, S_IRUGO | S_IWUSR,
		    show_temp_max, set_temp_max, 0),
	SENSOR_ATTR(temp2_max, S_IRUGO | S_IWUSR,
		    show_temp_max, set_temp_max, 1),
	SENSOR_ATTR(temp3_max, S_IRUGO | S_IWUSR,
		    show_temp_max, set_temp_max, 2),
};
static struct sensor_device_attribute temp_crit[] = {
	SENSOR_ATTR(temp1_crit, S_IRUGO | S_IWUSR,
		    show_temp_crit, set_temp_crit, 0),
	SENSOR_ATTR(temp2_crit, S_IRUGO | S_IWUSR,
		    show_temp_crit, set_temp_crit, 1),
	SENSOR_ATTR(temp3_crit, S_IRUGO | S_IWUSR,
		    show_temp_crit, set_temp_crit, 2),
};

static ssize_t show_temp_alarms(struct device *dev, struct device_attribute *attr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	return sprintf(buf, "%u\n", data->temp_alarms);
}
static DEVICE_ATTR(alarms_temp, S_IRUGO, show_temp_alarms, NULL);

/* show_temp_min/max_alarm() reads data from the per-channel status
   register (sec 12.3.7), not the temp event status registers (sec
   12.3.2) that show_temp_alarm() reads (via data->temp_alarms) */

static ssize_t show_temp_min_alarm(struct device *dev,
			struct device_attribute *devattr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	unsigned nr = to_sensor_dev_attr(devattr)->index;

	return sprintf(buf, "%u\n", !!(data->temp_status[nr] & CHAN_ALM_MIN));
}
static ssize_t show_temp_max_alarm(struct device *dev,
			struct device_attribute *devattr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	unsigned nr = to_sensor_dev_attr(devattr)->index;

	return sprintf(buf, "%u\n", !!(data->temp_status[nr] & CHAN_ALM_MAX));
}
static ssize_t show_temp_crit_alarm(struct device *dev,
			struct device_attribute *devattr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	unsigned nr = to_sensor_dev_attr(devattr)->index;

	return sprintf(buf, "%u\n", !!(data->temp_status[nr] & TEMP_ALM_CRIT));
}

static struct sensor_device_attribute temp_min_alarm[] = {
	SENSOR_ATTR(temp1_min_alarm, S_IRUGO, show_temp_min_alarm, NULL, 0),
	SENSOR_ATTR(temp2_min_alarm, S_IRUGO, show_temp_min_alarm, NULL, 1),
	SENSOR_ATTR(temp3_min_alarm, S_IRUGO, show_temp_min_alarm, NULL, 2),
};
static struct sensor_device_attribute temp_max_alarm[] = {
	SENSOR_ATTR(temp1_max_alarm, S_IRUGO, show_temp_max_alarm, NULL, 0),
	SENSOR_ATTR(temp2_max_alarm, S_IRUGO, show_temp_max_alarm, NULL, 1),
	SENSOR_ATTR(temp3_max_alarm, S_IRUGO, show_temp_max_alarm, NULL, 2),
};
static struct sensor_device_attribute temp_crit_alarm[] = {
	SENSOR_ATTR(temp1_crit_alarm, S_IRUGO, show_temp_crit_alarm, NULL, 0),
	SENSOR_ATTR(temp2_crit_alarm, S_IRUGO, show_temp_crit_alarm, NULL, 1),
	SENSOR_ATTR(temp3_crit_alarm, S_IRUGO, show_temp_crit_alarm, NULL, 2),
};

#define TEMP_FAULT	0x40	/* open diode */
static ssize_t show_temp_fault(struct device *dev,
			struct device_attribute *devattr, char *buf)
{
	struct pc87360_data *data = pc87360_update_device(dev);
	unsigned nr = to_sensor_dev_attr(devattr)->index;

	return sprintf(buf, "%u\n", !!(data->temp_status[nr] & TEMP_FAULT));
}
static struct sensor_device_attribute temp_fault[] = {
	SENSOR_ATTR(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0),
	SENSOR_ATTR(temp2_fault, S_IRUGO, show_temp_fault, NULL, 1),
	SENSOR_ATTR(temp3_fault, S_IRUGO, show_temp_fault, NULL, 2),
};

#define TEMP_UNIT_ATTRS(X) \
	&temp_input[X].dev_attr.attr,	\
	&temp_status[X].dev_attr.attr,	\
	&temp_min[X].dev_attr.attr,	\
	&temp_max[X].dev_attr.attr,	\
	&temp_crit[X].dev_attr.attr,	\
	&temp_min_alarm[X].dev_attr.attr, \
	&temp_max_alarm[X].dev_attr.attr, \
	&temp_crit_alarm[X].dev_attr.attr, \
	&temp_fault[X].dev_attr.attr

static struct attribute * pc8736x_temp_attr_array[] = {
	TEMP_UNIT_ATTRS(0),
	TEMP_UNIT_ATTRS(1),
	TEMP_UNIT_ATTRS(2),
	/* include the few miscellaneous atts here */
	&dev_attr_alarms_temp.attr,
	NULL
};
static const struct attribute_group pc8736x_temp_group = {
	.attrs = pc8736x_temp_attr_array,
};

static ssize_t show_name(struct device *dev,
			struct device_attribute *devattr, char *buf)
{
	struct pc87360_data *data = dev_get_drvdata(dev);
	return sprintf(buf, "%s\n", data->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);

/*
 * Device detection, registration and update
 */

static int __init pc87360_find(int sioaddr, u8 *devid, unsigned short *addresses)
{
	u16 val;
	int i;
	int nrdev; /* logical device count */

	/* No superio_enter */

	/* Identify device */
	val = force_id ? force_id : superio_inb(sioaddr, DEVID);
	switch (val) {
	case 0xE1: /* PC87360 */
	case 0xE8: /* PC87363 */
	case 0xE4: /* PC87364 */
		nrdev = 1;
		break;
	case 0xE5: /* PC87365 */
	case 0xE9: /* PC87366 */
		nrdev = 3;
		break;
	default:
		superio_exit(sioaddr);
		return -ENODEV;
	}
	/* Remember the device id */
	*devid = val;

	for (i = 0; i < nrdev; i++) {
		/* select logical device */
		superio_outb(sioaddr, DEV, logdev[i]);

		val = superio_inb(sioaddr, ACT);
		if (!(val & 0x01)) {
			pr_info("Device 0x%02x not activated\n", logdev[i]);
			continue;
		}

		val = (superio_inb(sioaddr, BASE) << 8)
		    | superio_inb(sioaddr, BASE + 1);
		if (!val) {
			pr_info("Base address not set for device 0x%02x\n",
				logdev[i]);
			continue;
		}

		addresses[i] = val;

		if (i==0) { /* Fans */
			confreg[0] = superio_inb(sioaddr, 0xF0);
			confreg[1] = superio_inb(sioaddr, 0xF1);

			pr_debug("Fan %d: mon=%d ctrl=%d inv=%d\n", 1,
				 (confreg[0] >> 2) & 1, (confreg[0] >> 3) & 1,
				 (confreg[0] >> 4) & 1);
			pr_debug("Fan %d: mon=%d ctrl=%d inv=%d\n", 2,
				 (confreg[0] >> 5) & 1, (confreg[0] >> 6) & 1,
				 (confreg[0] >> 7) & 1);
			pr_debug("Fan %d: mon=%d ctrl=%d inv=%d\n", 3,
				 confreg[1] & 1, (confreg[1] >> 1) & 1,
				 (confreg[1] >> 2) & 1);
		} else if (i==1) { /* Voltages */
			/* Are we using thermistors? */
			if (*devid == 0xE9) { /* PC87366 */
				/* These registers are not logical-device
				   specific, just that we won't need them if
				   we don't use the VLM device */
				confreg[2] = superio_inb(sioaddr, 0x2B);
				confreg[3] = superio_inb(sioaddr, 0x25);

				if (confreg[2] & 0x40) {
					pr_info("Using thermistors for "
						"temperature monitoring\n");
				}
				if (confreg[3] & 0xE0) {
					pr_info("VID inputs routed (mode %u)\n",
						confreg[3] >> 5);
				}
			}
		}
	}

	superio_exit(sioaddr);
	return 0;
}

static int __devinit pc87360_probe(struct platform_device *pdev)
{
	int i;
	struct pc87360_data *data;
	int err = 0;
	const char *name = "pc87360";
	int use_thermistors = 0;
	struct device *dev = &pdev->dev;

	if (!(data = kzalloc(sizeof(struct pc87360_data), GFP_KERNEL)))
		return -ENOMEM;

	data->fannr = 2;
	data->innr = 0;
	data->tempnr = 0;

	switch (devid) {
	case 0xe8:
		name = "pc87363";
		break;
	case 0xe4:
		name = "pc87364";
		data->fannr = 3;
		break;
	case 0xe5:
		name = "pc87365";
		data->fannr = extra_isa[0] ? 3 : 0;
		data->innr = extra_isa[1] ? 11 : 0;
		data->tempnr = extra_isa[2] ? 2 : 0;
		break;
	case 0xe9:
		name = "pc87366";
		data->fannr = extra_isa[0] ? 3 : 0;
		data->innr = extra_isa[1] ? 14 : 0;
		data->tempnr = extra_isa[2] ? 3 : 0;
		break;
	}

	data->name = name;
	data->valid = 0;
	mutex_init(&data->lock);
	mutex_init(&data->update_lock);
	platform_set_drvdata(pdev, data);

	for (i = 0; i < LDNI_MAX; i++) {
		if (((data->address[i] = extra_isa[i]))
		 && !request_region(extra_isa[i], PC87360_EXTENT,
		 		    pc87360_driver.driver.name)) {
			dev_err(dev, "Region 0x%x-0x%x already "
				"in use!\n", extra_isa[i],
				extra_isa[i]+PC87360_EXTENT-1);
			for (i--; i >= 0; i--)
				release_region(extra_isa[i], PC87360_EXTENT);
			err = -EBUSY;
			goto ERROR1;
		}
	}

	/* Retrieve the fans configuration from Super-I/O space */
	if (data->fannr)
		data->fan_conf = confreg[0] | (confreg[1] << 8);

	/* Use the correct reference voltage
	   Unless both the VLM and the TMS logical devices agree to
	   use an external Vref, the internal one is used. */
	if (data->innr) {
		i = pc87360_read_value(data, LD_IN, NO_BANK,
				       PC87365_REG_IN_CONFIG);
		if (data->tempnr) {
			i &= pc87360_read_value(data, LD_TEMP, NO_BANK,
						PC87365_REG_TEMP_CONFIG);
		}
		data->in_vref = (i&0x02) ? 3025 : 2966;
		dev_dbg(dev, "Using %s reference voltage\n",
			(i&0x02) ? "external" : "internal");

		data->vid_conf = confreg[3];
		data->vrm = vid_which_vrm();
	}

	/* Fan clock dividers may be needed before any data is read */
	for (i = 0; i < data->fannr; i++) {
		if (FAN_CONFIG_MONITOR(data->fan_conf, i))
			data->fan_status[i] = pc87360_read_value(data,
					      LD_FAN, NO_BANK,
					      PC87360_REG_FAN_STATUS(i));
	}

	if (init > 0) {
		if (devid == 0xe9 && data->address[1]) /* PC87366 */
			use_thermistors = confreg[2] & 0x40;

		pc87360_init_device(pdev, use_thermistors);
	}

	/* Register all-or-nothing sysfs groups */

	if (data->innr &&
	    (err = sysfs_create_group(&dev->kobj,
				      &pc8736x_vin_group)))
		goto ERROR3;

	if (data->innr == 14 &&
	    (err = sysfs_create_group(&dev->kobj,
				      &pc8736x_therm_group)))
		goto ERROR3;

	/* create device attr-files for varying sysfs groups */

	if (data->tempnr) {
		for (i = 0; i < data->tempnr; i++) {
			if ((err = device_create_file(dev,
					&temp_input[i].dev_attr))
			    || (err = device_create_file(dev,
					&temp_min[i].dev_attr))
			    || (err = device_create_file(dev,
					&temp_max[i].dev_attr))
			    || (err = device_create_file(dev,
					&temp_crit[i].dev_attr))
			    || (err = device_create_file(dev,
					&temp_status[i].dev_attr))
			    || (err = device_create_file(dev,
					&temp_min_alarm[i].dev_attr))
			    || (err = device_create_file(dev,
					&temp_max_alarm[i].dev_attr))
			    || (err = device_create_file(dev,
					&temp_crit_alarm[i].dev_attr))
			    || (err = device_create_file(dev,
					&temp_fault[i].dev_attr)))
				goto ERROR3;
		}
		if ((err = device_create_file(dev, &dev_attr_alarms_temp)))
			goto ERROR3;
	}

	for (i = 0; i < data->fannr; i++) {
		if (FAN_CONFIG_MONITOR(data->fan_conf, i)
		    && ((err = device_create_file(dev,
					&fan_input[i].dev_attr))
			|| (err = device_create_file(dev,
					&fan_min[i].dev_attr))
			|| (err = device_create_file(dev,
					&fan_div[i].dev_attr))
			|| (err = device_create_file(dev,
					&fan_status[i].dev_attr))))
			goto ERROR3;

		if (FAN_CONFIG_CONTROL(data->fan_conf, i)
		    && (err = device_create_file(dev, &pwm[i].dev_attr)))
			goto ERROR3;
	}

	if ((err = device_create_file(dev, &dev_attr_name)))
		goto ERROR3;

	data->hwmon_dev = hwmon_device_register(dev);
	if (IS_ERR(data->hwmon_dev)) {
		err = PTR_ERR(data->hwmon_dev);
		goto ERROR3;
	}
	return 0;

ERROR3:
	device_remove_file(dev, &dev_attr_name);
	/* can still remove groups whose members were added individually */
	sysfs_remove_group(&dev->kobj, &pc8736x_temp_group);
	sysfs_remove_group(&dev->kobj, &pc8736x_fan_group);
	sysfs_remove_group(&dev->kobj, &pc8736x_therm_group);
	sysfs_remove_group(&dev->kobj, &pc8736x_vin_group);
	for (i = 0; i < 3; i++) {
		if (data->address[i]) {
			release_region(data->address[i], PC87360_EXTENT);
		}
	}
ERROR1:
	kfree(data);
	return err;
}

static int __devexit pc87360_remove(struct platform_device *pdev)
{
	struct pc87360_data *data = platform_get_drvdata(pdev);
	int i;

	hwmon_device_unregister(data->hwmon_dev);

	device_remove_file(&pdev->dev, &dev_attr_name);
	sysfs_remove_group(&pdev->dev.kobj, &pc8736x_temp_group);
	sysfs_remove_group(&pdev->dev.kobj, &pc8736x_fan_group);
	sysfs_remove_group(&pdev->dev.kobj, &pc8736x_therm_group);
	sysfs_remove_group(&pdev->dev.kobj, &pc8736x_vin_group);

	for (i = 0; i < 3; i++) {
		if (data->address[i]) {
			release_region(data->address[i], PC87360_EXTENT);
		}
	}
	kfree(data);

	return 0;
}

/* ldi is the logical device index
   bank is for voltages and temperatures only */
static int pc87360_read_value(struct pc87360_data *data, u8 ldi, u8 bank,
			      u8 reg)
{
	int res;

	mutex_lock(&(data->lock));
	if (bank != NO_BANK)
		outb_p(bank, data->address[ldi] + PC87365_REG_BANK);
	res = inb_p(data->address[ldi] + reg);
	mutex_unlock(&(data->lock));

	return res;
}

static void pc87360_write_value(struct pc87360_data *data, u8 ldi, u8 bank,
				u8 reg, u8 value)
{
	mutex_lock(&(data->lock));
	if (bank != NO_BANK)
		outb_p(bank, data->address[ldi] + PC87365_REG_BANK);
	outb_p(value, data->address[ldi] + reg);
	mutex_unlock(&(data->lock));
}

/* (temp & vin) channel conversion status register flags (pdf sec.11.5.12) */
#define CHAN_CNVRTD	0x80	/* new data ready */
#define CHAN_ENA	0x01	/* enabled channel (temp or vin) */
#define CHAN_ALM_ENA	0x10	/* propagate to alarms-reg ?? (chk val!) */
#define CHAN_READY	(CHAN_ENA|CHAN_CNVRTD) /* sample ready mask */

#define TEMP_OTS_OE	0x20	/* OTS Output Enable */
#define VIN_RW1C_MASK	(CHAN_READY|CHAN_ALM_MAX|CHAN_ALM_MIN)   /* 0x87 */
#define TEMP_RW1C_MASK	(VIN_RW1C_MASK|TEMP_ALM_CRIT|TEMP_FAULT) /* 0xCF */

static void pc87360_init_device(struct platform_device *pdev,
				int use_thermistors)
{
	struct pc87360_data *data = platform_get_drvdata(pdev);
	int i, nr;
	const u8 init_in[14] = { 2, 2, 2, 2, 2, 2, 2, 1, 1, 3, 1, 2, 2, 2 };
	const u8 init_temp[3] = { 2, 2, 1 };
	u8 reg;

	if (init >= 2 && data->innr) {
		reg = pc87360_read_value(data, LD_IN, NO_BANK,
					 PC87365_REG_IN_CONVRATE);
		dev_info(&pdev->dev, "VLM conversion set to "
			 "1s period, 160us delay\n");
		pc87360_write_value(data, LD_IN, NO_BANK,
				    PC87365_REG_IN_CONVRATE,
				    (reg & 0xC0) | 0x11);
	}

	nr = data->innr < 11 ? data->innr : 11;
	for (i = 0; i < nr; i++) {
		reg = pc87360_read_value(data, LD_IN, i,
					 PC87365_REG_IN_STATUS);
		dev_dbg(&pdev->dev, "bios in%d status:0x%02x\n", i, reg);
		if (init >= init_in[i]) {
			/* Forcibly enable voltage channel */
			if (!(reg & CHAN_ENA)) {
				dev_dbg(&pdev->dev, "Forcibly "
					"enabling in%d\n", i);
				pc87360_write_value(data, LD_IN, i,
						    PC87365_REG_IN_STATUS,
						    (reg & 0x68) | 0x87);
			}
		}
	}

	/* We can't blindly trust the Super-I/O space configuration bit,
	   most BIOS won't set it properly */
	dev_dbg(&pdev->dev, "bios thermistors:%d\n", use_thermistors);
	for (i = 11; i < data->innr; i++) {
		reg = pc87360_read_value(data, LD_IN, i,
					 PC87365_REG_TEMP_STATUS);
		use_thermistors = use_thermistors || (reg & CHAN_ENA);
		/* thermistors are temp[4-6], measured on vin[11-14] */
		dev_dbg(&pdev->dev, "bios temp%d_status:0x%02x\n", i-7, reg);
	}
	dev_dbg(&pdev->dev, "using thermistors:%d\n", use_thermistors);

	i = use_thermistors ? 2 : 0;
	for (; i < data->tempnr; i++) {
		reg = pc87360_read_value(data, LD_TEMP, i,
					 PC87365_REG_TEMP_STATUS);
		dev_dbg(&pdev->dev, "bios temp%d_status:0x%02x\n", i+1, reg);
		if (init >= init_temp[i]) {
			/* Forcibly enable temperature channel */
			if (!(reg & CHAN_ENA)) {
				dev_dbg(&pdev->dev, "Forcibly "
					"enabling temp%d\n", i+1);
				pc87360_write_value(data, LD_TEMP, i,
						    PC87365_REG_TEMP_STATUS,
						    0xCF);
			}
		}
	}

	if (use_thermistors) {
		for (i = 11; i < data->innr; i++) {
			if (init >= init_in[i]) {
				/* The pin may already be used by thermal
				   diodes */
				reg = pc87360_read_value(data, LD_TEMP,
				      (i-11)/2, PC87365_REG_TEMP_STATUS);
				if (reg & CHAN_ENA) {
					dev_dbg(&pdev->dev, "Skipping "
						"temp%d, pin already in use "
						"by temp%d\n", i-7, (i-11)/2);
					continue;
				}

				/* Forcibly enable thermistor channel */
				reg = pc87360_read_value(data, LD_IN, i,
							 PC87365_REG_IN_STATUS);
				if (!(reg & CHAN_ENA)) {
					dev_dbg(&pdev->dev, "Forcibly "
						"enabling temp%d\n", i-7);
					pc87360_write_value(data, LD_IN, i,
						PC87365_REG_TEMP_STATUS,
						(reg & 0x60) | 0x8F);
				}
			}
		}
	}

	if (data->innr) {
		reg = pc87360_read_value(data, LD_IN, NO_BANK,
					 PC87365_REG_IN_CONFIG);
		dev_dbg(&pdev->dev, "bios vin-cfg:0x%02x\n", reg);
		if (reg & CHAN_ENA) {
			dev_dbg(&pdev->dev, "Forcibly "
				"enabling monitoring (VLM)\n");
			pc87360_write_value(data, LD_IN, NO_BANK,
					    PC87365_REG_IN_CONFIG,
					    reg & 0xFE);
		}
	}

	if (data->tempnr) {
		reg = pc87360_read_value(data, LD_TEMP, NO_BANK,
					 PC87365_REG_TEMP_CONFIG);
		dev_dbg(&pdev->dev, "bios temp-cfg:0x%02x\n", reg);
		if (reg & CHAN_ENA) {
			dev_dbg(&pdev->dev, "Forcibly enabling "
				"monitoring (TMS)\n");
			pc87360_write_value(data, LD_TEMP, NO_BANK,
					    PC87365_REG_TEMP_CONFIG,
					    reg & 0xFE);
		}

		if (init >= 2) {
			/* Chip config as documented by National Semi. */
			pc87360_write_value(data, LD_TEMP, 0xF, 0xA, 0x08);
			/* We voluntarily omit the bank here, in case the
			   sequence itself matters. It shouldn't be a problem,
			   since nobody else is supposed to access the
			   device at that point. */
			pc87360_write_value(data, LD_TEMP, NO_BANK, 0xB, 0x04);
			pc87360_write_value(data, LD_TEMP, NO_BANK, 0xC, 0x35);
			pc87360_write_value(data, LD_TEMP, NO_BANK, 0xD, 0x05);
			pc87360_write_value(data, LD_TEMP, NO_BANK, 0xE, 0x05);
		}
	}
}

static void pc87360_autodiv(struct device *dev, int nr)
{
	struct pc87360_data *data = dev_get_drvdata(dev);
	u8 old_min = data->fan_min[nr];

	/* Increase clock divider if needed and possible */
	if ((data->fan_status[nr] & 0x04) /* overflow flag */
	 || (data->fan[nr] >= 224)) { /* next to overflow */
		if ((data->fan_status[nr] & 0x60) != 0x60) {
			data->fan_status[nr] += 0x20;
			data->fan_min[nr] >>= 1;
			data->fan[nr] >>= 1;
			dev_dbg(dev, "Increasing "
				"clock divider to %d for fan %d\n",
				FAN_DIV_FROM_REG(data->fan_status[nr]), nr+1);
		}
	} else {
		/* Decrease clock divider if possible */
		while (!(data->fan_min[nr] & 0x80) /* min "nails" divider */
		 && data->fan[nr] < 85 /* bad accuracy */
		 && (data->fan_status[nr] & 0x60) != 0x00) {
			data->fan_status[nr] -= 0x20;
			data->fan_min[nr] <<= 1;
			data->fan[nr] <<= 1;
			dev_dbg(dev, "Decreasing "
				"clock divider to %d for fan %d\n",
				FAN_DIV_FROM_REG(data->fan_status[nr]),
				nr+1);
		}
	}

	/* Write new fan min if it changed */
	if (old_min != data->fan_min[nr]) {
		pc87360_write_value(data, LD_FAN, NO_BANK,
				    PC87360_REG_FAN_MIN(nr),
				    data->fan_min[nr]);
	}
}

static struct pc87360_data *pc87360_update_device(struct device *dev)
{
	struct pc87360_data *data = dev_get_drvdata(dev);
	u8 i;

	mutex_lock(&data->update_lock);

	if (time_after(jiffies, data->last_updated + HZ * 2) || !data->valid) {
		dev_dbg(dev, "Data update\n");

		/* Fans */
		for (i = 0; i < data->fannr; i++) {
			if (FAN_CONFIG_MONITOR(data->fan_conf, i)) {
				data->fan_status[i] =
					pc87360_read_value(data, LD_FAN,
					NO_BANK, PC87360_REG_FAN_STATUS(i));
				data->fan[i] = pc87360_read_value(data, LD_FAN,
					       NO_BANK, PC87360_REG_FAN(i));
				data->fan_min[i] = pc87360_read_value(data,
						   LD_FAN, NO_BANK,
						   PC87360_REG_FAN_MIN(i));
				/* Change clock divider if needed */
				pc87360_autodiv(dev, i);
				/* Clear bits and write new divider */
				pc87360_write_value(data, LD_FAN, NO_BANK,
						    PC87360_REG_FAN_STATUS(i),
						    data->fan_status[i]);
			}
			if (FAN_CONFIG_CONTROL(data->fan_conf, i))
				data->pwm[i] = pc87360_read_value(data, LD_FAN,
					       NO_BANK, PC87360_REG_PWM(i));
		}

		/* Voltages */
		for (i = 0; i < data->innr; i++) {
			data->in_status[i] = pc87360_read_value(data, LD_IN, i,
					     PC87365_REG_IN_STATUS);
			/* Clear bits */
			pc87360_write_value(data, LD_IN, i,
					    PC87365_REG_IN_STATUS,
					    data->in_status[i]);
			if ((data->in_status[i] & CHAN_READY) == CHAN_READY) {
				data->in[i] = pc87360_read_value(data, LD_IN,
					      i, PC87365_REG_IN);
			}
			if (data->in_status[i] & CHAN_ENA) {
				data->in_min[i] = pc87360_read_value(data,
						  LD_IN, i,
						  PC87365_REG_IN_MIN);
				data->in_max[i] = pc87360_read_value(data,
						  LD_IN, i,
						  PC87365_REG_IN_MAX);
				if (i >= 11)
					data->in_crit[i-11] =
						pc87360_read_value(data, LD_IN,
						i, PC87365_REG_TEMP_CRIT);
			}
		}
		if (data->innr) {
			data->in_alarms = pc87360_read_value(data, LD_IN,
					  NO_BANK, PC87365_REG_IN_ALARMS1)
					| ((pc87360_read_value(data, LD_IN,
					    NO_BANK, PC87365_REG_IN_ALARMS2)
					    & 0x07) << 8);
			data->vid = (data->vid_conf & 0xE0) ?
				    pc87360_read_value(data, LD_IN,
				    NO_BANK, PC87365_REG_VID) : 0x1F;
		}

		/* Temperatures */
		for (i = 0; i < data->tempnr; i++) {
			data->temp_status[i] = pc87360_read_value(data,
					       LD_TEMP, i,
					       PC87365_REG_TEMP_STATUS);
			/* Clear bits */
			pc87360_write_value(data, LD_TEMP, i,
					    PC87365_REG_TEMP_STATUS,
					    data->temp_status[i]);
			if ((data->temp_status[i] & CHAN_READY) == CHAN_READY) {
				data->temp[i] = pc87360_read_value(data,
						LD_TEMP, i,
						PC87365_REG_TEMP);
			}
			if (data->temp_status[i] & CHAN_ENA) {
				data->temp_min[i] = pc87360_read_value(data,
						    LD_TEMP, i,
						    PC87365_REG_TEMP_MIN);
				data->temp_max[i] = pc87360_read_value(data,
						    LD_TEMP, i,
						    PC87365_REG_TEMP_MAX);
				data->temp_crit[i] = pc87360_read_value(data,
						     LD_TEMP, i,
						     PC87365_REG_TEMP_CRIT);
			}
		}
		if (data->tempnr) {
			data->temp_alarms = pc87360_read_value(data, LD_TEMP,
					    NO_BANK, PC87365_REG_TEMP_ALARMS)
					    & 0x3F;
		}

		data->last_updated = jiffies;
		data->valid = 1;
	}

	mutex_unlock(&data->update_lock);

	return data;
}

static int __init pc87360_device_add(unsigned short address)
{
	struct resource res[3];
	int err, i, res_count;

	pdev = platform_device_alloc("pc87360", address);
	if (!pdev) {
		err = -ENOMEM;
		pr_err("Device allocation failed\n");
		goto exit;
	}

	memset(res, 0, 3 * sizeof(struct resource));
	res_count = 0;
	for (i = 0; i < 3; i++) {
		if (!extra_isa[i])
			continue;
		res[res_count].start = extra_isa[i];
		res[res_count].end = extra_isa[i] + PC87360_EXTENT - 1;
		res[res_count].name = "pc87360",
		res[res_count].flags = IORESOURCE_IO,

		err = acpi_check_resource_conflict(&res[res_count]);
		if (err)
			goto exit_device_put;

		res_count++;
	}

	err = platform_device_add_resources(pdev, res, res_count);
	if (err) {
		pr_err("Device resources addition failed (%d)\n", err);
		goto exit_device_put;
	}

	err = platform_device_add(pdev);
	if (err) {
		pr_err("Device addition failed (%d)\n", err);
		goto exit_device_put;
	}

	return 0;

exit_device_put:
	platform_device_put(pdev);
exit:
	return err;
}

static int __init pc87360_init(void)
{
	int err, i;
	unsigned short address = 0;

	if (pc87360_find(0x2e, &devid, extra_isa)
	 && pc87360_find(0x4e, &devid, extra_isa)) {
		pr_warn("PC8736x not detected, module not inserted\n");
		return -ENODEV;
	}

	/* Arbitrarily pick one of the addresses */
	for (i = 0; i < 3; i++) {
		if (extra_isa[i] != 0x0000) {
			address = extra_isa[i];
			break;
		}
	}

	if (address == 0x0000) {
		pr_warn("No active logical device, module not inserted\n");
		return -ENODEV;
	}

	err = platform_driver_register(&pc87360_driver);
	if (err)
		goto exit;

	/* Sets global pdev as a side effect */
	err = pc87360_device_add(address);
	if (err)
		goto exit_driver;

	return 0;

 exit_driver:
	platform_driver_unregister(&pc87360_driver);
 exit:
	return err;
}

static void __exit pc87360_exit(void)
{
	platform_device_unregister(pdev);
	platform_driver_unregister(&pc87360_driver);
}


MODULE_AUTHOR("Jean Delvare <khali@linux-fr.org>");
MODULE_DESCRIPTION("PC8736x hardware monitor");
MODULE_LICENSE("GPL");

module_init(pc87360_init);
module_exit(pc87360_exit);