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