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