xref: /linux/drivers/net/wwan/wwan_core.c (revision 97ef3b7f4fdf8ad6818aa2c8201c3b72cc635e16)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2021, Linaro Ltd <loic.poulain@linaro.org> */
3 
4 #include <linux/err.h>
5 #include <linux/errno.h>
6 #include <linux/fs.h>
7 #include <linux/init.h>
8 #include <linux/idr.h>
9 #include <linux/kernel.h>
10 #include <linux/module.h>
11 #include <linux/poll.h>
12 #include <linux/skbuff.h>
13 #include <linux/slab.h>
14 #include <linux/types.h>
15 #include <linux/termios.h>
16 #include <linux/wwan.h>
17 #include <net/rtnetlink.h>
18 #include <uapi/linux/wwan.h>
19 
20 /* Maximum number of minors in use */
21 #define WWAN_MAX_MINORS		(1 << MINORBITS)
22 
23 static DEFINE_MUTEX(wwan_register_lock); /* WWAN device create|remove lock */
24 static DEFINE_IDA(minors); /* minors for WWAN port chardevs */
25 static DEFINE_IDA(wwan_dev_ids); /* for unique WWAN device IDs */
26 static struct class *wwan_class;
27 static int wwan_major;
28 
29 #define to_wwan_dev(d) container_of(d, struct wwan_device, dev)
30 #define to_wwan_port(d) container_of(d, struct wwan_port, dev)
31 
32 /* WWAN port flags */
33 #define WWAN_PORT_TX_OFF	0
34 
35 /**
36  * struct wwan_device - The structure that defines a WWAN device
37  *
38  * @id: WWAN device unique ID.
39  * @dev: Underlying device.
40  * @port_id: Current available port ID to pick.
41  * @ops: wwan device ops
42  * @ops_ctxt: context to pass to ops
43  */
44 struct wwan_device {
45 	unsigned int id;
46 	struct device dev;
47 	atomic_t port_id;
48 	const struct wwan_ops *ops;
49 	void *ops_ctxt;
50 };
51 
52 /**
53  * struct wwan_port - The structure that defines a WWAN port
54  * @type: Port type
55  * @start_count: Port start counter
56  * @flags: Store port state and capabilities
57  * @ops: Pointer to WWAN port operations
58  * @ops_lock: Protect port ops
59  * @dev: Underlying device
60  * @rxq: Buffer inbound queue
61  * @waitqueue: The waitqueue for port fops (read/write/poll)
62  * @data_lock: Port specific data access serialization
63  * @at_data: AT port specific data
64  */
65 struct wwan_port {
66 	enum wwan_port_type type;
67 	unsigned int start_count;
68 	unsigned long flags;
69 	const struct wwan_port_ops *ops;
70 	struct mutex ops_lock; /* Serialize ops + protect against removal */
71 	struct device dev;
72 	struct sk_buff_head rxq;
73 	wait_queue_head_t waitqueue;
74 	struct mutex data_lock;	/* Port specific data access serialization */
75 	union {
76 		struct {
77 			struct ktermios termios;
78 			int mdmbits;
79 		} at_data;
80 	};
81 };
82 
83 static ssize_t index_show(struct device *dev, struct device_attribute *attr, char *buf)
84 {
85 	struct wwan_device *wwan = to_wwan_dev(dev);
86 
87 	return sprintf(buf, "%d\n", wwan->id);
88 }
89 static DEVICE_ATTR_RO(index);
90 
91 static struct attribute *wwan_dev_attrs[] = {
92 	&dev_attr_index.attr,
93 	NULL,
94 };
95 ATTRIBUTE_GROUPS(wwan_dev);
96 
97 static void wwan_dev_destroy(struct device *dev)
98 {
99 	struct wwan_device *wwandev = to_wwan_dev(dev);
100 
101 	ida_free(&wwan_dev_ids, wwandev->id);
102 	kfree(wwandev);
103 }
104 
105 static const struct device_type wwan_dev_type = {
106 	.name    = "wwan_dev",
107 	.release = wwan_dev_destroy,
108 	.groups = wwan_dev_groups,
109 };
110 
111 static int wwan_dev_parent_match(struct device *dev, const void *parent)
112 {
113 	return (dev->type == &wwan_dev_type &&
114 		(dev->parent == parent || dev == parent));
115 }
116 
117 static struct wwan_device *wwan_dev_get_by_parent(struct device *parent)
118 {
119 	struct device *dev;
120 
121 	dev = class_find_device(wwan_class, NULL, parent, wwan_dev_parent_match);
122 	if (!dev)
123 		return ERR_PTR(-ENODEV);
124 
125 	return to_wwan_dev(dev);
126 }
127 
128 static int wwan_dev_name_match(struct device *dev, const void *name)
129 {
130 	return dev->type == &wwan_dev_type &&
131 	       strcmp(dev_name(dev), name) == 0;
132 }
133 
134 static struct wwan_device *wwan_dev_get_by_name(const char *name)
135 {
136 	struct device *dev;
137 
138 	dev = class_find_device(wwan_class, NULL, name, wwan_dev_name_match);
139 	if (!dev)
140 		return ERR_PTR(-ENODEV);
141 
142 	return to_wwan_dev(dev);
143 }
144 
145 /* This function allocates and registers a new WWAN device OR if a WWAN device
146  * already exist for the given parent, it gets a reference and return it.
147  * This function is not exported (for now), it is called indirectly via
148  * wwan_create_port().
149  */
150 static struct wwan_device *wwan_create_dev(struct device *parent)
151 {
152 	struct wwan_device *wwandev;
153 	int err, id;
154 
155 	/* The 'find-alloc-register' operation must be protected against
156 	 * concurrent execution, a WWAN device is possibly shared between
157 	 * multiple callers or concurrently unregistered from wwan_remove_dev().
158 	 */
159 	mutex_lock(&wwan_register_lock);
160 
161 	/* If wwandev already exists, return it */
162 	wwandev = wwan_dev_get_by_parent(parent);
163 	if (!IS_ERR(wwandev))
164 		goto done_unlock;
165 
166 	id = ida_alloc(&wwan_dev_ids, GFP_KERNEL);
167 	if (id < 0) {
168 		wwandev = ERR_PTR(id);
169 		goto done_unlock;
170 	}
171 
172 	wwandev = kzalloc(sizeof(*wwandev), GFP_KERNEL);
173 	if (!wwandev) {
174 		wwandev = ERR_PTR(-ENOMEM);
175 		ida_free(&wwan_dev_ids, id);
176 		goto done_unlock;
177 	}
178 
179 	wwandev->dev.parent = parent;
180 	wwandev->dev.class = wwan_class;
181 	wwandev->dev.type = &wwan_dev_type;
182 	wwandev->id = id;
183 	dev_set_name(&wwandev->dev, "wwan%d", wwandev->id);
184 
185 	err = device_register(&wwandev->dev);
186 	if (err) {
187 		put_device(&wwandev->dev);
188 		wwandev = ERR_PTR(err);
189 		goto done_unlock;
190 	}
191 
192 done_unlock:
193 	mutex_unlock(&wwan_register_lock);
194 
195 	return wwandev;
196 }
197 
198 static int is_wwan_child(struct device *dev, void *data)
199 {
200 	return dev->class == wwan_class;
201 }
202 
203 static void wwan_remove_dev(struct wwan_device *wwandev)
204 {
205 	int ret;
206 
207 	/* Prevent concurrent picking from wwan_create_dev */
208 	mutex_lock(&wwan_register_lock);
209 
210 	/* WWAN device is created and registered (get+add) along with its first
211 	 * child port, and subsequent port registrations only grab a reference
212 	 * (get). The WWAN device must then be unregistered (del+put) along with
213 	 * its last port, and reference simply dropped (put) otherwise. In the
214 	 * same fashion, we must not unregister it when the ops are still there.
215 	 */
216 	if (wwandev->ops)
217 		ret = 1;
218 	else
219 		ret = device_for_each_child(&wwandev->dev, NULL, is_wwan_child);
220 
221 	if (!ret)
222 		device_unregister(&wwandev->dev);
223 	else
224 		put_device(&wwandev->dev);
225 
226 	mutex_unlock(&wwan_register_lock);
227 }
228 
229 /* ------- WWAN port management ------- */
230 
231 static const struct {
232 	const char * const name;	/* Port type name */
233 	const char * const devsuf;	/* Port devce name suffix */
234 } wwan_port_types[WWAN_PORT_MAX + 1] = {
235 	[WWAN_PORT_AT] = {
236 		.name = "AT",
237 		.devsuf = "at",
238 	},
239 	[WWAN_PORT_MBIM] = {
240 		.name = "MBIM",
241 		.devsuf = "mbim",
242 	},
243 	[WWAN_PORT_QMI] = {
244 		.name = "QMI",
245 		.devsuf = "qmi",
246 	},
247 	[WWAN_PORT_QCDM] = {
248 		.name = "QCDM",
249 		.devsuf = "qcdm",
250 	},
251 	[WWAN_PORT_FIREHOSE] = {
252 		.name = "FIREHOSE",
253 		.devsuf = "firehose",
254 	},
255 };
256 
257 static ssize_t type_show(struct device *dev, struct device_attribute *attr,
258 			 char *buf)
259 {
260 	struct wwan_port *port = to_wwan_port(dev);
261 
262 	return sprintf(buf, "%s\n", wwan_port_types[port->type].name);
263 }
264 static DEVICE_ATTR_RO(type);
265 
266 static struct attribute *wwan_port_attrs[] = {
267 	&dev_attr_type.attr,
268 	NULL,
269 };
270 ATTRIBUTE_GROUPS(wwan_port);
271 
272 static void wwan_port_destroy(struct device *dev)
273 {
274 	struct wwan_port *port = to_wwan_port(dev);
275 
276 	ida_free(&minors, MINOR(port->dev.devt));
277 	mutex_destroy(&port->data_lock);
278 	mutex_destroy(&port->ops_lock);
279 	kfree(port);
280 }
281 
282 static const struct device_type wwan_port_dev_type = {
283 	.name = "wwan_port",
284 	.release = wwan_port_destroy,
285 	.groups = wwan_port_groups,
286 };
287 
288 static int wwan_port_minor_match(struct device *dev, const void *minor)
289 {
290 	return (dev->type == &wwan_port_dev_type &&
291 		MINOR(dev->devt) == *(unsigned int *)minor);
292 }
293 
294 static struct wwan_port *wwan_port_get_by_minor(unsigned int minor)
295 {
296 	struct device *dev;
297 
298 	dev = class_find_device(wwan_class, NULL, &minor, wwan_port_minor_match);
299 	if (!dev)
300 		return ERR_PTR(-ENODEV);
301 
302 	return to_wwan_port(dev);
303 }
304 
305 /* Allocate and set unique name based on passed format
306  *
307  * Name allocation approach is highly inspired by the __dev_alloc_name()
308  * function.
309  *
310  * To avoid names collision, the caller must prevent the new port device
311  * registration as well as concurrent invocation of this function.
312  */
313 static int __wwan_port_dev_assign_name(struct wwan_port *port, const char *fmt)
314 {
315 	struct wwan_device *wwandev = to_wwan_dev(port->dev.parent);
316 	const unsigned int max_ports = PAGE_SIZE * 8;
317 	struct class_dev_iter iter;
318 	unsigned long *idmap;
319 	struct device *dev;
320 	char buf[0x20];
321 	int id;
322 
323 	idmap = (unsigned long *)get_zeroed_page(GFP_KERNEL);
324 	if (!idmap)
325 		return -ENOMEM;
326 
327 	/* Collect ids of same name format ports */
328 	class_dev_iter_init(&iter, wwan_class, NULL, &wwan_port_dev_type);
329 	while ((dev = class_dev_iter_next(&iter))) {
330 		if (dev->parent != &wwandev->dev)
331 			continue;
332 		if (sscanf(dev_name(dev), fmt, &id) != 1)
333 			continue;
334 		if (id < 0 || id >= max_ports)
335 			continue;
336 		set_bit(id, idmap);
337 	}
338 	class_dev_iter_exit(&iter);
339 
340 	/* Allocate unique id */
341 	id = find_first_zero_bit(idmap, max_ports);
342 	free_page((unsigned long)idmap);
343 
344 	snprintf(buf, sizeof(buf), fmt, id);	/* Name generation */
345 
346 	dev = device_find_child_by_name(&wwandev->dev, buf);
347 	if (dev) {
348 		put_device(dev);
349 		return -ENFILE;
350 	}
351 
352 	return dev_set_name(&port->dev, buf);
353 }
354 
355 struct wwan_port *wwan_create_port(struct device *parent,
356 				   enum wwan_port_type type,
357 				   const struct wwan_port_ops *ops,
358 				   void *drvdata)
359 {
360 	struct wwan_device *wwandev;
361 	struct wwan_port *port;
362 	char namefmt[0x20];
363 	int minor, err;
364 
365 	if (type > WWAN_PORT_MAX || !ops)
366 		return ERR_PTR(-EINVAL);
367 
368 	/* A port is always a child of a WWAN device, retrieve (allocate or
369 	 * pick) the WWAN device based on the provided parent device.
370 	 */
371 	wwandev = wwan_create_dev(parent);
372 	if (IS_ERR(wwandev))
373 		return ERR_CAST(wwandev);
374 
375 	/* A port is exposed as character device, get a minor */
376 	minor = ida_alloc_range(&minors, 0, WWAN_MAX_MINORS - 1, GFP_KERNEL);
377 	if (minor < 0) {
378 		err = minor;
379 		goto error_wwandev_remove;
380 	}
381 
382 	port = kzalloc(sizeof(*port), GFP_KERNEL);
383 	if (!port) {
384 		err = -ENOMEM;
385 		ida_free(&minors, minor);
386 		goto error_wwandev_remove;
387 	}
388 
389 	port->type = type;
390 	port->ops = ops;
391 	mutex_init(&port->ops_lock);
392 	skb_queue_head_init(&port->rxq);
393 	init_waitqueue_head(&port->waitqueue);
394 	mutex_init(&port->data_lock);
395 
396 	port->dev.parent = &wwandev->dev;
397 	port->dev.class = wwan_class;
398 	port->dev.type = &wwan_port_dev_type;
399 	port->dev.devt = MKDEV(wwan_major, minor);
400 	dev_set_drvdata(&port->dev, drvdata);
401 
402 	/* allocate unique name based on wwan device id, port type and number */
403 	snprintf(namefmt, sizeof(namefmt), "wwan%u%s%%d", wwandev->id,
404 		 wwan_port_types[port->type].devsuf);
405 
406 	/* Serialize ports registration */
407 	mutex_lock(&wwan_register_lock);
408 
409 	__wwan_port_dev_assign_name(port, namefmt);
410 	err = device_register(&port->dev);
411 
412 	mutex_unlock(&wwan_register_lock);
413 
414 	if (err)
415 		goto error_put_device;
416 
417 	return port;
418 
419 error_put_device:
420 	put_device(&port->dev);
421 error_wwandev_remove:
422 	wwan_remove_dev(wwandev);
423 
424 	return ERR_PTR(err);
425 }
426 EXPORT_SYMBOL_GPL(wwan_create_port);
427 
428 void wwan_remove_port(struct wwan_port *port)
429 {
430 	struct wwan_device *wwandev = to_wwan_dev(port->dev.parent);
431 
432 	mutex_lock(&port->ops_lock);
433 	if (port->start_count)
434 		port->ops->stop(port);
435 	port->ops = NULL; /* Prevent any new port operations (e.g. from fops) */
436 	mutex_unlock(&port->ops_lock);
437 
438 	wake_up_interruptible(&port->waitqueue);
439 
440 	skb_queue_purge(&port->rxq);
441 	dev_set_drvdata(&port->dev, NULL);
442 	device_unregister(&port->dev);
443 
444 	/* Release related wwan device */
445 	wwan_remove_dev(wwandev);
446 }
447 EXPORT_SYMBOL_GPL(wwan_remove_port);
448 
449 void wwan_port_rx(struct wwan_port *port, struct sk_buff *skb)
450 {
451 	skb_queue_tail(&port->rxq, skb);
452 	wake_up_interruptible(&port->waitqueue);
453 }
454 EXPORT_SYMBOL_GPL(wwan_port_rx);
455 
456 void wwan_port_txon(struct wwan_port *port)
457 {
458 	clear_bit(WWAN_PORT_TX_OFF, &port->flags);
459 	wake_up_interruptible(&port->waitqueue);
460 }
461 EXPORT_SYMBOL_GPL(wwan_port_txon);
462 
463 void wwan_port_txoff(struct wwan_port *port)
464 {
465 	set_bit(WWAN_PORT_TX_OFF, &port->flags);
466 }
467 EXPORT_SYMBOL_GPL(wwan_port_txoff);
468 
469 void *wwan_port_get_drvdata(struct wwan_port *port)
470 {
471 	return dev_get_drvdata(&port->dev);
472 }
473 EXPORT_SYMBOL_GPL(wwan_port_get_drvdata);
474 
475 static int wwan_port_op_start(struct wwan_port *port)
476 {
477 	int ret = 0;
478 
479 	mutex_lock(&port->ops_lock);
480 	if (!port->ops) { /* Port got unplugged */
481 		ret = -ENODEV;
482 		goto out_unlock;
483 	}
484 
485 	/* If port is already started, don't start again */
486 	if (!port->start_count)
487 		ret = port->ops->start(port);
488 
489 	if (!ret)
490 		port->start_count++;
491 
492 out_unlock:
493 	mutex_unlock(&port->ops_lock);
494 
495 	return ret;
496 }
497 
498 static void wwan_port_op_stop(struct wwan_port *port)
499 {
500 	mutex_lock(&port->ops_lock);
501 	port->start_count--;
502 	if (!port->start_count) {
503 		if (port->ops)
504 			port->ops->stop(port);
505 		skb_queue_purge(&port->rxq);
506 	}
507 	mutex_unlock(&port->ops_lock);
508 }
509 
510 static int wwan_port_op_tx(struct wwan_port *port, struct sk_buff *skb,
511 			   bool nonblock)
512 {
513 	int ret;
514 
515 	mutex_lock(&port->ops_lock);
516 	if (!port->ops) { /* Port got unplugged */
517 		ret = -ENODEV;
518 		goto out_unlock;
519 	}
520 
521 	if (nonblock || !port->ops->tx_blocking)
522 		ret = port->ops->tx(port, skb);
523 	else
524 		ret = port->ops->tx_blocking(port, skb);
525 
526 out_unlock:
527 	mutex_unlock(&port->ops_lock);
528 
529 	return ret;
530 }
531 
532 static bool is_read_blocked(struct wwan_port *port)
533 {
534 	return skb_queue_empty(&port->rxq) && port->ops;
535 }
536 
537 static bool is_write_blocked(struct wwan_port *port)
538 {
539 	return test_bit(WWAN_PORT_TX_OFF, &port->flags) && port->ops;
540 }
541 
542 static int wwan_wait_rx(struct wwan_port *port, bool nonblock)
543 {
544 	if (!is_read_blocked(port))
545 		return 0;
546 
547 	if (nonblock)
548 		return -EAGAIN;
549 
550 	if (wait_event_interruptible(port->waitqueue, !is_read_blocked(port)))
551 		return -ERESTARTSYS;
552 
553 	return 0;
554 }
555 
556 static int wwan_wait_tx(struct wwan_port *port, bool nonblock)
557 {
558 	if (!is_write_blocked(port))
559 		return 0;
560 
561 	if (nonblock)
562 		return -EAGAIN;
563 
564 	if (wait_event_interruptible(port->waitqueue, !is_write_blocked(port)))
565 		return -ERESTARTSYS;
566 
567 	return 0;
568 }
569 
570 static int wwan_port_fops_open(struct inode *inode, struct file *file)
571 {
572 	struct wwan_port *port;
573 	int err = 0;
574 
575 	port = wwan_port_get_by_minor(iminor(inode));
576 	if (IS_ERR(port))
577 		return PTR_ERR(port);
578 
579 	file->private_data = port;
580 	stream_open(inode, file);
581 
582 	err = wwan_port_op_start(port);
583 	if (err)
584 		put_device(&port->dev);
585 
586 	return err;
587 }
588 
589 static int wwan_port_fops_release(struct inode *inode, struct file *filp)
590 {
591 	struct wwan_port *port = filp->private_data;
592 
593 	wwan_port_op_stop(port);
594 	put_device(&port->dev);
595 
596 	return 0;
597 }
598 
599 static ssize_t wwan_port_fops_read(struct file *filp, char __user *buf,
600 				   size_t count, loff_t *ppos)
601 {
602 	struct wwan_port *port = filp->private_data;
603 	struct sk_buff *skb;
604 	size_t copied;
605 	int ret;
606 
607 	ret = wwan_wait_rx(port, !!(filp->f_flags & O_NONBLOCK));
608 	if (ret)
609 		return ret;
610 
611 	skb = skb_dequeue(&port->rxq);
612 	if (!skb)
613 		return -EIO;
614 
615 	copied = min_t(size_t, count, skb->len);
616 	if (copy_to_user(buf, skb->data, copied)) {
617 		kfree_skb(skb);
618 		return -EFAULT;
619 	}
620 	skb_pull(skb, copied);
621 
622 	/* skb is not fully consumed, keep it in the queue */
623 	if (skb->len)
624 		skb_queue_head(&port->rxq, skb);
625 	else
626 		consume_skb(skb);
627 
628 	return copied;
629 }
630 
631 static ssize_t wwan_port_fops_write(struct file *filp, const char __user *buf,
632 				    size_t count, loff_t *offp)
633 {
634 	struct wwan_port *port = filp->private_data;
635 	struct sk_buff *skb;
636 	int ret;
637 
638 	ret = wwan_wait_tx(port, !!(filp->f_flags & O_NONBLOCK));
639 	if (ret)
640 		return ret;
641 
642 	skb = alloc_skb(count, GFP_KERNEL);
643 	if (!skb)
644 		return -ENOMEM;
645 
646 	if (copy_from_user(skb_put(skb, count), buf, count)) {
647 		kfree_skb(skb);
648 		return -EFAULT;
649 	}
650 
651 	ret = wwan_port_op_tx(port, skb, !!(filp->f_flags & O_NONBLOCK));
652 	if (ret) {
653 		kfree_skb(skb);
654 		return ret;
655 	}
656 
657 	return count;
658 }
659 
660 static __poll_t wwan_port_fops_poll(struct file *filp, poll_table *wait)
661 {
662 	struct wwan_port *port = filp->private_data;
663 	__poll_t mask = 0;
664 
665 	poll_wait(filp, &port->waitqueue, wait);
666 
667 	mutex_lock(&port->ops_lock);
668 	if (port->ops && port->ops->tx_poll)
669 		mask |= port->ops->tx_poll(port, filp, wait);
670 	else if (!is_write_blocked(port))
671 		mask |= EPOLLOUT | EPOLLWRNORM;
672 	if (!is_read_blocked(port))
673 		mask |= EPOLLIN | EPOLLRDNORM;
674 	if (!port->ops)
675 		mask |= EPOLLHUP | EPOLLERR;
676 	mutex_unlock(&port->ops_lock);
677 
678 	return mask;
679 }
680 
681 /* Implements minimalistic stub terminal IOCTLs support */
682 static long wwan_port_fops_at_ioctl(struct wwan_port *port, unsigned int cmd,
683 				    unsigned long arg)
684 {
685 	int ret = 0;
686 
687 	mutex_lock(&port->data_lock);
688 
689 	switch (cmd) {
690 	case TCFLSH:
691 		break;
692 
693 	case TCGETS:
694 		if (copy_to_user((void __user *)arg, &port->at_data.termios,
695 				 sizeof(struct termios)))
696 			ret = -EFAULT;
697 		break;
698 
699 	case TCSETS:
700 	case TCSETSW:
701 	case TCSETSF:
702 		if (copy_from_user(&port->at_data.termios, (void __user *)arg,
703 				   sizeof(struct termios)))
704 			ret = -EFAULT;
705 		break;
706 
707 #ifdef TCGETS2
708 	case TCGETS2:
709 		if (copy_to_user((void __user *)arg, &port->at_data.termios,
710 				 sizeof(struct termios2)))
711 			ret = -EFAULT;
712 		break;
713 
714 	case TCSETS2:
715 	case TCSETSW2:
716 	case TCSETSF2:
717 		if (copy_from_user(&port->at_data.termios, (void __user *)arg,
718 				   sizeof(struct termios2)))
719 			ret = -EFAULT;
720 		break;
721 #endif
722 
723 	case TIOCMGET:
724 		ret = put_user(port->at_data.mdmbits, (int __user *)arg);
725 		break;
726 
727 	case TIOCMSET:
728 	case TIOCMBIC:
729 	case TIOCMBIS: {
730 		int mdmbits;
731 
732 		if (copy_from_user(&mdmbits, (int __user *)arg, sizeof(int))) {
733 			ret = -EFAULT;
734 			break;
735 		}
736 		if (cmd == TIOCMBIC)
737 			port->at_data.mdmbits &= ~mdmbits;
738 		else if (cmd == TIOCMBIS)
739 			port->at_data.mdmbits |= mdmbits;
740 		else
741 			port->at_data.mdmbits = mdmbits;
742 		break;
743 	}
744 
745 	default:
746 		ret = -ENOIOCTLCMD;
747 	}
748 
749 	mutex_unlock(&port->data_lock);
750 
751 	return ret;
752 }
753 
754 static long wwan_port_fops_ioctl(struct file *filp, unsigned int cmd,
755 				 unsigned long arg)
756 {
757 	struct wwan_port *port = filp->private_data;
758 	int res;
759 
760 	if (port->type == WWAN_PORT_AT) {	/* AT port specific IOCTLs */
761 		res = wwan_port_fops_at_ioctl(port, cmd, arg);
762 		if (res != -ENOIOCTLCMD)
763 			return res;
764 	}
765 
766 	switch (cmd) {
767 	case TIOCINQ: {	/* aka SIOCINQ aka FIONREAD */
768 		unsigned long flags;
769 		struct sk_buff *skb;
770 		int amount = 0;
771 
772 		spin_lock_irqsave(&port->rxq.lock, flags);
773 		skb_queue_walk(&port->rxq, skb)
774 			amount += skb->len;
775 		spin_unlock_irqrestore(&port->rxq.lock, flags);
776 
777 		return put_user(amount, (int __user *)arg);
778 	}
779 
780 	default:
781 		return -ENOIOCTLCMD;
782 	}
783 }
784 
785 static const struct file_operations wwan_port_fops = {
786 	.owner = THIS_MODULE,
787 	.open = wwan_port_fops_open,
788 	.release = wwan_port_fops_release,
789 	.read = wwan_port_fops_read,
790 	.write = wwan_port_fops_write,
791 	.poll = wwan_port_fops_poll,
792 	.unlocked_ioctl = wwan_port_fops_ioctl,
793 #ifdef CONFIG_COMPAT
794 	.compat_ioctl = compat_ptr_ioctl,
795 #endif
796 	.llseek = noop_llseek,
797 };
798 
799 static int wwan_rtnl_validate(struct nlattr *tb[], struct nlattr *data[],
800 			      struct netlink_ext_ack *extack)
801 {
802 	if (!data)
803 		return -EINVAL;
804 
805 	if (!tb[IFLA_PARENT_DEV_NAME])
806 		return -EINVAL;
807 
808 	if (!data[IFLA_WWAN_LINK_ID])
809 		return -EINVAL;
810 
811 	return 0;
812 }
813 
814 static struct device_type wwan_type = { .name = "wwan" };
815 
816 static struct net_device *wwan_rtnl_alloc(struct nlattr *tb[],
817 					  const char *ifname,
818 					  unsigned char name_assign_type,
819 					  unsigned int num_tx_queues,
820 					  unsigned int num_rx_queues)
821 {
822 	const char *devname = nla_data(tb[IFLA_PARENT_DEV_NAME]);
823 	struct wwan_device *wwandev = wwan_dev_get_by_name(devname);
824 	struct net_device *dev;
825 	unsigned int priv_size;
826 
827 	if (IS_ERR(wwandev))
828 		return ERR_CAST(wwandev);
829 
830 	/* only supported if ops were registered (not just ports) */
831 	if (!wwandev->ops) {
832 		dev = ERR_PTR(-EOPNOTSUPP);
833 		goto out;
834 	}
835 
836 	priv_size = sizeof(struct wwan_netdev_priv) + wwandev->ops->priv_size;
837 	dev = alloc_netdev_mqs(priv_size, ifname, name_assign_type,
838 			       wwandev->ops->setup, num_tx_queues, num_rx_queues);
839 
840 	if (dev) {
841 		SET_NETDEV_DEV(dev, &wwandev->dev);
842 		SET_NETDEV_DEVTYPE(dev, &wwan_type);
843 	}
844 
845 out:
846 	/* release the reference */
847 	put_device(&wwandev->dev);
848 	return dev;
849 }
850 
851 static int wwan_rtnl_newlink(struct net *src_net, struct net_device *dev,
852 			     struct nlattr *tb[], struct nlattr *data[],
853 			     struct netlink_ext_ack *extack)
854 {
855 	struct wwan_device *wwandev = wwan_dev_get_by_parent(dev->dev.parent);
856 	u32 link_id = nla_get_u32(data[IFLA_WWAN_LINK_ID]);
857 	struct wwan_netdev_priv *priv = netdev_priv(dev);
858 	int ret;
859 
860 	if (IS_ERR(wwandev))
861 		return PTR_ERR(wwandev);
862 
863 	/* shouldn't have a netdev (left) with us as parent so WARN */
864 	if (WARN_ON(!wwandev->ops)) {
865 		ret = -EOPNOTSUPP;
866 		goto out;
867 	}
868 
869 	priv->link_id = link_id;
870 	if (wwandev->ops->newlink)
871 		ret = wwandev->ops->newlink(wwandev->ops_ctxt, dev,
872 					    link_id, extack);
873 	else
874 		ret = register_netdevice(dev);
875 
876 out:
877 	/* release the reference */
878 	put_device(&wwandev->dev);
879 	return ret;
880 }
881 
882 static void wwan_rtnl_dellink(struct net_device *dev, struct list_head *head)
883 {
884 	struct wwan_device *wwandev = wwan_dev_get_by_parent(dev->dev.parent);
885 
886 	if (IS_ERR(wwandev))
887 		return;
888 
889 	/* shouldn't have a netdev (left) with us as parent so WARN */
890 	if (WARN_ON(!wwandev->ops))
891 		goto out;
892 
893 	if (wwandev->ops->dellink)
894 		wwandev->ops->dellink(wwandev->ops_ctxt, dev, head);
895 	else
896 		unregister_netdevice_queue(dev, head);
897 
898 out:
899 	/* release the reference */
900 	put_device(&wwandev->dev);
901 }
902 
903 static size_t wwan_rtnl_get_size(const struct net_device *dev)
904 {
905 	return
906 		nla_total_size(4) +	/* IFLA_WWAN_LINK_ID */
907 		0;
908 }
909 
910 static int wwan_rtnl_fill_info(struct sk_buff *skb,
911 			       const struct net_device *dev)
912 {
913 	struct wwan_netdev_priv *priv = netdev_priv(dev);
914 
915 	if (nla_put_u32(skb, IFLA_WWAN_LINK_ID, priv->link_id))
916 		goto nla_put_failure;
917 
918 	return 0;
919 
920 nla_put_failure:
921 	return -EMSGSIZE;
922 }
923 
924 static const struct nla_policy wwan_rtnl_policy[IFLA_WWAN_MAX + 1] = {
925 	[IFLA_WWAN_LINK_ID] = { .type = NLA_U32 },
926 };
927 
928 static struct rtnl_link_ops wwan_rtnl_link_ops __read_mostly = {
929 	.kind = "wwan",
930 	.maxtype = __IFLA_WWAN_MAX,
931 	.alloc = wwan_rtnl_alloc,
932 	.validate = wwan_rtnl_validate,
933 	.newlink = wwan_rtnl_newlink,
934 	.dellink = wwan_rtnl_dellink,
935 	.get_size = wwan_rtnl_get_size,
936 	.fill_info = wwan_rtnl_fill_info,
937 	.policy = wwan_rtnl_policy,
938 };
939 
940 static void wwan_create_default_link(struct wwan_device *wwandev,
941 				     u32 def_link_id)
942 {
943 	struct nlattr *tb[IFLA_MAX + 1], *linkinfo[IFLA_INFO_MAX + 1];
944 	struct nlattr *data[IFLA_WWAN_MAX + 1];
945 	struct net_device *dev;
946 	struct nlmsghdr *nlh;
947 	struct sk_buff *msg;
948 
949 	/* Forge attributes required to create a WWAN netdev. We first
950 	 * build a netlink message and then parse it. This looks
951 	 * odd, but such approach is less error prone.
952 	 */
953 	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
954 	if (WARN_ON(!msg))
955 		return;
956 	nlh = nlmsg_put(msg, 0, 0, RTM_NEWLINK, 0, 0);
957 	if (WARN_ON(!nlh))
958 		goto free_attrs;
959 
960 	if (nla_put_string(msg, IFLA_PARENT_DEV_NAME, dev_name(&wwandev->dev)))
961 		goto free_attrs;
962 	tb[IFLA_LINKINFO] = nla_nest_start(msg, IFLA_LINKINFO);
963 	if (!tb[IFLA_LINKINFO])
964 		goto free_attrs;
965 	linkinfo[IFLA_INFO_DATA] = nla_nest_start(msg, IFLA_INFO_DATA);
966 	if (!linkinfo[IFLA_INFO_DATA])
967 		goto free_attrs;
968 	if (nla_put_u32(msg, IFLA_WWAN_LINK_ID, def_link_id))
969 		goto free_attrs;
970 	nla_nest_end(msg, linkinfo[IFLA_INFO_DATA]);
971 	nla_nest_end(msg, tb[IFLA_LINKINFO]);
972 
973 	nlmsg_end(msg, nlh);
974 
975 	/* The next three parsing calls can not fail */
976 	nlmsg_parse_deprecated(nlh, 0, tb, IFLA_MAX, NULL, NULL);
977 	nla_parse_nested_deprecated(linkinfo, IFLA_INFO_MAX, tb[IFLA_LINKINFO],
978 				    NULL, NULL);
979 	nla_parse_nested_deprecated(data, IFLA_WWAN_MAX,
980 				    linkinfo[IFLA_INFO_DATA], NULL, NULL);
981 
982 	rtnl_lock();
983 
984 	dev = rtnl_create_link(&init_net, "wwan%d", NET_NAME_ENUM,
985 			       &wwan_rtnl_link_ops, tb, NULL);
986 	if (WARN_ON(IS_ERR(dev)))
987 		goto unlock;
988 
989 	if (WARN_ON(wwan_rtnl_newlink(&init_net, dev, tb, data, NULL))) {
990 		free_netdev(dev);
991 		goto unlock;
992 	}
993 
994 	rtnl_configure_link(dev, NULL); /* Link initialized, notify new link */
995 
996 unlock:
997 	rtnl_unlock();
998 
999 free_attrs:
1000 	nlmsg_free(msg);
1001 }
1002 
1003 /**
1004  * wwan_register_ops - register WWAN device ops
1005  * @parent: Device to use as parent and shared by all WWAN ports and
1006  *	created netdevs
1007  * @ops: operations to register
1008  * @ctxt: context to pass to operations
1009  * @def_link_id: id of the default link that will be automatically created by
1010  *	the WWAN core for the WWAN device. The default link will not be created
1011  *	if the passed value is WWAN_NO_DEFAULT_LINK.
1012  *
1013  * Returns: 0 on success, a negative error code on failure
1014  */
1015 int wwan_register_ops(struct device *parent, const struct wwan_ops *ops,
1016 		      void *ctxt, u32 def_link_id)
1017 {
1018 	struct wwan_device *wwandev;
1019 
1020 	if (WARN_ON(!parent || !ops || !ops->setup))
1021 		return -EINVAL;
1022 
1023 	wwandev = wwan_create_dev(parent);
1024 	if (IS_ERR(wwandev))
1025 		return PTR_ERR(wwandev);
1026 
1027 	if (WARN_ON(wwandev->ops)) {
1028 		wwan_remove_dev(wwandev);
1029 		return -EBUSY;
1030 	}
1031 
1032 	wwandev->ops = ops;
1033 	wwandev->ops_ctxt = ctxt;
1034 
1035 	/* NB: we do not abort ops registration in case of default link
1036 	 * creation failure. Link ops is the management interface, while the
1037 	 * default link creation is a service option. And we should not prevent
1038 	 * a user from manually creating a link latter if service option failed
1039 	 * now.
1040 	 */
1041 	if (def_link_id != WWAN_NO_DEFAULT_LINK)
1042 		wwan_create_default_link(wwandev, def_link_id);
1043 
1044 	return 0;
1045 }
1046 EXPORT_SYMBOL_GPL(wwan_register_ops);
1047 
1048 /* Enqueue child netdev deletion */
1049 static int wwan_child_dellink(struct device *dev, void *data)
1050 {
1051 	struct list_head *kill_list = data;
1052 
1053 	if (dev->type == &wwan_type)
1054 		wwan_rtnl_dellink(to_net_dev(dev), kill_list);
1055 
1056 	return 0;
1057 }
1058 
1059 /**
1060  * wwan_unregister_ops - remove WWAN device ops
1061  * @parent: Device to use as parent and shared by all WWAN ports and
1062  *	created netdevs
1063  */
1064 void wwan_unregister_ops(struct device *parent)
1065 {
1066 	struct wwan_device *wwandev = wwan_dev_get_by_parent(parent);
1067 	LIST_HEAD(kill_list);
1068 
1069 	if (WARN_ON(IS_ERR(wwandev)))
1070 		return;
1071 	if (WARN_ON(!wwandev->ops)) {
1072 		put_device(&wwandev->dev);
1073 		return;
1074 	}
1075 
1076 	/* put the reference obtained by wwan_dev_get_by_parent(),
1077 	 * we should still have one (that the owner is giving back
1078 	 * now) due to the ops being assigned.
1079 	 */
1080 	put_device(&wwandev->dev);
1081 
1082 	rtnl_lock();	/* Prevent concurent netdev(s) creation/destroying */
1083 
1084 	/* Remove all child netdev(s), using batch removing */
1085 	device_for_each_child(&wwandev->dev, &kill_list,
1086 			      wwan_child_dellink);
1087 	unregister_netdevice_many(&kill_list);
1088 
1089 	wwandev->ops = NULL;	/* Finally remove ops */
1090 
1091 	rtnl_unlock();
1092 
1093 	wwandev->ops_ctxt = NULL;
1094 	wwan_remove_dev(wwandev);
1095 }
1096 EXPORT_SYMBOL_GPL(wwan_unregister_ops);
1097 
1098 static int __init wwan_init(void)
1099 {
1100 	int err;
1101 
1102 	err = rtnl_link_register(&wwan_rtnl_link_ops);
1103 	if (err)
1104 		return err;
1105 
1106 	wwan_class = class_create(THIS_MODULE, "wwan");
1107 	if (IS_ERR(wwan_class)) {
1108 		err = PTR_ERR(wwan_class);
1109 		goto unregister;
1110 	}
1111 
1112 	/* chrdev used for wwan ports */
1113 	wwan_major = __register_chrdev(0, 0, WWAN_MAX_MINORS, "wwan_port",
1114 				       &wwan_port_fops);
1115 	if (wwan_major < 0) {
1116 		err = wwan_major;
1117 		goto destroy;
1118 	}
1119 
1120 	return 0;
1121 
1122 destroy:
1123 	class_destroy(wwan_class);
1124 unregister:
1125 	rtnl_link_unregister(&wwan_rtnl_link_ops);
1126 	return err;
1127 }
1128 
1129 static void __exit wwan_exit(void)
1130 {
1131 	__unregister_chrdev(wwan_major, 0, WWAN_MAX_MINORS, "wwan_port");
1132 	rtnl_link_unregister(&wwan_rtnl_link_ops);
1133 	class_destroy(wwan_class);
1134 }
1135 
1136 module_init(wwan_init);
1137 module_exit(wwan_exit);
1138 
1139 MODULE_AUTHOR("Loic Poulain <loic.poulain@linaro.org>");
1140 MODULE_DESCRIPTION("WWAN core");
1141 MODULE_LICENSE("GPL v2");
1142