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