1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *	ds2490.c  USB to one wire bridge
4  *
5  * Copyright (c) 2004 Evgeniy Polyakov <zbr@ioremap.net>
6  */
7 
8 #include <linux/module.h>
9 #include <linux/kernel.h>
10 #include <linux/mod_devicetable.h>
11 #include <linux/usb.h>
12 #include <linux/slab.h>
13 
14 #include <linux/w1.h>
15 
16 /* USB Standard */
17 /* USB Control request vendor type */
18 #define VENDOR				0x40
19 
20 /* COMMAND TYPE CODES */
21 #define CONTROL_CMD			0x00
22 #define COMM_CMD			0x01
23 #define MODE_CMD			0x02
24 
25 /* CONTROL COMMAND CODES */
26 #define CTL_RESET_DEVICE		0x0000
27 #define CTL_START_EXE			0x0001
28 #define CTL_RESUME_EXE			0x0002
29 #define CTL_HALT_EXE_IDLE		0x0003
30 #define CTL_HALT_EXE_DONE		0x0004
31 #define CTL_FLUSH_COMM_CMDS		0x0007
32 #define CTL_FLUSH_RCV_BUFFER		0x0008
33 #define CTL_FLUSH_XMT_BUFFER		0x0009
34 #define CTL_GET_COMM_CMDS		0x000A
35 
36 /* MODE COMMAND CODES */
37 #define MOD_PULSE_EN			0x0000
38 #define MOD_SPEED_CHANGE_EN		0x0001
39 #define MOD_1WIRE_SPEED			0x0002
40 #define MOD_STRONG_PU_DURATION		0x0003
41 #define MOD_PULLDOWN_SLEWRATE		0x0004
42 #define MOD_PROG_PULSE_DURATION		0x0005
43 #define MOD_WRITE1_LOWTIME		0x0006
44 #define MOD_DSOW0_TREC			0x0007
45 
46 /* COMMUNICATION COMMAND CODES */
47 #define COMM_ERROR_ESCAPE		0x0601
48 #define COMM_SET_DURATION		0x0012
49 #define COMM_BIT_IO			0x0020
50 #define COMM_PULSE			0x0030
51 #define COMM_1_WIRE_RESET		0x0042
52 #define COMM_BYTE_IO			0x0052
53 #define COMM_MATCH_ACCESS		0x0064
54 #define COMM_BLOCK_IO			0x0074
55 #define COMM_READ_STRAIGHT		0x0080
56 #define COMM_DO_RELEASE			0x6092
57 #define COMM_SET_PATH			0x00A2
58 #define COMM_WRITE_SRAM_PAGE		0x00B2
59 #define COMM_WRITE_EPROM		0x00C4
60 #define COMM_READ_CRC_PROT_PAGE		0x00D4
61 #define COMM_READ_REDIRECT_PAGE_CRC	0x21E4
62 #define COMM_SEARCH_ACCESS		0x00F4
63 
64 /* Communication command bits */
65 #define COMM_TYPE			0x0008
66 #define COMM_SE				0x0008
67 #define COMM_D				0x0008
68 #define COMM_Z				0x0008
69 #define COMM_CH				0x0008
70 #define COMM_SM				0x0008
71 #define COMM_R				0x0008
72 #define COMM_IM				0x0001
73 
74 #define COMM_PS				0x4000
75 #define COMM_PST			0x4000
76 #define COMM_CIB			0x4000
77 #define COMM_RTS			0x4000
78 #define COMM_DT				0x2000
79 #define COMM_SPU			0x1000
80 #define COMM_F				0x0800
81 #define COMM_NTF			0x0400
82 #define COMM_ICP			0x0200
83 #define COMM_RST			0x0100
84 
85 #define PULSE_PROG			0x01
86 #define PULSE_SPUE			0x02
87 
88 #define BRANCH_MAIN			0xCC
89 #define BRANCH_AUX			0x33
90 
91 /* Status flags */
92 #define ST_SPUA				0x01  /* Strong Pull-up is active */
93 #define ST_PRGA				0x02  /* 12V programming pulse is being generated */
94 #define ST_12VP				0x04  /* external 12V programming voltage is present */
95 #define ST_PMOD				0x08  /* DS2490 powered from USB and external sources */
96 #define ST_HALT				0x10  /* DS2490 is currently halted */
97 #define ST_IDLE				0x20  /* DS2490 is currently idle */
98 #define ST_EPOF				0x80
99 /* Status transfer size, 16 bytes status, 16 byte result flags */
100 #define ST_SIZE				0x20
101 
102 /* Result Register flags */
103 #define RR_DETECT			0xA5 /* New device detected */
104 #define RR_NRS				0x01 /* Reset no presence or ... */
105 #define RR_SH				0x02 /* short on reset or set path */
106 #define RR_APP				0x04 /* alarming presence on reset */
107 #define RR_VPP				0x08 /* 12V expected not seen */
108 #define RR_CMP				0x10 /* compare error */
109 #define RR_CRC				0x20 /* CRC error detected */
110 #define RR_RDP				0x40 /* redirected page */
111 #define RR_EOS				0x80 /* end of search error */
112 
113 #define SPEED_NORMAL			0x00
114 #define SPEED_FLEXIBLE			0x01
115 #define SPEED_OVERDRIVE			0x02
116 
117 #define NUM_EP				4
118 #define EP_CONTROL			0
119 #define EP_STATUS			1
120 #define EP_DATA_OUT			2
121 #define EP_DATA_IN			3
122 
123 struct ds_device {
124 	struct list_head	ds_entry;
125 
126 	struct usb_device	*udev;
127 	struct usb_interface	*intf;
128 
129 	int			ep[NUM_EP];
130 
131 	/* Strong PullUp
132 	 * 0: pullup not active, else duration in milliseconds
133 	 */
134 	int			spu_sleep;
135 	/* spu_bit contains COMM_SPU or 0 depending on if the strong pullup
136 	 * should be active or not for writes.
137 	 */
138 	u16			spu_bit;
139 
140 	u8			st_buf[ST_SIZE];
141 	u8			byte_buf;
142 
143 	struct w1_bus_master	master;
144 };
145 
146 struct ds_status {
147 	u8			enable;
148 	u8			speed;
149 	u8			pullup_dur;
150 	u8			ppuls_dur;
151 	u8			pulldown_slew;
152 	u8			write1_time;
153 	u8			write0_time;
154 	u8			reserved0;
155 	u8			status;
156 	u8			command0;
157 	u8			command1;
158 	u8			command_buffer_status;
159 	u8			data_out_buffer_status;
160 	u8			data_in_buffer_status;
161 	u8			reserved1;
162 	u8			reserved2;
163 };
164 
165 static LIST_HEAD(ds_devices);
166 static DEFINE_MUTEX(ds_mutex);
167 
ds_send_control_cmd(struct ds_device * dev,u16 value,u16 index)168 static int ds_send_control_cmd(struct ds_device *dev, u16 value, u16 index)
169 {
170 	int err;
171 
172 	err = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, dev->ep[EP_CONTROL]),
173 			CONTROL_CMD, VENDOR, value, index, NULL, 0, 1000);
174 	if (err < 0) {
175 		pr_err("Failed to send command control message %x.%x: err=%d.\n",
176 				value, index, err);
177 		return err;
178 	}
179 
180 	return err;
181 }
182 
ds_send_control_mode(struct ds_device * dev,u16 value,u16 index)183 static int ds_send_control_mode(struct ds_device *dev, u16 value, u16 index)
184 {
185 	int err;
186 
187 	err = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, dev->ep[EP_CONTROL]),
188 			MODE_CMD, VENDOR, value, index, NULL, 0, 1000);
189 	if (err < 0) {
190 		pr_err("Failed to send mode control message %x.%x: err=%d.\n",
191 				value, index, err);
192 		return err;
193 	}
194 
195 	return err;
196 }
197 
ds_send_control(struct ds_device * dev,u16 value,u16 index)198 static int ds_send_control(struct ds_device *dev, u16 value, u16 index)
199 {
200 	int err;
201 
202 	err = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, dev->ep[EP_CONTROL]),
203 			COMM_CMD, VENDOR, value, index, NULL, 0, 1000);
204 	if (err < 0) {
205 		pr_err("Failed to send control message %x.%x: err=%d.\n",
206 				value, index, err);
207 		return err;
208 	}
209 
210 	return err;
211 }
212 
ds_print_msg(unsigned char * buf,unsigned char * str,int off)213 static inline void ds_print_msg(unsigned char *buf, unsigned char *str, int off)
214 {
215 	pr_info("%45s: %8x\n", str, buf[off]);
216 }
217 
ds_dump_status(struct ds_device * dev,unsigned char * buf,int count)218 static void ds_dump_status(struct ds_device *dev, unsigned char *buf, int count)
219 {
220 	int i;
221 
222 	pr_info("0x%x: count=%d, status: ", dev->ep[EP_STATUS], count);
223 	for (i = 0; i < count; ++i)
224 		pr_info("%02x ", buf[i]);
225 	pr_info("\n");
226 
227 	if (count >= 16) {
228 		ds_print_msg(buf, "enable flag", 0);
229 		ds_print_msg(buf, "1-wire speed", 1);
230 		ds_print_msg(buf, "strong pullup duration", 2);
231 		ds_print_msg(buf, "programming pulse duration", 3);
232 		ds_print_msg(buf, "pulldown slew rate control", 4);
233 		ds_print_msg(buf, "write-1 low time", 5);
234 		ds_print_msg(buf, "data sample offset/write-0 recovery time",
235 			6);
236 		ds_print_msg(buf, "reserved (test register)", 7);
237 		ds_print_msg(buf, "device status flags", 8);
238 		ds_print_msg(buf, "communication command byte 1", 9);
239 		ds_print_msg(buf, "communication command byte 2", 10);
240 		ds_print_msg(buf, "communication command buffer status", 11);
241 		ds_print_msg(buf, "1-wire data output buffer status", 12);
242 		ds_print_msg(buf, "1-wire data input buffer status", 13);
243 		ds_print_msg(buf, "reserved", 14);
244 		ds_print_msg(buf, "reserved", 15);
245 	}
246 	for (i = 16; i < count; ++i) {
247 		if (buf[i] == RR_DETECT) {
248 			ds_print_msg(buf, "new device detect", i);
249 			continue;
250 		}
251 		ds_print_msg(buf, "Result Register Value: ", i);
252 		if (buf[i] & RR_NRS)
253 			pr_info("NRS: Reset no presence or ...\n");
254 		if (buf[i] & RR_SH)
255 			pr_info("SH: short on reset or set path\n");
256 		if (buf[i] & RR_APP)
257 			pr_info("APP: alarming presence on reset\n");
258 		if (buf[i] & RR_VPP)
259 			pr_info("VPP: 12V expected not seen\n");
260 		if (buf[i] & RR_CMP)
261 			pr_info("CMP: compare error\n");
262 		if (buf[i] & RR_CRC)
263 			pr_info("CRC: CRC error detected\n");
264 		if (buf[i] & RR_RDP)
265 			pr_info("RDP: redirected page\n");
266 		if (buf[i] & RR_EOS)
267 			pr_info("EOS: end of search error\n");
268 	}
269 }
270 
ds_recv_status(struct ds_device * dev,struct ds_status * st,bool dump)271 static int ds_recv_status(struct ds_device *dev, struct ds_status *st,
272 			  bool dump)
273 {
274 	int count, err;
275 
276 	if (st)
277 		memset(st, 0, sizeof(*st));
278 
279 	count = 0;
280 	err = usb_interrupt_msg(dev->udev,
281 				usb_rcvintpipe(dev->udev,
282 					       dev->ep[EP_STATUS]),
283 				dev->st_buf, sizeof(dev->st_buf),
284 				&count, 1000);
285 	if (err < 0) {
286 		pr_err("Failed to read 1-wire data from 0x%x: err=%d.\n",
287 		       dev->ep[EP_STATUS], err);
288 		return err;
289 	}
290 
291 	if (dump)
292 		ds_dump_status(dev, dev->st_buf, count);
293 
294 	if (st && count >= sizeof(*st))
295 		memcpy(st, dev->st_buf, sizeof(*st));
296 
297 	return count;
298 }
299 
ds_reset_device(struct ds_device * dev)300 static void ds_reset_device(struct ds_device *dev)
301 {
302 	ds_send_control_cmd(dev, CTL_RESET_DEVICE, 0);
303 	/* Always allow strong pullup which allow individual writes to use
304 	 * the strong pullup.
305 	 */
306 	if (ds_send_control_mode(dev, MOD_PULSE_EN, PULSE_SPUE))
307 		pr_err("ds_reset_device: Error allowing strong pullup\n");
308 	/* Chip strong pullup time was cleared. */
309 	if (dev->spu_sleep) {
310 		/* lower 4 bits are 0, see ds_set_pullup */
311 		u8 del = dev->spu_sleep>>4;
312 		if (ds_send_control(dev, COMM_SET_DURATION | COMM_IM, del))
313 			pr_err("ds_reset_device: Error setting duration\n");
314 	}
315 }
316 
ds_recv_data(struct ds_device * dev,unsigned char * buf,int size)317 static int ds_recv_data(struct ds_device *dev, unsigned char *buf, int size)
318 {
319 	int count, err;
320 
321 	/* Careful on size.  If size is less than what is available in
322 	 * the input buffer, the device fails the bulk transfer and
323 	 * clears the input buffer.  It could read the maximum size of
324 	 * the data buffer, but then do you return the first, last, or
325 	 * some set of the middle size bytes?  As long as the rest of
326 	 * the code is correct there will be size bytes waiting.  A
327 	 * call to ds_wait_status will wait until the device is idle
328 	 * and any data to be received would have been available.
329 	 */
330 	count = 0;
331 	err = usb_bulk_msg(dev->udev, usb_rcvbulkpipe(dev->udev, dev->ep[EP_DATA_IN]),
332 				buf, size, &count, 1000);
333 	if (err < 0) {
334 		pr_info("Clearing ep0x%x.\n", dev->ep[EP_DATA_IN]);
335 		usb_clear_halt(dev->udev, usb_rcvbulkpipe(dev->udev, dev->ep[EP_DATA_IN]));
336 		ds_recv_status(dev, NULL, true);
337 		return err;
338 	}
339 
340 #if 0
341 	{
342 		int i;
343 
344 		printk("%s: count=%d: ", __func__, count);
345 		for (i = 0; i < count; ++i)
346 			printk("%02x ", buf[i]);
347 		printk("\n");
348 	}
349 #endif
350 	return count;
351 }
352 
ds_send_data(struct ds_device * dev,unsigned char * buf,int len)353 static int ds_send_data(struct ds_device *dev, unsigned char *buf, int len)
354 {
355 	int count, err;
356 
357 	count = 0;
358 	err = usb_bulk_msg(dev->udev, usb_sndbulkpipe(dev->udev, dev->ep[EP_DATA_OUT]), buf, len, &count, 1000);
359 	if (err < 0) {
360 		pr_err("Failed to write 1-wire data to ep0x%x: "
361 			"err=%d.\n", dev->ep[EP_DATA_OUT], err);
362 		return err;
363 	}
364 
365 	return err;
366 }
367 
368 #if 0
369 
370 int ds_stop_pulse(struct ds_device *dev, int limit)
371 {
372 	struct ds_status st;
373 	int count = 0, err = 0;
374 
375 	do {
376 		err = ds_send_control(dev, CTL_HALT_EXE_IDLE, 0);
377 		if (err)
378 			break;
379 		err = ds_send_control(dev, CTL_RESUME_EXE, 0);
380 		if (err)
381 			break;
382 		err = ds_recv_status(dev, &st, false);
383 		if (err)
384 			break;
385 
386 		if ((st.status & ST_SPUA) == 0) {
387 			err = ds_send_control_mode(dev, MOD_PULSE_EN, 0);
388 			if (err)
389 				break;
390 		}
391 	} while (++count < limit);
392 
393 	return err;
394 }
395 
396 int ds_detect(struct ds_device *dev, struct ds_status *st)
397 {
398 	int err;
399 
400 	err = ds_send_control_cmd(dev, CTL_RESET_DEVICE, 0);
401 	if (err)
402 		return err;
403 
404 	err = ds_send_control(dev, COMM_SET_DURATION | COMM_IM, 0);
405 	if (err)
406 		return err;
407 
408 	err = ds_send_control(dev, COMM_SET_DURATION | COMM_IM | COMM_TYPE, 0x40);
409 	if (err)
410 		return err;
411 
412 	err = ds_send_control_mode(dev, MOD_PULSE_EN, PULSE_PROG);
413 	if (err)
414 		return err;
415 
416 	err = ds_dump_status(dev, st);
417 
418 	return err;
419 }
420 
421 #endif  /*  0  */
422 
ds_wait_status(struct ds_device * dev,struct ds_status * st)423 static int ds_wait_status(struct ds_device *dev, struct ds_status *st)
424 {
425 	int err, count = 0;
426 
427 	do {
428 		st->status = 0;
429 		err = ds_recv_status(dev, st, false);
430 #if 0
431 		if (err >= 0) {
432 			int i;
433 			printk("0x%x: count=%d, status: ", dev->ep[EP_STATUS], err);
434 			for (i = 0; i < err; ++i)
435 				printk("%02x ", dev->st_buf[i]);
436 			printk("\n");
437 		}
438 #endif
439 	} while (!(st->status & ST_IDLE) && !(err < 0) && ++count < 100);
440 
441 	if (err >= 16 && st->status & ST_EPOF) {
442 		pr_info("Resetting device after ST_EPOF.\n");
443 		ds_reset_device(dev);
444 		/* Always dump the device status. */
445 		count = 101;
446 	}
447 
448 	/* Dump the status for errors or if there is extended return data.
449 	 * The extended status includes new device detection (maybe someone
450 	 * can do something with it).
451 	 */
452 	if (err > 16 || count >= 100 || err < 0)
453 		ds_dump_status(dev, dev->st_buf, err);
454 
455 	/* Extended data isn't an error.  Well, a short is, but the dump
456 	 * would have already told the user that and we can't do anything
457 	 * about it in software anyway.
458 	 */
459 	if (count >= 100 || err < 0)
460 		return -1;
461 	else
462 		return 0;
463 }
464 
ds_reset(struct ds_device * dev)465 static int ds_reset(struct ds_device *dev)
466 {
467 	int err;
468 
469 	/* Other potentionally interesting flags for reset.
470 	 *
471 	 * COMM_NTF: Return result register feedback.  This could be used to
472 	 * detect some conditions such as short, alarming presence, or
473 	 * detect if a new device was detected.
474 	 *
475 	 * COMM_SE which allows SPEED_NORMAL, SPEED_FLEXIBLE, SPEED_OVERDRIVE:
476 	 * Select the data transfer rate.
477 	 */
478 	err = ds_send_control(dev, COMM_1_WIRE_RESET | COMM_IM, SPEED_NORMAL);
479 	if (err)
480 		return err;
481 
482 	return 0;
483 }
484 
485 #if 0
486 static int ds_set_speed(struct ds_device *dev, int speed)
487 {
488 	int err;
489 
490 	if (speed != SPEED_NORMAL && speed != SPEED_FLEXIBLE && speed != SPEED_OVERDRIVE)
491 		return -EINVAL;
492 
493 	if (speed != SPEED_OVERDRIVE)
494 		speed = SPEED_FLEXIBLE;
495 
496 	speed &= 0xff;
497 
498 	err = ds_send_control_mode(dev, MOD_1WIRE_SPEED, speed);
499 	if (err)
500 		return err;
501 
502 	return err;
503 }
504 #endif  /*  0  */
505 
ds_set_pullup(struct ds_device * dev,int delay)506 static int ds_set_pullup(struct ds_device *dev, int delay)
507 {
508 	int err = 0;
509 	u8 del = 1 + (u8)(delay >> 4);
510 	/* Just storing delay would not get the trunication and roundup. */
511 	int ms = del<<4;
512 
513 	/* Enable spu_bit if a delay is set. */
514 	dev->spu_bit = delay ? COMM_SPU : 0;
515 	/* If delay is zero, it has already been disabled, if the time is
516 	 * the same as the hardware was last programmed to, there is also
517 	 * nothing more to do.  Compare with the recalculated value ms
518 	 * rather than del or delay which can have a different value.
519 	 */
520 	if (delay == 0 || ms == dev->spu_sleep)
521 		return err;
522 
523 	err = ds_send_control(dev, COMM_SET_DURATION | COMM_IM, del);
524 	if (err)
525 		return err;
526 
527 	dev->spu_sleep = ms;
528 
529 	return err;
530 }
531 
ds_touch_bit(struct ds_device * dev,u8 bit,u8 * tbit)532 static int ds_touch_bit(struct ds_device *dev, u8 bit, u8 *tbit)
533 {
534 	int err;
535 	struct ds_status st;
536 
537 	err = ds_send_control(dev, COMM_BIT_IO | COMM_IM | (bit ? COMM_D : 0),
538 		0);
539 	if (err)
540 		return err;
541 
542 	ds_wait_status(dev, &st);
543 
544 	err = ds_recv_data(dev, tbit, sizeof(*tbit));
545 	if (err < 0)
546 		return err;
547 
548 	return 0;
549 }
550 
551 #if 0
552 static int ds_write_bit(struct ds_device *dev, u8 bit)
553 {
554 	int err;
555 	struct ds_status st;
556 
557 	/* Set COMM_ICP to write without a readback.  Note, this will
558 	 * produce one time slot, a down followed by an up with COMM_D
559 	 * only determing the timing.
560 	 */
561 	err = ds_send_control(dev, COMM_BIT_IO | COMM_IM | COMM_ICP |
562 		(bit ? COMM_D : 0), 0);
563 	if (err)
564 		return err;
565 
566 	ds_wait_status(dev, &st);
567 
568 	return 0;
569 }
570 #endif
571 
ds_write_byte(struct ds_device * dev,u8 byte)572 static int ds_write_byte(struct ds_device *dev, u8 byte)
573 {
574 	int err;
575 	struct ds_status st;
576 
577 	err = ds_send_control(dev, COMM_BYTE_IO | COMM_IM | dev->spu_bit, byte);
578 	if (err)
579 		return err;
580 
581 	if (dev->spu_bit)
582 		msleep(dev->spu_sleep);
583 
584 	err = ds_wait_status(dev, &st);
585 	if (err)
586 		return err;
587 
588 	err = ds_recv_data(dev, &dev->byte_buf, 1);
589 	if (err < 0)
590 		return err;
591 
592 	return !(byte == dev->byte_buf);
593 }
594 
ds_read_byte(struct ds_device * dev,u8 * byte)595 static int ds_read_byte(struct ds_device *dev, u8 *byte)
596 {
597 	int err;
598 	struct ds_status st;
599 
600 	err = ds_send_control(dev, COMM_BYTE_IO | COMM_IM, 0xff);
601 	if (err)
602 		return err;
603 
604 	ds_wait_status(dev, &st);
605 
606 	err = ds_recv_data(dev, byte, sizeof(*byte));
607 	if (err < 0)
608 		return err;
609 
610 	return 0;
611 }
612 
ds_read_block(struct ds_device * dev,u8 * buf,int len)613 static int ds_read_block(struct ds_device *dev, u8 *buf, int len)
614 {
615 	struct ds_status st;
616 	int err;
617 
618 	if (len > 64*1024)
619 		return -E2BIG;
620 
621 	memset(buf, 0xFF, len);
622 
623 	err = ds_send_data(dev, buf, len);
624 	if (err < 0)
625 		return err;
626 
627 	err = ds_send_control(dev, COMM_BLOCK_IO | COMM_IM, len);
628 	if (err)
629 		return err;
630 
631 	ds_wait_status(dev, &st);
632 
633 	memset(buf, 0x00, len);
634 	err = ds_recv_data(dev, buf, len);
635 
636 	return err;
637 }
638 
ds_write_block(struct ds_device * dev,u8 * buf,int len)639 static int ds_write_block(struct ds_device *dev, u8 *buf, int len)
640 {
641 	int err;
642 	struct ds_status st;
643 
644 	err = ds_send_data(dev, buf, len);
645 	if (err < 0)
646 		return err;
647 
648 	err = ds_send_control(dev, COMM_BLOCK_IO | COMM_IM | dev->spu_bit, len);
649 	if (err)
650 		return err;
651 
652 	if (dev->spu_bit)
653 		msleep(dev->spu_sleep);
654 
655 	ds_wait_status(dev, &st);
656 
657 	err = ds_recv_data(dev, buf, len);
658 	if (err < 0)
659 		return err;
660 
661 	return !(err == len);
662 }
663 
ds9490r_search(void * data,struct w1_master * master,u8 search_type,w1_slave_found_callback callback)664 static void ds9490r_search(void *data, struct w1_master *master,
665 	u8 search_type, w1_slave_found_callback callback)
666 {
667 	/* When starting with an existing id, the first id returned will
668 	 * be that device (if it is still on the bus most likely).
669 	 *
670 	 * If the number of devices found is less than or equal to the
671 	 * search_limit, that number of IDs will be returned.  If there are
672 	 * more, search_limit IDs will be returned followed by a non-zero
673 	 * discrepency value.
674 	 */
675 	struct ds_device *dev = data;
676 	int err;
677 	u16 value, index;
678 	struct ds_status st;
679 	int search_limit;
680 	int found = 0;
681 	int i;
682 
683 	/* DS18b20 spec, 13.16 ms per device, 75 per second, sleep for
684 	 * discovering 8 devices (1 bulk transfer and 1/2 FIFO size) at a time.
685 	 */
686 	const unsigned long jtime = msecs_to_jiffies(1000*8/75);
687 	/* FIFO 128 bytes, bulk packet size 64, read a multiple of the
688 	 * packet size.
689 	 */
690 	const size_t bufsize = 2 * 64;
691 	u64 *buf, *found_ids;
692 
693 	buf = kmalloc(bufsize, GFP_KERNEL);
694 	if (!buf)
695 		return;
696 
697 	/*
698 	 * We are holding the bus mutex during the scan, but adding devices via the
699 	 * callback needs the bus to be unlocked. So we queue up found ids here.
700 	 */
701 	found_ids = kmalloc_array(master->max_slave_count, sizeof(u64), GFP_KERNEL);
702 	if (!found_ids) {
703 		kfree(buf);
704 		return;
705 	}
706 
707 	mutex_lock(&master->bus_mutex);
708 
709 	/* address to start searching at */
710 	if (ds_send_data(dev, (u8 *)&master->search_id, 8) < 0)
711 		goto search_out;
712 	master->search_id = 0;
713 
714 	value = COMM_SEARCH_ACCESS | COMM_IM | COMM_RST | COMM_SM | COMM_F |
715 		COMM_RTS;
716 	search_limit = master->max_slave_count;
717 	if (search_limit > 255)
718 		search_limit = 0;
719 	index = search_type | (search_limit << 8);
720 	if (ds_send_control(dev, value, index) < 0)
721 		goto search_out;
722 
723 	do {
724 		schedule_timeout(jtime);
725 
726 		err = ds_recv_status(dev, &st, false);
727 		if (err < 0 || err < sizeof(st))
728 			break;
729 
730 		if (st.data_in_buffer_status) {
731 			/* Bulk in can receive partial ids, but when it does
732 			 * they fail crc and will be discarded anyway.
733 			 * That has only been seen when status in buffer
734 			 * is 0 and bulk is read anyway, so don't read
735 			 * bulk without first checking if status says there
736 			 * is data to read.
737 			 */
738 			err = ds_recv_data(dev, (u8 *)buf, bufsize);
739 			if (err < 0)
740 				break;
741 			for (i = 0; i < err/8; ++i) {
742 				found_ids[found++] = buf[i];
743 				/* can't know if there will be a discrepancy
744 				 * value after until the next id */
745 				if (found == search_limit) {
746 					master->search_id = buf[i];
747 					break;
748 				}
749 			}
750 		}
751 
752 		if (test_bit(W1_ABORT_SEARCH, &master->flags))
753 			break;
754 	} while (!(st.status & (ST_IDLE | ST_HALT)));
755 
756 	/* only continue the search if some weren't found */
757 	if (found <= search_limit) {
758 		master->search_id = 0;
759 	} else if (!test_bit(W1_WARN_MAX_COUNT, &master->flags)) {
760 		/* Only max_slave_count will be scanned in a search,
761 		 * but it will start where it left off next search
762 		 * until all ids are identified and then it will start
763 		 * over.  A continued search will report the previous
764 		 * last id as the first id (provided it is still on the
765 		 * bus).
766 		 */
767 		dev_info(&dev->udev->dev, "%s: max_slave_count %d reached, "
768 			"will continue next search.\n", __func__,
769 			master->max_slave_count);
770 		set_bit(W1_WARN_MAX_COUNT, &master->flags);
771 	}
772 
773 search_out:
774 	mutex_unlock(&master->bus_mutex);
775 	kfree(buf);
776 
777 	for (i = 0; i < found; i++) /* run callback for all queued up IDs */
778 		callback(master, found_ids[i]);
779 	kfree(found_ids);
780 }
781 
782 #if 0
783 /*
784  * FIXME: if this disabled code is ever used in the future all ds_send_data()
785  * calls must be changed to use a DMAable buffer.
786  */
787 static int ds_match_access(struct ds_device *dev, u64 init)
788 {
789 	int err;
790 	struct ds_status st;
791 
792 	err = ds_send_data(dev, (unsigned char *)&init, sizeof(init));
793 	if (err)
794 		return err;
795 
796 	ds_wait_status(dev, &st);
797 
798 	err = ds_send_control(dev, COMM_MATCH_ACCESS | COMM_IM | COMM_RST, 0x0055);
799 	if (err)
800 		return err;
801 
802 	ds_wait_status(dev, &st);
803 
804 	return 0;
805 }
806 
807 static int ds_set_path(struct ds_device *dev, u64 init)
808 {
809 	int err;
810 	struct ds_status st;
811 	u8 buf[9];
812 
813 	memcpy(buf, &init, 8);
814 	buf[8] = BRANCH_MAIN;
815 
816 	err = ds_send_data(dev, buf, sizeof(buf));
817 	if (err)
818 		return err;
819 
820 	ds_wait_status(dev, &st);
821 
822 	err = ds_send_control(dev, COMM_SET_PATH | COMM_IM | COMM_RST, 0);
823 	if (err)
824 		return err;
825 
826 	ds_wait_status(dev, &st);
827 
828 	return 0;
829 }
830 
831 #endif  /*  0  */
832 
ds9490r_touch_bit(void * data,u8 bit)833 static u8 ds9490r_touch_bit(void *data, u8 bit)
834 {
835 	struct ds_device *dev = data;
836 
837 	if (ds_touch_bit(dev, bit, &dev->byte_buf))
838 		return 0;
839 
840 	return dev->byte_buf;
841 }
842 
843 #if 0
844 static void ds9490r_write_bit(void *data, u8 bit)
845 {
846 	struct ds_device *dev = data;
847 
848 	ds_write_bit(dev, bit);
849 }
850 
851 static u8 ds9490r_read_bit(void *data)
852 {
853 	struct ds_device *dev = data;
854 	int err;
855 
856 	err = ds_touch_bit(dev, 1, &dev->byte_buf);
857 	if (err)
858 		return 0;
859 
860 	return dev->byte_buf & 1;
861 }
862 #endif
863 
ds9490r_write_byte(void * data,u8 byte)864 static void ds9490r_write_byte(void *data, u8 byte)
865 {
866 	struct ds_device *dev = data;
867 
868 	ds_write_byte(dev, byte);
869 }
870 
ds9490r_read_byte(void * data)871 static u8 ds9490r_read_byte(void *data)
872 {
873 	struct ds_device *dev = data;
874 	int err;
875 
876 	err = ds_read_byte(dev, &dev->byte_buf);
877 	if (err)
878 		return 0;
879 
880 	return dev->byte_buf;
881 }
882 
ds9490r_write_block(void * data,const u8 * buf,int len)883 static void ds9490r_write_block(void *data, const u8 *buf, int len)
884 {
885 	struct ds_device *dev = data;
886 	u8 *tbuf;
887 
888 	if (len <= 0)
889 		return;
890 
891 	tbuf = kmemdup(buf, len, GFP_KERNEL);
892 	if (!tbuf)
893 		return;
894 
895 	ds_write_block(dev, tbuf, len);
896 
897 	kfree(tbuf);
898 }
899 
ds9490r_read_block(void * data,u8 * buf,int len)900 static u8 ds9490r_read_block(void *data, u8 *buf, int len)
901 {
902 	struct ds_device *dev = data;
903 	int err;
904 	u8 *tbuf;
905 
906 	if (len <= 0)
907 		return 0;
908 
909 	tbuf = kmalloc(len, GFP_KERNEL);
910 	if (!tbuf)
911 		return 0;
912 
913 	err = ds_read_block(dev, tbuf, len);
914 	if (err >= 0)
915 		memcpy(buf, tbuf, len);
916 
917 	kfree(tbuf);
918 
919 	return err >= 0 ? len : 0;
920 }
921 
ds9490r_reset(void * data)922 static u8 ds9490r_reset(void *data)
923 {
924 	struct ds_device *dev = data;
925 	int err;
926 
927 	err = ds_reset(dev);
928 	if (err)
929 		return 1;
930 
931 	return 0;
932 }
933 
ds9490r_set_pullup(void * data,int delay)934 static u8 ds9490r_set_pullup(void *data, int delay)
935 {
936 	struct ds_device *dev = data;
937 
938 	if (ds_set_pullup(dev, delay))
939 		return 1;
940 
941 	return 0;
942 }
943 
ds_w1_init(struct ds_device * dev)944 static int ds_w1_init(struct ds_device *dev)
945 {
946 	memset(&dev->master, 0, sizeof(struct w1_bus_master));
947 
948 	/* Reset the device as it can be in a bad state.
949 	 * This is necessary because a block write will wait for data
950 	 * to be placed in the output buffer and block any later
951 	 * commands which will keep accumulating and the device will
952 	 * not be idle.  Another case is removing the ds2490 module
953 	 * while a bus search is in progress, somehow a few commands
954 	 * get through, but the input transfers fail leaving data in
955 	 * the input buffer.  This will cause the next read to fail
956 	 * see the note in ds_recv_data.
957 	 */
958 	ds_reset_device(dev);
959 
960 	dev->master.data	= dev;
961 	dev->master.touch_bit	= &ds9490r_touch_bit;
962 	/* read_bit and write_bit in w1_bus_master are expected to set and
963 	 * sample the line level.  For write_bit that means it is expected to
964 	 * set it to that value and leave it there.  ds2490 only supports an
965 	 * individual time slot at the lowest level.  The requirement from
966 	 * pulling the bus state down to reading the state is 15us, something
967 	 * that isn't realistic on the USB bus anyway.
968 	dev->master.read_bit	= &ds9490r_read_bit;
969 	dev->master.write_bit	= &ds9490r_write_bit;
970 	*/
971 	dev->master.read_byte	= &ds9490r_read_byte;
972 	dev->master.write_byte	= &ds9490r_write_byte;
973 	dev->master.read_block	= &ds9490r_read_block;
974 	dev->master.write_block	= &ds9490r_write_block;
975 	dev->master.reset_bus	= &ds9490r_reset;
976 	dev->master.set_pullup	= &ds9490r_set_pullup;
977 	dev->master.search	= &ds9490r_search;
978 
979 	return w1_add_master_device(&dev->master);
980 }
981 
ds_w1_fini(struct ds_device * dev)982 static void ds_w1_fini(struct ds_device *dev)
983 {
984 	w1_remove_master_device(&dev->master);
985 }
986 
ds_probe(struct usb_interface * intf,const struct usb_device_id * udev_id)987 static int ds_probe(struct usb_interface *intf,
988 		    const struct usb_device_id *udev_id)
989 {
990 	struct usb_device *udev = interface_to_usbdev(intf);
991 	struct usb_endpoint_descriptor *endpoint;
992 	struct usb_host_interface *iface_desc;
993 	struct ds_device *dev;
994 	int i, err, alt;
995 
996 	dev = kzalloc(sizeof(struct ds_device), GFP_KERNEL);
997 	if (!dev) {
998 		pr_info("Failed to allocate new DS9490R structure.\n");
999 		return -ENOMEM;
1000 	}
1001 	dev->udev = usb_get_dev(udev);
1002 	if (!dev->udev) {
1003 		err = -ENOMEM;
1004 		goto err_out_free;
1005 	}
1006 	memset(dev->ep, 0, sizeof(dev->ep));
1007 
1008 	usb_set_intfdata(intf, dev);
1009 
1010 	err = usb_reset_configuration(dev->udev);
1011 	if (err) {
1012 		dev_err(&dev->udev->dev,
1013 			"Failed to reset configuration: err=%d.\n", err);
1014 		goto err_out_clear;
1015 	}
1016 
1017 	/* alternative 3, 1ms interrupt (greatly speeds search), 64 byte bulk */
1018 	alt = 3;
1019 	err = usb_set_interface(dev->udev,
1020 		intf->cur_altsetting->desc.bInterfaceNumber, alt);
1021 	if (err) {
1022 		dev_err(&dev->udev->dev, "Failed to set alternative setting %d "
1023 			"for %d interface: err=%d.\n", alt,
1024 			intf->cur_altsetting->desc.bInterfaceNumber, err);
1025 		goto err_out_clear;
1026 	}
1027 
1028 	iface_desc = intf->cur_altsetting;
1029 	if (iface_desc->desc.bNumEndpoints != NUM_EP-1) {
1030 		pr_info("Num endpoints=%d. It is not DS9490R.\n",
1031 			iface_desc->desc.bNumEndpoints);
1032 		err = -EINVAL;
1033 		goto err_out_clear;
1034 	}
1035 
1036 	/*
1037 	 * This loop doesn'd show control 0 endpoint,
1038 	 * so we will fill only 1-3 endpoints entry.
1039 	 */
1040 	for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
1041 		endpoint = &iface_desc->endpoint[i].desc;
1042 
1043 		dev->ep[i+1] = endpoint->bEndpointAddress;
1044 #if 0
1045 		printk("%d: addr=%x, size=%d, dir=%s, type=%x\n",
1046 			i, endpoint->bEndpointAddress, le16_to_cpu(endpoint->wMaxPacketSize),
1047 			(endpoint->bEndpointAddress & USB_DIR_IN)?"IN":"OUT",
1048 			endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK);
1049 #endif
1050 	}
1051 
1052 	err = ds_w1_init(dev);
1053 	if (err)
1054 		goto err_out_clear;
1055 
1056 	mutex_lock(&ds_mutex);
1057 	list_add_tail(&dev->ds_entry, &ds_devices);
1058 	mutex_unlock(&ds_mutex);
1059 
1060 	return 0;
1061 
1062 err_out_clear:
1063 	usb_set_intfdata(intf, NULL);
1064 	usb_put_dev(dev->udev);
1065 err_out_free:
1066 	kfree(dev);
1067 	return err;
1068 }
1069 
ds_disconnect(struct usb_interface * intf)1070 static void ds_disconnect(struct usb_interface *intf)
1071 {
1072 	struct ds_device *dev;
1073 
1074 	dev = usb_get_intfdata(intf);
1075 	if (!dev)
1076 		return;
1077 
1078 	mutex_lock(&ds_mutex);
1079 	list_del(&dev->ds_entry);
1080 	mutex_unlock(&ds_mutex);
1081 
1082 	ds_w1_fini(dev);
1083 
1084 	usb_set_intfdata(intf, NULL);
1085 
1086 	usb_put_dev(dev->udev);
1087 	kfree(dev);
1088 }
1089 
1090 static const struct usb_device_id ds_id_table[] = {
1091 	{ USB_DEVICE(0x04fa, 0x2490) },
1092 	{ },
1093 };
1094 MODULE_DEVICE_TABLE(usb, ds_id_table);
1095 
1096 static struct usb_driver ds_driver = {
1097 	.name =		"DS9490R",
1098 	.probe =	ds_probe,
1099 	.disconnect =	ds_disconnect,
1100 	.id_table =	ds_id_table,
1101 };
1102 module_usb_driver(ds_driver);
1103 
1104 MODULE_AUTHOR("Evgeniy Polyakov <zbr@ioremap.net>");
1105 MODULE_DESCRIPTION("DS2490 USB <-> W1 bus master driver (DS9490*)");
1106 MODULE_LICENSE("GPL");
1107