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