1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * Copyright (c) 2004 Evgeniy Polyakov <zbr@ioremap.net>
4 */
5
6#include <linux/delay.h>
7#include <linux/kernel.h>
8#include <linux/module.h>
9#include <linux/moduleparam.h>
10#include <linux/list.h>
11#include <linux/interrupt.h>
12#include <linux/spinlock.h>
13#include <linux/timer.h>
14#include <linux/device.h>
15#include <linux/slab.h>
16#include <linux/sched.h>
17#include <linux/kthread.h>
18#include <linux/freezer.h>
19#include <linux/hwmon.h>
20#include <linux/of.h>
21
22#include <linux/atomic.h>
23
24#include "w1_internal.h"
25#include "w1_netlink.h"
26
27#define W1_FAMILY_DEFAULT	0
28#define W1_FAMILY_DS28E04       0x1C /* for crc quirk */
29
30
31static int w1_timeout = 10;
32module_param_named(timeout, w1_timeout, int, 0);
33MODULE_PARM_DESC(timeout, "time in seconds between automatic slave searches");
34
35static int w1_timeout_us;
36module_param_named(timeout_us, w1_timeout_us, int, 0);
37MODULE_PARM_DESC(timeout_us,
38		 "time in microseconds between automatic slave searches");
39
40/* A search stops when w1_max_slave_count devices have been found in that
41 * search.  The next search will start over and detect the same set of devices
42 * on a static 1-wire bus.  Memory is not allocated based on this number, just
43 * on the number of devices known to the kernel.  Having a high number does not
44 * consume additional resources.  As a special case, if there is only one
45 * device on the network and w1_max_slave_count is set to 1, the device id can
46 * be read directly skipping the normal slower search process.
47 */
48int w1_max_slave_count = 64;
49module_param_named(max_slave_count, w1_max_slave_count, int, 0);
50MODULE_PARM_DESC(max_slave_count,
51	"maximum number of slaves detected in a search");
52
53int w1_max_slave_ttl = 10;
54module_param_named(slave_ttl, w1_max_slave_ttl, int, 0);
55MODULE_PARM_DESC(slave_ttl,
56	"Number of searches not seeing a slave before it will be removed");
57
58DEFINE_MUTEX(w1_mlock);
59LIST_HEAD(w1_masters);
60
61static int w1_master_probe(struct device *dev)
62{
63	return -ENODEV;
64}
65
66static void w1_master_release(struct device *dev)
67{
68	struct w1_master *md = dev_to_w1_master(dev);
69
70	dev_dbg(dev, "%s: Releasing %s.\n", __func__, md->name);
71	memset(md, 0, sizeof(struct w1_master) + sizeof(struct w1_bus_master));
72	kfree(md);
73}
74
75static void w1_slave_release(struct device *dev)
76{
77	struct w1_slave *sl = dev_to_w1_slave(dev);
78
79	dev_dbg(dev, "%s: Releasing %s [%p]\n", __func__, sl->name, sl);
80
81	w1_family_put(sl->family);
82	sl->master->slave_count--;
83}
84
85static ssize_t name_show(struct device *dev, struct device_attribute *attr, char *buf)
86{
87	struct w1_slave *sl = dev_to_w1_slave(dev);
88
89	return sprintf(buf, "%s\n", sl->name);
90}
91static DEVICE_ATTR_RO(name);
92
93static ssize_t id_show(struct device *dev,
94	struct device_attribute *attr, char *buf)
95{
96	struct w1_slave *sl = dev_to_w1_slave(dev);
97	ssize_t count = sizeof(sl->reg_num);
98
99	memcpy(buf, (u8 *)&sl->reg_num, count);
100	return count;
101}
102static DEVICE_ATTR_RO(id);
103
104static struct attribute *w1_slave_attrs[] = {
105	&dev_attr_name.attr,
106	&dev_attr_id.attr,
107	NULL,
108};
109ATTRIBUTE_GROUPS(w1_slave);
110
111/* Default family */
112
113static ssize_t rw_write(struct file *filp, struct kobject *kobj,
114			struct bin_attribute *bin_attr, char *buf, loff_t off,
115			size_t count)
116{
117	struct w1_slave *sl = kobj_to_w1_slave(kobj);
118
119	mutex_lock(&sl->master->mutex);
120	if (w1_reset_select_slave(sl)) {
121		count = 0;
122		goto out_up;
123	}
124
125	w1_write_block(sl->master, buf, count);
126
127out_up:
128	mutex_unlock(&sl->master->mutex);
129	return count;
130}
131
132static ssize_t rw_read(struct file *filp, struct kobject *kobj,
133		       struct bin_attribute *bin_attr, char *buf, loff_t off,
134		       size_t count)
135{
136	struct w1_slave *sl = kobj_to_w1_slave(kobj);
137
138	mutex_lock(&sl->master->mutex);
139	w1_read_block(sl->master, buf, count);
140	mutex_unlock(&sl->master->mutex);
141	return count;
142}
143
144static BIN_ATTR_RW(rw, PAGE_SIZE);
145
146static struct bin_attribute *w1_slave_bin_attrs[] = {
147	&bin_attr_rw,
148	NULL,
149};
150
151static const struct attribute_group w1_slave_default_group = {
152	.bin_attrs = w1_slave_bin_attrs,
153};
154
155static const struct attribute_group *w1_slave_default_groups[] = {
156	&w1_slave_default_group,
157	NULL,
158};
159
160static const struct w1_family_ops w1_default_fops = {
161	.groups		= w1_slave_default_groups,
162};
163
164static struct w1_family w1_default_family = {
165	.fops = &w1_default_fops,
166};
167
168static int w1_uevent(const struct device *dev, struct kobj_uevent_env *env);
169
170static const struct bus_type w1_bus_type = {
171	.name = "w1",
172	.uevent = w1_uevent,
173};
174
175struct device_driver w1_master_driver = {
176	.name = "w1_master_driver",
177	.bus = &w1_bus_type,
178	.probe = w1_master_probe,
179};
180
181struct device w1_master_device = {
182	.parent = NULL,
183	.bus = &w1_bus_type,
184	.init_name = "w1 bus master",
185	.driver = &w1_master_driver,
186	.release = &w1_master_release
187};
188
189static struct device_driver w1_slave_driver = {
190	.name = "w1_slave_driver",
191	.bus = &w1_bus_type,
192};
193
194#if 0
195struct device w1_slave_device = {
196	.parent = NULL,
197	.bus = &w1_bus_type,
198	.init_name = "w1 bus slave",
199	.driver = &w1_slave_driver,
200	.release = &w1_slave_release
201};
202#endif  /*  0  */
203
204static ssize_t w1_master_attribute_show_name(struct device *dev, struct device_attribute *attr, char *buf)
205{
206	struct w1_master *md = dev_to_w1_master(dev);
207	ssize_t count;
208
209	mutex_lock(&md->mutex);
210	count = sprintf(buf, "%s\n", md->name);
211	mutex_unlock(&md->mutex);
212
213	return count;
214}
215
216static ssize_t w1_master_attribute_store_search(struct device * dev,
217						struct device_attribute *attr,
218						const char * buf, size_t count)
219{
220	long tmp;
221	struct w1_master *md = dev_to_w1_master(dev);
222	int ret;
223
224	ret = kstrtol(buf, 0, &tmp);
225	if (ret)
226		return ret;
227
228	mutex_lock(&md->mutex);
229	md->search_count = tmp;
230	mutex_unlock(&md->mutex);
231	/* Only wake if it is going to be searching. */
232	if (tmp)
233		wake_up_process(md->thread);
234
235	return count;
236}
237
238static ssize_t w1_master_attribute_show_search(struct device *dev,
239					       struct device_attribute *attr,
240					       char *buf)
241{
242	struct w1_master *md = dev_to_w1_master(dev);
243	ssize_t count;
244
245	mutex_lock(&md->mutex);
246	count = sprintf(buf, "%d\n", md->search_count);
247	mutex_unlock(&md->mutex);
248
249	return count;
250}
251
252static ssize_t w1_master_attribute_store_pullup(struct device *dev,
253						struct device_attribute *attr,
254						const char *buf, size_t count)
255{
256	long tmp;
257	struct w1_master *md = dev_to_w1_master(dev);
258	int ret;
259
260	ret = kstrtol(buf, 0, &tmp);
261	if (ret)
262		return ret;
263
264	mutex_lock(&md->mutex);
265	md->enable_pullup = tmp;
266	mutex_unlock(&md->mutex);
267
268	return count;
269}
270
271static ssize_t w1_master_attribute_show_pullup(struct device *dev,
272					       struct device_attribute *attr,
273					       char *buf)
274{
275	struct w1_master *md = dev_to_w1_master(dev);
276	ssize_t count;
277
278	mutex_lock(&md->mutex);
279	count = sprintf(buf, "%d\n", md->enable_pullup);
280	mutex_unlock(&md->mutex);
281
282	return count;
283}
284
285static ssize_t w1_master_attribute_show_pointer(struct device *dev, struct device_attribute *attr, char *buf)
286{
287	struct w1_master *md = dev_to_w1_master(dev);
288	ssize_t count;
289
290	mutex_lock(&md->mutex);
291	count = sprintf(buf, "0x%p\n", md->bus_master);
292	mutex_unlock(&md->mutex);
293	return count;
294}
295
296static ssize_t w1_master_attribute_show_timeout(struct device *dev, struct device_attribute *attr, char *buf)
297{
298	return sprintf(buf, "%d\n", w1_timeout);
299}
300
301static ssize_t w1_master_attribute_show_timeout_us(struct device *dev,
302	struct device_attribute *attr, char *buf)
303{
304	return sprintf(buf, "%d\n", w1_timeout_us);
305}
306
307static ssize_t w1_master_attribute_store_max_slave_count(struct device *dev,
308	struct device_attribute *attr, const char *buf, size_t count)
309{
310	int tmp;
311	struct w1_master *md = dev_to_w1_master(dev);
312
313	if (kstrtoint(buf, 0, &tmp) || tmp < 1)
314		return -EINVAL;
315
316	mutex_lock(&md->mutex);
317	md->max_slave_count = tmp;
318	/* allow each time the max_slave_count is updated */
319	clear_bit(W1_WARN_MAX_COUNT, &md->flags);
320	mutex_unlock(&md->mutex);
321
322	return count;
323}
324
325static ssize_t w1_master_attribute_show_max_slave_count(struct device *dev, struct device_attribute *attr, char *buf)
326{
327	struct w1_master *md = dev_to_w1_master(dev);
328	ssize_t count;
329
330	mutex_lock(&md->mutex);
331	count = sprintf(buf, "%d\n", md->max_slave_count);
332	mutex_unlock(&md->mutex);
333	return count;
334}
335
336static ssize_t w1_master_attribute_show_attempts(struct device *dev, struct device_attribute *attr, char *buf)
337{
338	struct w1_master *md = dev_to_w1_master(dev);
339	ssize_t count;
340
341	mutex_lock(&md->mutex);
342	count = sprintf(buf, "%lu\n", md->attempts);
343	mutex_unlock(&md->mutex);
344	return count;
345}
346
347static ssize_t w1_master_attribute_show_slave_count(struct device *dev, struct device_attribute *attr, char *buf)
348{
349	struct w1_master *md = dev_to_w1_master(dev);
350	ssize_t count;
351
352	mutex_lock(&md->mutex);
353	count = sprintf(buf, "%d\n", md->slave_count);
354	mutex_unlock(&md->mutex);
355	return count;
356}
357
358static ssize_t w1_master_attribute_show_slaves(struct device *dev,
359	struct device_attribute *attr, char *buf)
360{
361	struct w1_master *md = dev_to_w1_master(dev);
362	int c = PAGE_SIZE;
363	struct list_head *ent, *n;
364	struct w1_slave *sl = NULL;
365
366	mutex_lock(&md->list_mutex);
367
368	list_for_each_safe(ent, n, &md->slist) {
369		sl = list_entry(ent, struct w1_slave, w1_slave_entry);
370
371		c -= snprintf(buf + PAGE_SIZE - c, c, "%s\n", sl->name);
372	}
373	if (!sl)
374		c -= snprintf(buf + PAGE_SIZE - c, c, "not found.\n");
375
376	mutex_unlock(&md->list_mutex);
377
378	return PAGE_SIZE - c;
379}
380
381static ssize_t w1_master_attribute_show_add(struct device *dev,
382	struct device_attribute *attr, char *buf)
383{
384	int c = PAGE_SIZE;
385	c -= snprintf(buf+PAGE_SIZE - c, c,
386		"write device id xx-xxxxxxxxxxxx to add slave\n");
387	return PAGE_SIZE - c;
388}
389
390static int w1_atoreg_num(struct device *dev, const char *buf, size_t count,
391	struct w1_reg_num *rn)
392{
393	unsigned int family;
394	unsigned long long id;
395	int i;
396	u64 rn64_le;
397
398	/* The CRC value isn't read from the user because the sysfs directory
399	 * doesn't include it and most messages from the bus search don't
400	 * print it either.  It would be unreasonable for the user to then
401	 * provide it.
402	 */
403	const char *error_msg = "bad slave string format, expecting "
404		"ff-dddddddddddd\n";
405
406	if (buf[2] != '-') {
407		dev_err(dev, "%s", error_msg);
408		return -EINVAL;
409	}
410	i = sscanf(buf, "%02x-%012llx", &family, &id);
411	if (i != 2) {
412		dev_err(dev, "%s", error_msg);
413		return -EINVAL;
414	}
415	rn->family = family;
416	rn->id = id;
417
418	rn64_le = cpu_to_le64(*(u64 *)rn);
419	rn->crc = w1_calc_crc8((u8 *)&rn64_le, 7);
420
421#if 0
422	dev_info(dev, "With CRC device is %02x.%012llx.%02x.\n",
423		  rn->family, (unsigned long long)rn->id, rn->crc);
424#endif
425
426	return 0;
427}
428
429/* Searches the slaves in the w1_master and returns a pointer or NULL.
430 * Note: must not hold list_mutex
431 */
432struct w1_slave *w1_slave_search_device(struct w1_master *dev,
433	struct w1_reg_num *rn)
434{
435	struct w1_slave *sl;
436	mutex_lock(&dev->list_mutex);
437	list_for_each_entry(sl, &dev->slist, w1_slave_entry) {
438		if (sl->reg_num.family == rn->family &&
439				sl->reg_num.id == rn->id &&
440				sl->reg_num.crc == rn->crc) {
441			mutex_unlock(&dev->list_mutex);
442			return sl;
443		}
444	}
445	mutex_unlock(&dev->list_mutex);
446	return NULL;
447}
448
449static ssize_t w1_master_attribute_store_add(struct device *dev,
450						struct device_attribute *attr,
451						const char *buf, size_t count)
452{
453	struct w1_master *md = dev_to_w1_master(dev);
454	struct w1_reg_num rn;
455	struct w1_slave *sl;
456	ssize_t result = count;
457
458	if (w1_atoreg_num(dev, buf, count, &rn))
459		return -EINVAL;
460
461	mutex_lock(&md->mutex);
462	sl = w1_slave_search_device(md, &rn);
463	/* It would be nice to do a targeted search one the one-wire bus
464	 * for the new device to see if it is out there or not.  But the
465	 * current search doesn't support that.
466	 */
467	if (sl) {
468		dev_info(dev, "Device %s already exists\n", sl->name);
469		result = -EINVAL;
470	} else {
471		w1_attach_slave_device(md, &rn);
472	}
473	mutex_unlock(&md->mutex);
474
475	return result;
476}
477
478static ssize_t w1_master_attribute_show_remove(struct device *dev,
479	struct device_attribute *attr, char *buf)
480{
481	int c = PAGE_SIZE;
482	c -= snprintf(buf+PAGE_SIZE - c, c,
483		"write device id xx-xxxxxxxxxxxx to remove slave\n");
484	return PAGE_SIZE - c;
485}
486
487static ssize_t w1_master_attribute_store_remove(struct device *dev,
488						struct device_attribute *attr,
489						const char *buf, size_t count)
490{
491	struct w1_master *md = dev_to_w1_master(dev);
492	struct w1_reg_num rn;
493	struct w1_slave *sl;
494	ssize_t result;
495
496	if (w1_atoreg_num(dev, buf, count, &rn))
497		return -EINVAL;
498
499	mutex_lock(&md->mutex);
500	sl = w1_slave_search_device(md, &rn);
501	if (sl) {
502		result = w1_slave_detach(sl);
503		/* refcnt 0 means it was detached in the call */
504		if (result == 0)
505			result = count;
506	} else {
507		dev_info(dev, "Device %02x-%012llx doesn't exists\n", rn.family,
508			(unsigned long long)rn.id);
509		result = -EINVAL;
510	}
511	mutex_unlock(&md->mutex);
512
513	return result;
514}
515
516#define W1_MASTER_ATTR_RO(_name, _mode)				\
517	struct device_attribute w1_master_attribute_##_name =	\
518		__ATTR(w1_master_##_name, _mode,		\
519		       w1_master_attribute_show_##_name, NULL)
520
521#define W1_MASTER_ATTR_RW(_name, _mode)				\
522	struct device_attribute w1_master_attribute_##_name =	\
523		__ATTR(w1_master_##_name, _mode,		\
524		       w1_master_attribute_show_##_name,	\
525		       w1_master_attribute_store_##_name)
526
527static W1_MASTER_ATTR_RO(name, S_IRUGO);
528static W1_MASTER_ATTR_RO(slaves, S_IRUGO);
529static W1_MASTER_ATTR_RO(slave_count, S_IRUGO);
530static W1_MASTER_ATTR_RW(max_slave_count, S_IRUGO | S_IWUSR | S_IWGRP);
531static W1_MASTER_ATTR_RO(attempts, S_IRUGO);
532static W1_MASTER_ATTR_RO(timeout, S_IRUGO);
533static W1_MASTER_ATTR_RO(timeout_us, S_IRUGO);
534static W1_MASTER_ATTR_RO(pointer, S_IRUGO);
535static W1_MASTER_ATTR_RW(search, S_IRUGO | S_IWUSR | S_IWGRP);
536static W1_MASTER_ATTR_RW(pullup, S_IRUGO | S_IWUSR | S_IWGRP);
537static W1_MASTER_ATTR_RW(add, S_IRUGO | S_IWUSR | S_IWGRP);
538static W1_MASTER_ATTR_RW(remove, S_IRUGO | S_IWUSR | S_IWGRP);
539
540static struct attribute *w1_master_default_attrs[] = {
541	&w1_master_attribute_name.attr,
542	&w1_master_attribute_slaves.attr,
543	&w1_master_attribute_slave_count.attr,
544	&w1_master_attribute_max_slave_count.attr,
545	&w1_master_attribute_attempts.attr,
546	&w1_master_attribute_timeout.attr,
547	&w1_master_attribute_timeout_us.attr,
548	&w1_master_attribute_pointer.attr,
549	&w1_master_attribute_search.attr,
550	&w1_master_attribute_pullup.attr,
551	&w1_master_attribute_add.attr,
552	&w1_master_attribute_remove.attr,
553	NULL
554};
555
556static const struct attribute_group w1_master_defattr_group = {
557	.attrs = w1_master_default_attrs,
558};
559
560int w1_create_master_attributes(struct w1_master *master)
561{
562	return sysfs_create_group(&master->dev.kobj, &w1_master_defattr_group);
563}
564
565void w1_destroy_master_attributes(struct w1_master *master)
566{
567	sysfs_remove_group(&master->dev.kobj, &w1_master_defattr_group);
568}
569
570static int w1_uevent(const struct device *dev, struct kobj_uevent_env *env)
571{
572	const struct w1_master *md = NULL;
573	const struct w1_slave *sl = NULL;
574	const char *event_owner, *name;
575	int err = 0;
576
577	if (dev->driver == &w1_master_driver) {
578		md = container_of(dev, struct w1_master, dev);
579		event_owner = "master";
580		name = md->name;
581	} else if (dev->driver == &w1_slave_driver) {
582		sl = container_of(dev, struct w1_slave, dev);
583		event_owner = "slave";
584		name = sl->name;
585	} else {
586		dev_dbg(dev, "Unknown event.\n");
587		return -EINVAL;
588	}
589
590	dev_dbg(dev, "Hotplug event for %s %s, bus_id=%s.\n",
591			event_owner, name, dev_name(dev));
592
593	if (dev->driver != &w1_slave_driver || !sl)
594		goto end;
595
596	err = add_uevent_var(env, "W1_FID=%02X", sl->reg_num.family);
597	if (err)
598		goto end;
599
600	err = add_uevent_var(env, "W1_SLAVE_ID=%024LX",
601			     (unsigned long long)sl->reg_num.id);
602end:
603	return err;
604}
605
606static int w1_family_notify(unsigned long action, struct w1_slave *sl)
607{
608	const struct w1_family_ops *fops;
609	int err;
610
611	fops = sl->family->fops;
612
613	if (!fops)
614		return 0;
615
616	switch (action) {
617	case BUS_NOTIFY_ADD_DEVICE:
618		/* if the family driver needs to initialize something... */
619		if (fops->add_slave) {
620			err = fops->add_slave(sl);
621			if (err < 0) {
622				dev_err(&sl->dev,
623					"add_slave() call failed. err=%d\n",
624					err);
625				return err;
626			}
627		}
628		if (fops->groups) {
629			err = sysfs_create_groups(&sl->dev.kobj, fops->groups);
630			if (err) {
631				dev_err(&sl->dev,
632					"sysfs group creation failed. err=%d\n",
633					err);
634				return err;
635			}
636		}
637		if (IS_REACHABLE(CONFIG_HWMON) && fops->chip_info) {
638			struct device *hwmon
639				= hwmon_device_register_with_info(&sl->dev,
640						"w1_slave_temp", sl,
641						fops->chip_info,
642						NULL);
643			if (IS_ERR(hwmon)) {
644				dev_warn(&sl->dev,
645					 "could not create hwmon device\n");
646			} else {
647				sl->hwmon = hwmon;
648			}
649		}
650		break;
651	case BUS_NOTIFY_DEL_DEVICE:
652		if (IS_REACHABLE(CONFIG_HWMON) && fops->chip_info &&
653			    sl->hwmon)
654			hwmon_device_unregister(sl->hwmon);
655		if (fops->remove_slave)
656			sl->family->fops->remove_slave(sl);
657		if (fops->groups)
658			sysfs_remove_groups(&sl->dev.kobj, fops->groups);
659		break;
660	}
661	return 0;
662}
663
664static int __w1_attach_slave_device(struct w1_slave *sl)
665{
666	int err;
667
668	sl->dev.parent = &sl->master->dev;
669	sl->dev.driver = &w1_slave_driver;
670	sl->dev.bus = &w1_bus_type;
671	sl->dev.release = &w1_slave_release;
672	sl->dev.groups = w1_slave_groups;
673	sl->dev.of_node = of_find_matching_node(sl->master->dev.of_node,
674						sl->family->of_match_table);
675
676	dev_set_name(&sl->dev, "%02x-%012llx",
677		 (unsigned int) sl->reg_num.family,
678		 (unsigned long long) sl->reg_num.id);
679	snprintf(&sl->name[0], sizeof(sl->name),
680		 "%02x-%012llx",
681		 (unsigned int) sl->reg_num.family,
682		 (unsigned long long) sl->reg_num.id);
683
684	dev_dbg(&sl->dev, "%s: registering %s as %p.\n", __func__,
685		dev_name(&sl->dev), sl);
686
687	/* suppress for w1_family_notify before sending KOBJ_ADD */
688	dev_set_uevent_suppress(&sl->dev, true);
689
690	err = device_register(&sl->dev);
691	if (err < 0) {
692		dev_err(&sl->dev,
693			"Device registration [%s] failed. err=%d\n",
694			dev_name(&sl->dev), err);
695		of_node_put(sl->dev.of_node);
696		put_device(&sl->dev);
697		return err;
698	}
699	w1_family_notify(BUS_NOTIFY_ADD_DEVICE, sl);
700
701	dev_set_uevent_suppress(&sl->dev, false);
702	kobject_uevent(&sl->dev.kobj, KOBJ_ADD);
703
704	mutex_lock(&sl->master->list_mutex);
705	list_add_tail(&sl->w1_slave_entry, &sl->master->slist);
706	mutex_unlock(&sl->master->list_mutex);
707
708	return 0;
709}
710
711int w1_attach_slave_device(struct w1_master *dev, struct w1_reg_num *rn)
712{
713	struct w1_slave *sl;
714	struct w1_family *f;
715	int err;
716	struct w1_netlink_msg msg;
717
718	sl = kzalloc(sizeof(struct w1_slave), GFP_KERNEL);
719	if (!sl) {
720		dev_err(&dev->dev,
721			 "%s: failed to allocate new slave device.\n",
722			 __func__);
723		return -ENOMEM;
724	}
725
726
727	sl->owner = THIS_MODULE;
728	sl->master = dev;
729	set_bit(W1_SLAVE_ACTIVE, &sl->flags);
730
731	memset(&msg, 0, sizeof(msg));
732	memcpy(&sl->reg_num, rn, sizeof(sl->reg_num));
733	atomic_set(&sl->refcnt, 1);
734	atomic_inc(&sl->master->refcnt);
735	dev->slave_count++;
736	dev_info(&dev->dev, "Attaching one wire slave %02x.%012llx crc %02x\n",
737		  rn->family, (unsigned long long)rn->id, rn->crc);
738
739	/* slave modules need to be loaded in a context with unlocked mutex */
740	mutex_unlock(&dev->mutex);
741	request_module("w1-family-0x%02X", rn->family);
742	mutex_lock(&dev->mutex);
743
744	spin_lock(&w1_flock);
745	f = w1_family_registered(rn->family);
746	if (!f) {
747		f= &w1_default_family;
748		dev_info(&dev->dev, "Family %x for %02x.%012llx.%02x is not registered.\n",
749			  rn->family, rn->family,
750			  (unsigned long long)rn->id, rn->crc);
751	}
752	__w1_family_get(f);
753	spin_unlock(&w1_flock);
754
755	sl->family = f;
756
757	err = __w1_attach_slave_device(sl);
758	if (err < 0) {
759		dev_err(&dev->dev, "%s: Attaching %s failed.\n", __func__,
760			 sl->name);
761		dev->slave_count--;
762		w1_family_put(sl->family);
763		atomic_dec(&sl->master->refcnt);
764		kfree(sl);
765		return err;
766	}
767
768	sl->ttl = dev->slave_ttl;
769
770	memcpy(msg.id.id, rn, sizeof(msg.id));
771	msg.type = W1_SLAVE_ADD;
772	w1_netlink_send(dev, &msg);
773
774	return 0;
775}
776
777int w1_unref_slave(struct w1_slave *sl)
778{
779	struct w1_master *dev = sl->master;
780	int refcnt;
781	mutex_lock(&dev->list_mutex);
782	refcnt = atomic_sub_return(1, &sl->refcnt);
783	if (refcnt == 0) {
784		struct w1_netlink_msg msg;
785
786		dev_dbg(&sl->dev, "%s: detaching %s [%p].\n", __func__,
787			sl->name, sl);
788
789		list_del(&sl->w1_slave_entry);
790
791		memset(&msg, 0, sizeof(msg));
792		memcpy(msg.id.id, &sl->reg_num, sizeof(msg.id));
793		msg.type = W1_SLAVE_REMOVE;
794		w1_netlink_send(sl->master, &msg);
795
796		w1_family_notify(BUS_NOTIFY_DEL_DEVICE, sl);
797		device_unregister(&sl->dev);
798		#ifdef DEBUG
799		memset(sl, 0, sizeof(*sl));
800		#endif
801		kfree(sl);
802	}
803	atomic_dec(&dev->refcnt);
804	mutex_unlock(&dev->list_mutex);
805	return refcnt;
806}
807
808int w1_slave_detach(struct w1_slave *sl)
809{
810	/* Only detach a slave once as it decreases the refcnt each time. */
811	int destroy_now;
812	mutex_lock(&sl->master->list_mutex);
813	destroy_now = !test_bit(W1_SLAVE_DETACH, &sl->flags);
814	set_bit(W1_SLAVE_DETACH, &sl->flags);
815	mutex_unlock(&sl->master->list_mutex);
816
817	if (destroy_now)
818		destroy_now = !w1_unref_slave(sl);
819	return destroy_now ? 0 : -EBUSY;
820}
821
822struct w1_master *w1_search_master_id(u32 id)
823{
824	struct w1_master *dev = NULL, *iter;
825
826	mutex_lock(&w1_mlock);
827	list_for_each_entry(iter, &w1_masters, w1_master_entry) {
828		if (iter->id == id) {
829			dev = iter;
830			atomic_inc(&iter->refcnt);
831			break;
832		}
833	}
834	mutex_unlock(&w1_mlock);
835
836	return dev;
837}
838
839struct w1_slave *w1_search_slave(struct w1_reg_num *id)
840{
841	struct w1_master *dev;
842	struct w1_slave *sl = NULL, *iter;
843
844	mutex_lock(&w1_mlock);
845	list_for_each_entry(dev, &w1_masters, w1_master_entry) {
846		mutex_lock(&dev->list_mutex);
847		list_for_each_entry(iter, &dev->slist, w1_slave_entry) {
848			if (iter->reg_num.family == id->family &&
849			    iter->reg_num.id == id->id &&
850			    iter->reg_num.crc == id->crc) {
851				sl = iter;
852				atomic_inc(&dev->refcnt);
853				atomic_inc(&iter->refcnt);
854				break;
855			}
856		}
857		mutex_unlock(&dev->list_mutex);
858
859		if (sl)
860			break;
861	}
862	mutex_unlock(&w1_mlock);
863
864	return sl;
865}
866
867void w1_reconnect_slaves(struct w1_family *f, int attach)
868{
869	struct w1_slave *sl, *sln;
870	struct w1_master *dev;
871
872	mutex_lock(&w1_mlock);
873	list_for_each_entry(dev, &w1_masters, w1_master_entry) {
874		dev_dbg(&dev->dev, "Reconnecting slaves in device %s "
875			"for family %02x.\n", dev->name, f->fid);
876		mutex_lock(&dev->mutex);
877		mutex_lock(&dev->list_mutex);
878		list_for_each_entry_safe(sl, sln, &dev->slist, w1_slave_entry) {
879			/* If it is a new family, slaves with the default
880			 * family driver and are that family will be
881			 * connected.  If the family is going away, devices
882			 * matching that family are reconneced.
883			 */
884			if ((attach && sl->family->fid == W1_FAMILY_DEFAULT
885				&& sl->reg_num.family == f->fid) ||
886				(!attach && sl->family->fid == f->fid)) {
887				struct w1_reg_num rn;
888
889				mutex_unlock(&dev->list_mutex);
890				memcpy(&rn, &sl->reg_num, sizeof(rn));
891				/* If it was already in use let the automatic
892				 * scan pick it up again later.
893				 */
894				if (!w1_slave_detach(sl))
895					w1_attach_slave_device(dev, &rn);
896				mutex_lock(&dev->list_mutex);
897			}
898		}
899		dev_dbg(&dev->dev, "Reconnecting slaves in device %s "
900			"has been finished.\n", dev->name);
901		mutex_unlock(&dev->list_mutex);
902		mutex_unlock(&dev->mutex);
903	}
904	mutex_unlock(&w1_mlock);
905}
906
907static int w1_addr_crc_is_valid(struct w1_master *dev, u64 rn)
908{
909	u64 rn_le = cpu_to_le64(rn);
910	struct w1_reg_num *tmp = (struct w1_reg_num *)&rn;
911	u8 crc;
912
913	crc = w1_calc_crc8((u8 *)&rn_le, 7);
914
915	/* quirk:
916	 *   DS28E04 (1w eeprom) has strapping pins to change
917	 *   address, but will not update the crc. So normal rules
918	 *   for consistent w1 addresses are violated. We test
919	 *   with the 7 LSBs of the address forced high.
920	 *
921	 *   (char*)&rn_le = { family, addr_lsb, ..., addr_msb, crc }.
922	 */
923	if (crc != tmp->crc && tmp->family == W1_FAMILY_DS28E04) {
924		u64 corr_le = rn_le;
925
926		((u8 *)&corr_le)[1] |= 0x7f;
927		crc = w1_calc_crc8((u8 *)&corr_le, 7);
928
929		dev_info(&dev->dev, "DS28E04 crc workaround on %02x.%012llx.%02x\n",
930			tmp->family, (unsigned long long)tmp->id, tmp->crc);
931	}
932
933	if (crc != tmp->crc) {
934		dev_dbg(&dev->dev, "w1 addr crc mismatch: %02x.%012llx.%02x != 0x%02x.\n",
935			tmp->family, (unsigned long long)tmp->id, tmp->crc, crc);
936		return 0;
937	}
938	return 1;
939}
940
941void w1_slave_found(struct w1_master *dev, u64 rn)
942{
943	struct w1_slave *sl;
944	struct w1_reg_num *tmp;
945
946	atomic_inc(&dev->refcnt);
947
948	tmp = (struct w1_reg_num *) &rn;
949
950	sl = w1_slave_search_device(dev, tmp);
951	if (sl) {
952		set_bit(W1_SLAVE_ACTIVE, &sl->flags);
953	} else {
954		if (rn && w1_addr_crc_is_valid(dev, rn))
955			w1_attach_slave_device(dev, tmp);
956	}
957
958	atomic_dec(&dev->refcnt);
959}
960
961/**
962 * w1_search() - Performs a ROM Search & registers any devices found.
963 * @dev: The master device to search
964 * @search_type: W1_SEARCH to search all devices, or W1_ALARM_SEARCH
965 * to return only devices in the alarmed state
966 * @cb: Function to call when a device is found
967 *
968 * The 1-wire search is a simple binary tree search.
969 * For each bit of the address, we read two bits and write one bit.
970 * The bit written will put to sleep all devies that don't match that bit.
971 * When the two reads differ, the direction choice is obvious.
972 * When both bits are 0, we must choose a path to take.
973 * When we can scan all 64 bits without having to choose a path, we are done.
974 *
975 * See "Application note 187 1-wire search algorithm" at www.maxim-ic.com
976 *
977 */
978void w1_search(struct w1_master *dev, u8 search_type, w1_slave_found_callback cb)
979{
980	u64 last_rn, rn, tmp64;
981	int i, slave_count = 0;
982	int last_zero, last_device;
983	int search_bit, desc_bit;
984	u8  triplet_ret = 0;
985
986	search_bit = 0;
987	rn = dev->search_id;
988	last_rn = 0;
989	last_device = 0;
990	last_zero = -1;
991
992	desc_bit = 64;
993
994	while ( !last_device && (slave_count++ < dev->max_slave_count) ) {
995		last_rn = rn;
996		rn = 0;
997
998		/*
999		 * Reset bus and all 1-wire device state machines
1000		 * so they can respond to our requests.
1001		 *
1002		 * Return 0 - device(s) present, 1 - no devices present.
1003		 */
1004		mutex_lock(&dev->bus_mutex);
1005		if (w1_reset_bus(dev)) {
1006			mutex_unlock(&dev->bus_mutex);
1007			dev_dbg(&dev->dev, "No devices present on the wire.\n");
1008			break;
1009		}
1010
1011		/* Do fast search on single slave bus */
1012		if (dev->max_slave_count == 1) {
1013			int rv;
1014			w1_write_8(dev, W1_READ_ROM);
1015			rv = w1_read_block(dev, (u8 *)&rn, 8);
1016			mutex_unlock(&dev->bus_mutex);
1017
1018			if (rv == 8 && rn)
1019				cb(dev, rn);
1020
1021			break;
1022		}
1023
1024		/* Start the search */
1025		w1_write_8(dev, search_type);
1026		for (i = 0; i < 64; ++i) {
1027			/* Determine the direction/search bit */
1028			if (i == desc_bit)
1029				search_bit = 1;	  /* took the 0 path last time, so take the 1 path */
1030			else if (i > desc_bit)
1031				search_bit = 0;	  /* take the 0 path on the next branch */
1032			else
1033				search_bit = ((last_rn >> i) & 0x1);
1034
1035			/* Read two bits and write one bit */
1036			triplet_ret = w1_triplet(dev, search_bit);
1037
1038			/* quit if no device responded */
1039			if ( (triplet_ret & 0x03) == 0x03 )
1040				break;
1041
1042			/* If both directions were valid, and we took the 0 path... */
1043			if (triplet_ret == 0)
1044				last_zero = i;
1045
1046			/* extract the direction taken & update the device number */
1047			tmp64 = (triplet_ret >> 2);
1048			rn |= (tmp64 << i);
1049
1050			if (test_bit(W1_ABORT_SEARCH, &dev->flags)) {
1051				mutex_unlock(&dev->bus_mutex);
1052				dev_dbg(&dev->dev, "Abort w1_search\n");
1053				return;
1054			}
1055		}
1056		mutex_unlock(&dev->bus_mutex);
1057
1058		if ( (triplet_ret & 0x03) != 0x03 ) {
1059			if ((desc_bit == last_zero) || (last_zero < 0)) {
1060				last_device = 1;
1061				dev->search_id = 0;
1062			} else {
1063				dev->search_id = rn;
1064			}
1065			desc_bit = last_zero;
1066			cb(dev, rn);
1067		}
1068
1069		if (!last_device && slave_count == dev->max_slave_count &&
1070			!test_bit(W1_WARN_MAX_COUNT, &dev->flags)) {
1071			/* Only max_slave_count will be scanned in a search,
1072			 * but it will start where it left off next search
1073			 * until all ids are identified and then it will start
1074			 * over.  A continued search will report the previous
1075			 * last id as the first id (provided it is still on the
1076			 * bus).
1077			 */
1078			dev_info(&dev->dev, "%s: max_slave_count %d reached, "
1079				"will continue next search.\n", __func__,
1080				dev->max_slave_count);
1081			set_bit(W1_WARN_MAX_COUNT, &dev->flags);
1082		}
1083	}
1084}
1085
1086void w1_search_process_cb(struct w1_master *dev, u8 search_type,
1087	w1_slave_found_callback cb)
1088{
1089	struct w1_slave *sl, *sln;
1090
1091	mutex_lock(&dev->list_mutex);
1092	list_for_each_entry(sl, &dev->slist, w1_slave_entry)
1093		clear_bit(W1_SLAVE_ACTIVE, &sl->flags);
1094	mutex_unlock(&dev->list_mutex);
1095
1096	w1_search_devices(dev, search_type, cb);
1097
1098	mutex_lock(&dev->list_mutex);
1099	list_for_each_entry_safe(sl, sln, &dev->slist, w1_slave_entry) {
1100		if (!test_bit(W1_SLAVE_ACTIVE, &sl->flags) && !--sl->ttl) {
1101			mutex_unlock(&dev->list_mutex);
1102			w1_slave_detach(sl);
1103			mutex_lock(&dev->list_mutex);
1104		}
1105		else if (test_bit(W1_SLAVE_ACTIVE, &sl->flags))
1106			sl->ttl = dev->slave_ttl;
1107	}
1108	mutex_unlock(&dev->list_mutex);
1109
1110	if (dev->search_count > 0)
1111		dev->search_count--;
1112}
1113
1114static void w1_search_process(struct w1_master *dev, u8 search_type)
1115{
1116	w1_search_process_cb(dev, search_type, w1_slave_found);
1117}
1118
1119/**
1120 * w1_process_callbacks() - execute each dev->async_list callback entry
1121 * @dev: w1_master device
1122 *
1123 * The w1 master list_mutex must be held.
1124 *
1125 * Return: 1 if there were commands to executed 0 otherwise
1126 */
1127int w1_process_callbacks(struct w1_master *dev)
1128{
1129	int ret = 0;
1130	struct w1_async_cmd *async_cmd, *async_n;
1131
1132	/* The list can be added to in another thread, loop until it is empty */
1133	while (!list_empty(&dev->async_list)) {
1134		list_for_each_entry_safe(async_cmd, async_n, &dev->async_list,
1135			async_entry) {
1136			/* drop the lock, if it is a search it can take a long
1137			 * time */
1138			mutex_unlock(&dev->list_mutex);
1139			async_cmd->cb(dev, async_cmd);
1140			ret = 1;
1141			mutex_lock(&dev->list_mutex);
1142		}
1143	}
1144	return ret;
1145}
1146
1147int w1_process(void *data)
1148{
1149	struct w1_master *dev = (struct w1_master *) data;
1150	/* As long as w1_timeout is only set by a module parameter the sleep
1151	 * time can be calculated in jiffies once.
1152	 */
1153	const unsigned long jtime =
1154	  usecs_to_jiffies(w1_timeout * 1000000 + w1_timeout_us);
1155	/* remainder if it woke up early */
1156	unsigned long jremain = 0;
1157
1158	atomic_inc(&dev->refcnt);
1159
1160	for (;;) {
1161
1162		if (!jremain && dev->search_count) {
1163			mutex_lock(&dev->mutex);
1164			w1_search_process(dev, W1_SEARCH);
1165			mutex_unlock(&dev->mutex);
1166		}
1167
1168		mutex_lock(&dev->list_mutex);
1169		/* Note, w1_process_callback drops the lock while processing,
1170		 * but locks it again before returning.
1171		 */
1172		if (!w1_process_callbacks(dev) && jremain) {
1173			/* a wake up is either to stop the thread, process
1174			 * callbacks, or search, it isn't process callbacks, so
1175			 * schedule a search.
1176			 */
1177			jremain = 1;
1178		}
1179
1180		__set_current_state(TASK_INTERRUPTIBLE);
1181
1182		/* hold list_mutex until after interruptible to prevent loosing
1183		 * the wakeup signal when async_cmd is added.
1184		 */
1185		mutex_unlock(&dev->list_mutex);
1186
1187		if (kthread_should_stop()) {
1188			__set_current_state(TASK_RUNNING);
1189			break;
1190		}
1191
1192		/* Only sleep when the search is active. */
1193		if (dev->search_count) {
1194			if (!jremain)
1195				jremain = jtime;
1196			jremain = schedule_timeout(jremain);
1197		}
1198		else
1199			schedule();
1200	}
1201
1202	atomic_dec(&dev->refcnt);
1203
1204	return 0;
1205}
1206
1207static int __init w1_init(void)
1208{
1209	int retval;
1210
1211	pr_info("Driver for 1-wire Dallas network protocol.\n");
1212
1213	w1_init_netlink();
1214
1215	retval = bus_register(&w1_bus_type);
1216	if (retval) {
1217		pr_err("Failed to register bus. err=%d.\n", retval);
1218		goto err_out_exit_init;
1219	}
1220
1221	retval = driver_register(&w1_master_driver);
1222	if (retval) {
1223		pr_err("Failed to register master driver. err=%d.\n",
1224			retval);
1225		goto err_out_bus_unregister;
1226	}
1227
1228	retval = driver_register(&w1_slave_driver);
1229	if (retval) {
1230		pr_err("Failed to register slave driver. err=%d.\n",
1231			retval);
1232		goto err_out_master_unregister;
1233	}
1234
1235	return 0;
1236
1237#if 0
1238/* For undoing the slave register if there was a step after it. */
1239err_out_slave_unregister:
1240	driver_unregister(&w1_slave_driver);
1241#endif
1242
1243err_out_master_unregister:
1244	driver_unregister(&w1_master_driver);
1245
1246err_out_bus_unregister:
1247	bus_unregister(&w1_bus_type);
1248
1249err_out_exit_init:
1250	return retval;
1251}
1252
1253static void __exit w1_fini(void)
1254{
1255	struct w1_master *dev, *n;
1256
1257	/* Set netlink removal messages and some cleanup */
1258	list_for_each_entry_safe(dev, n, &w1_masters, w1_master_entry)
1259		__w1_remove_master_device(dev);
1260
1261	w1_fini_netlink();
1262
1263	driver_unregister(&w1_slave_driver);
1264	driver_unregister(&w1_master_driver);
1265	bus_unregister(&w1_bus_type);
1266}
1267
1268module_init(w1_init);
1269module_exit(w1_fini);
1270
1271MODULE_AUTHOR("Evgeniy Polyakov <zbr@ioremap.net>");
1272MODULE_DESCRIPTION("Driver for 1-wire Dallas network protocol.");
1273MODULE_LICENSE("GPL");
1274