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