xref: /openbmc/linux/drivers/net/xen-netback/xenbus.c (revision e3d786a3)
1 /*
2  * Xenbus code for netif backend
3  *
4  * Copyright (C) 2005 Rusty Russell <rusty@rustcorp.com.au>
5  * Copyright (C) 2005 XenSource Ltd
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20 
21 #include "common.h"
22 #include <linux/vmalloc.h>
23 #include <linux/rtnetlink.h>
24 
25 struct backend_info {
26 	struct xenbus_device *dev;
27 	struct xenvif *vif;
28 
29 	/* This is the state that will be reflected in xenstore when any
30 	 * active hotplug script completes.
31 	 */
32 	enum xenbus_state state;
33 
34 	enum xenbus_state frontend_state;
35 	struct xenbus_watch hotplug_status_watch;
36 	u8 have_hotplug_status_watch:1;
37 
38 	const char *hotplug_script;
39 };
40 
41 static int connect_data_rings(struct backend_info *be,
42 			      struct xenvif_queue *queue);
43 static void connect(struct backend_info *be);
44 static int read_xenbus_vif_flags(struct backend_info *be);
45 static int backend_create_xenvif(struct backend_info *be);
46 static void unregister_hotplug_status_watch(struct backend_info *be);
47 static void xen_unregister_watchers(struct xenvif *vif);
48 static void set_backend_state(struct backend_info *be,
49 			      enum xenbus_state state);
50 
51 #ifdef CONFIG_DEBUG_FS
52 struct dentry *xen_netback_dbg_root = NULL;
53 
54 static int xenvif_read_io_ring(struct seq_file *m, void *v)
55 {
56 	struct xenvif_queue *queue = m->private;
57 	struct xen_netif_tx_back_ring *tx_ring = &queue->tx;
58 	struct xen_netif_rx_back_ring *rx_ring = &queue->rx;
59 	struct netdev_queue *dev_queue;
60 
61 	if (tx_ring->sring) {
62 		struct xen_netif_tx_sring *sring = tx_ring->sring;
63 
64 		seq_printf(m, "Queue %d\nTX: nr_ents %u\n", queue->id,
65 			   tx_ring->nr_ents);
66 		seq_printf(m, "req prod %u (%d) cons %u (%d) event %u (%d)\n",
67 			   sring->req_prod,
68 			   sring->req_prod - sring->rsp_prod,
69 			   tx_ring->req_cons,
70 			   tx_ring->req_cons - sring->rsp_prod,
71 			   sring->req_event,
72 			   sring->req_event - sring->rsp_prod);
73 		seq_printf(m, "rsp prod %u (base) pvt %u (%d) event %u (%d)\n",
74 			   sring->rsp_prod,
75 			   tx_ring->rsp_prod_pvt,
76 			   tx_ring->rsp_prod_pvt - sring->rsp_prod,
77 			   sring->rsp_event,
78 			   sring->rsp_event - sring->rsp_prod);
79 		seq_printf(m, "pending prod %u pending cons %u nr_pending_reqs %u\n",
80 			   queue->pending_prod,
81 			   queue->pending_cons,
82 			   nr_pending_reqs(queue));
83 		seq_printf(m, "dealloc prod %u dealloc cons %u dealloc_queue %u\n\n",
84 			   queue->dealloc_prod,
85 			   queue->dealloc_cons,
86 			   queue->dealloc_prod - queue->dealloc_cons);
87 	}
88 
89 	if (rx_ring->sring) {
90 		struct xen_netif_rx_sring *sring = rx_ring->sring;
91 
92 		seq_printf(m, "RX: nr_ents %u\n", rx_ring->nr_ents);
93 		seq_printf(m, "req prod %u (%d) cons %u (%d) event %u (%d)\n",
94 			   sring->req_prod,
95 			   sring->req_prod - sring->rsp_prod,
96 			   rx_ring->req_cons,
97 			   rx_ring->req_cons - sring->rsp_prod,
98 			   sring->req_event,
99 			   sring->req_event - sring->rsp_prod);
100 		seq_printf(m, "rsp prod %u (base) pvt %u (%d) event %u (%d)\n\n",
101 			   sring->rsp_prod,
102 			   rx_ring->rsp_prod_pvt,
103 			   rx_ring->rsp_prod_pvt - sring->rsp_prod,
104 			   sring->rsp_event,
105 			   sring->rsp_event - sring->rsp_prod);
106 	}
107 
108 	seq_printf(m, "NAPI state: %lx NAPI weight: %d TX queue len %u\n"
109 		   "Credit timer_pending: %d, credit: %lu, usec: %lu\n"
110 		   "remaining: %lu, expires: %lu, now: %lu\n",
111 		   queue->napi.state, queue->napi.weight,
112 		   skb_queue_len(&queue->tx_queue),
113 		   timer_pending(&queue->credit_timeout),
114 		   queue->credit_bytes,
115 		   queue->credit_usec,
116 		   queue->remaining_credit,
117 		   queue->credit_timeout.expires,
118 		   jiffies);
119 
120 	dev_queue = netdev_get_tx_queue(queue->vif->dev, queue->id);
121 
122 	seq_printf(m, "\nRx internal queue: len %u max %u pkts %u %s\n",
123 		   queue->rx_queue_len, queue->rx_queue_max,
124 		   skb_queue_len(&queue->rx_queue),
125 		   netif_tx_queue_stopped(dev_queue) ? "stopped" : "running");
126 
127 	return 0;
128 }
129 
130 #define XENVIF_KICK_STR "kick"
131 #define BUFFER_SIZE     32
132 
133 static ssize_t
134 xenvif_write_io_ring(struct file *filp, const char __user *buf, size_t count,
135 		     loff_t *ppos)
136 {
137 	struct xenvif_queue *queue =
138 		((struct seq_file *)filp->private_data)->private;
139 	int len;
140 	char write[BUFFER_SIZE];
141 
142 	/* don't allow partial writes and check the length */
143 	if (*ppos != 0)
144 		return 0;
145 	if (count >= sizeof(write))
146 		return -ENOSPC;
147 
148 	len = simple_write_to_buffer(write,
149 				     sizeof(write) - 1,
150 				     ppos,
151 				     buf,
152 				     count);
153 	if (len < 0)
154 		return len;
155 
156 	write[len] = '\0';
157 
158 	if (!strncmp(write, XENVIF_KICK_STR, sizeof(XENVIF_KICK_STR) - 1))
159 		xenvif_interrupt(0, (void *)queue);
160 	else {
161 		pr_warn("Unknown command to io_ring_q%d. Available: kick\n",
162 			queue->id);
163 		count = -EINVAL;
164 	}
165 	return count;
166 }
167 
168 static int xenvif_io_ring_open(struct inode *inode, struct file *filp)
169 {
170 	int ret;
171 	void *queue = NULL;
172 
173 	if (inode->i_private)
174 		queue = inode->i_private;
175 	ret = single_open(filp, xenvif_read_io_ring, queue);
176 	filp->f_mode |= FMODE_PWRITE;
177 	return ret;
178 }
179 
180 static const struct file_operations xenvif_dbg_io_ring_ops_fops = {
181 	.owner = THIS_MODULE,
182 	.open = xenvif_io_ring_open,
183 	.read = seq_read,
184 	.llseek = seq_lseek,
185 	.release = single_release,
186 	.write = xenvif_write_io_ring,
187 };
188 
189 static int xenvif_read_ctrl(struct seq_file *m, void *v)
190 {
191 	struct xenvif *vif = m->private;
192 
193 	xenvif_dump_hash_info(vif, m);
194 
195 	return 0;
196 }
197 
198 static int xenvif_ctrl_open(struct inode *inode, struct file *filp)
199 {
200 	return single_open(filp, xenvif_read_ctrl, inode->i_private);
201 }
202 
203 static const struct file_operations xenvif_dbg_ctrl_ops_fops = {
204 	.owner = THIS_MODULE,
205 	.open = xenvif_ctrl_open,
206 	.read = seq_read,
207 	.llseek = seq_lseek,
208 	.release = single_release,
209 };
210 
211 static void xenvif_debugfs_addif(struct xenvif *vif)
212 {
213 	struct dentry *pfile;
214 	int i;
215 
216 	if (IS_ERR_OR_NULL(xen_netback_dbg_root))
217 		return;
218 
219 	vif->xenvif_dbg_root = debugfs_create_dir(vif->dev->name,
220 						  xen_netback_dbg_root);
221 	if (!IS_ERR_OR_NULL(vif->xenvif_dbg_root)) {
222 		for (i = 0; i < vif->num_queues; ++i) {
223 			char filename[sizeof("io_ring_q") + 4];
224 
225 			snprintf(filename, sizeof(filename), "io_ring_q%d", i);
226 			pfile = debugfs_create_file(filename,
227 						    0600,
228 						    vif->xenvif_dbg_root,
229 						    &vif->queues[i],
230 						    &xenvif_dbg_io_ring_ops_fops);
231 			if (IS_ERR_OR_NULL(pfile))
232 				pr_warn("Creation of io_ring file returned %ld!\n",
233 					PTR_ERR(pfile));
234 		}
235 
236 		if (vif->ctrl_irq) {
237 			pfile = debugfs_create_file("ctrl",
238 						    0400,
239 						    vif->xenvif_dbg_root,
240 						    vif,
241 						    &xenvif_dbg_ctrl_ops_fops);
242 			if (IS_ERR_OR_NULL(pfile))
243 				pr_warn("Creation of ctrl file returned %ld!\n",
244 					PTR_ERR(pfile));
245 		}
246 	} else
247 		netdev_warn(vif->dev,
248 			    "Creation of vif debugfs dir returned %ld!\n",
249 			    PTR_ERR(vif->xenvif_dbg_root));
250 }
251 
252 static void xenvif_debugfs_delif(struct xenvif *vif)
253 {
254 	if (IS_ERR_OR_NULL(xen_netback_dbg_root))
255 		return;
256 
257 	debugfs_remove_recursive(vif->xenvif_dbg_root);
258 	vif->xenvif_dbg_root = NULL;
259 }
260 #endif /* CONFIG_DEBUG_FS */
261 
262 static int netback_remove(struct xenbus_device *dev)
263 {
264 	struct backend_info *be = dev_get_drvdata(&dev->dev);
265 
266 	set_backend_state(be, XenbusStateClosed);
267 
268 	unregister_hotplug_status_watch(be);
269 	if (be->vif) {
270 		kobject_uevent(&dev->dev.kobj, KOBJ_OFFLINE);
271 		xen_unregister_watchers(be->vif);
272 		xenbus_rm(XBT_NIL, dev->nodename, "hotplug-status");
273 		xenvif_free(be->vif);
274 		be->vif = NULL;
275 	}
276 	kfree(be->hotplug_script);
277 	kfree(be);
278 	dev_set_drvdata(&dev->dev, NULL);
279 	return 0;
280 }
281 
282 
283 /**
284  * Entry point to this code when a new device is created.  Allocate the basic
285  * structures and switch to InitWait.
286  */
287 static int netback_probe(struct xenbus_device *dev,
288 			 const struct xenbus_device_id *id)
289 {
290 	const char *message;
291 	struct xenbus_transaction xbt;
292 	int err;
293 	int sg;
294 	const char *script;
295 	struct backend_info *be = kzalloc(sizeof(struct backend_info),
296 					  GFP_KERNEL);
297 	if (!be) {
298 		xenbus_dev_fatal(dev, -ENOMEM,
299 				 "allocating backend structure");
300 		return -ENOMEM;
301 	}
302 
303 	be->dev = dev;
304 	dev_set_drvdata(&dev->dev, be);
305 
306 	be->state = XenbusStateInitialising;
307 	err = xenbus_switch_state(dev, XenbusStateInitialising);
308 	if (err)
309 		goto fail;
310 
311 	sg = 1;
312 
313 	do {
314 		err = xenbus_transaction_start(&xbt);
315 		if (err) {
316 			xenbus_dev_fatal(dev, err, "starting transaction");
317 			goto fail;
318 		}
319 
320 		err = xenbus_printf(xbt, dev->nodename, "feature-sg", "%d", sg);
321 		if (err) {
322 			message = "writing feature-sg";
323 			goto abort_transaction;
324 		}
325 
326 		err = xenbus_printf(xbt, dev->nodename, "feature-gso-tcpv4",
327 				    "%d", sg);
328 		if (err) {
329 			message = "writing feature-gso-tcpv4";
330 			goto abort_transaction;
331 		}
332 
333 		err = xenbus_printf(xbt, dev->nodename, "feature-gso-tcpv6",
334 				    "%d", sg);
335 		if (err) {
336 			message = "writing feature-gso-tcpv6";
337 			goto abort_transaction;
338 		}
339 
340 		/* We support partial checksum setup for IPv6 packets */
341 		err = xenbus_printf(xbt, dev->nodename,
342 				    "feature-ipv6-csum-offload",
343 				    "%d", 1);
344 		if (err) {
345 			message = "writing feature-ipv6-csum-offload";
346 			goto abort_transaction;
347 		}
348 
349 		/* We support rx-copy path. */
350 		err = xenbus_printf(xbt, dev->nodename,
351 				    "feature-rx-copy", "%d", 1);
352 		if (err) {
353 			message = "writing feature-rx-copy";
354 			goto abort_transaction;
355 		}
356 
357 		/*
358 		 * We don't support rx-flip path (except old guests who don't
359 		 * grok this feature flag).
360 		 */
361 		err = xenbus_printf(xbt, dev->nodename,
362 				    "feature-rx-flip", "%d", 0);
363 		if (err) {
364 			message = "writing feature-rx-flip";
365 			goto abort_transaction;
366 		}
367 
368 		/* We support dynamic multicast-control. */
369 		err = xenbus_printf(xbt, dev->nodename,
370 				    "feature-multicast-control", "%d", 1);
371 		if (err) {
372 			message = "writing feature-multicast-control";
373 			goto abort_transaction;
374 		}
375 
376 		err = xenbus_printf(xbt, dev->nodename,
377 				    "feature-dynamic-multicast-control",
378 				    "%d", 1);
379 		if (err) {
380 			message = "writing feature-dynamic-multicast-control";
381 			goto abort_transaction;
382 		}
383 
384 		err = xenbus_transaction_end(xbt, 0);
385 	} while (err == -EAGAIN);
386 
387 	if (err) {
388 		xenbus_dev_fatal(dev, err, "completing transaction");
389 		goto fail;
390 	}
391 
392 	/*
393 	 * Split event channels support, this is optional so it is not
394 	 * put inside the above loop.
395 	 */
396 	err = xenbus_printf(XBT_NIL, dev->nodename,
397 			    "feature-split-event-channels",
398 			    "%u", separate_tx_rx_irq);
399 	if (err)
400 		pr_debug("Error writing feature-split-event-channels\n");
401 
402 	/* Multi-queue support: This is an optional feature. */
403 	err = xenbus_printf(XBT_NIL, dev->nodename,
404 			    "multi-queue-max-queues", "%u", xenvif_max_queues);
405 	if (err)
406 		pr_debug("Error writing multi-queue-max-queues\n");
407 
408 	err = xenbus_printf(XBT_NIL, dev->nodename,
409 			    "feature-ctrl-ring",
410 			    "%u", true);
411 	if (err)
412 		pr_debug("Error writing feature-ctrl-ring\n");
413 
414 	script = xenbus_read(XBT_NIL, dev->nodename, "script", NULL);
415 	if (IS_ERR(script)) {
416 		err = PTR_ERR(script);
417 		xenbus_dev_fatal(dev, err, "reading script");
418 		goto fail;
419 	}
420 
421 	be->hotplug_script = script;
422 
423 
424 	/* This kicks hotplug scripts, so do it immediately. */
425 	err = backend_create_xenvif(be);
426 	if (err)
427 		goto fail;
428 
429 	return 0;
430 
431 abort_transaction:
432 	xenbus_transaction_end(xbt, 1);
433 	xenbus_dev_fatal(dev, err, "%s", message);
434 fail:
435 	pr_debug("failed\n");
436 	netback_remove(dev);
437 	return err;
438 }
439 
440 
441 /*
442  * Handle the creation of the hotplug script environment.  We add the script
443  * and vif variables to the environment, for the benefit of the vif-* hotplug
444  * scripts.
445  */
446 static int netback_uevent(struct xenbus_device *xdev,
447 			  struct kobj_uevent_env *env)
448 {
449 	struct backend_info *be = dev_get_drvdata(&xdev->dev);
450 
451 	if (!be)
452 		return 0;
453 
454 	if (add_uevent_var(env, "script=%s", be->hotplug_script))
455 		return -ENOMEM;
456 
457 	if (!be->vif)
458 		return 0;
459 
460 	return add_uevent_var(env, "vif=%s", be->vif->dev->name);
461 }
462 
463 
464 static int backend_create_xenvif(struct backend_info *be)
465 {
466 	int err;
467 	long handle;
468 	struct xenbus_device *dev = be->dev;
469 	struct xenvif *vif;
470 
471 	if (be->vif != NULL)
472 		return 0;
473 
474 	err = xenbus_scanf(XBT_NIL, dev->nodename, "handle", "%li", &handle);
475 	if (err != 1) {
476 		xenbus_dev_fatal(dev, err, "reading handle");
477 		return (err < 0) ? err : -EINVAL;
478 	}
479 
480 	vif = xenvif_alloc(&dev->dev, dev->otherend_id, handle);
481 	if (IS_ERR(vif)) {
482 		err = PTR_ERR(vif);
483 		xenbus_dev_fatal(dev, err, "creating interface");
484 		return err;
485 	}
486 	be->vif = vif;
487 
488 	kobject_uevent(&dev->dev.kobj, KOBJ_ONLINE);
489 	return 0;
490 }
491 
492 static void backend_disconnect(struct backend_info *be)
493 {
494 	struct xenvif *vif = be->vif;
495 
496 	if (vif) {
497 		unsigned int num_queues = vif->num_queues;
498 		unsigned int queue_index;
499 
500 		xen_unregister_watchers(vif);
501 #ifdef CONFIG_DEBUG_FS
502 		xenvif_debugfs_delif(vif);
503 #endif /* CONFIG_DEBUG_FS */
504 		xenvif_disconnect_data(vif);
505 
506 		/* At this point some of the handlers may still be active
507 		 * so we need to have additional synchronization here.
508 		 */
509 		vif->num_queues = 0;
510 		synchronize_net();
511 
512 		for (queue_index = 0; queue_index < num_queues; ++queue_index)
513 			xenvif_deinit_queue(&vif->queues[queue_index]);
514 
515 		vfree(vif->queues);
516 		vif->queues = NULL;
517 
518 		xenvif_disconnect_ctrl(vif);
519 	}
520 }
521 
522 static void backend_connect(struct backend_info *be)
523 {
524 	if (be->vif)
525 		connect(be);
526 }
527 
528 static inline void backend_switch_state(struct backend_info *be,
529 					enum xenbus_state state)
530 {
531 	struct xenbus_device *dev = be->dev;
532 
533 	pr_debug("%s -> %s\n", dev->nodename, xenbus_strstate(state));
534 	be->state = state;
535 
536 	/* If we are waiting for a hotplug script then defer the
537 	 * actual xenbus state change.
538 	 */
539 	if (!be->have_hotplug_status_watch)
540 		xenbus_switch_state(dev, state);
541 }
542 
543 /* Handle backend state transitions:
544  *
545  * The backend state starts in Initialising and the following transitions are
546  * allowed.
547  *
548  * Initialising -> InitWait -> Connected
549  *          \
550  *           \        ^    \         |
551  *            \       |     \        |
552  *             \      |      \       |
553  *              \     |       \      |
554  *               \    |        \     |
555  *                \   |         \    |
556  *                 V  |          V   V
557  *
558  *                  Closed  <-> Closing
559  *
560  * The state argument specifies the eventual state of the backend and the
561  * function transitions to that state via the shortest path.
562  */
563 static void set_backend_state(struct backend_info *be,
564 			      enum xenbus_state state)
565 {
566 	while (be->state != state) {
567 		switch (be->state) {
568 		case XenbusStateInitialising:
569 			switch (state) {
570 			case XenbusStateInitWait:
571 			case XenbusStateConnected:
572 			case XenbusStateClosing:
573 				backend_switch_state(be, XenbusStateInitWait);
574 				break;
575 			case XenbusStateClosed:
576 				backend_switch_state(be, XenbusStateClosed);
577 				break;
578 			default:
579 				BUG();
580 			}
581 			break;
582 		case XenbusStateClosed:
583 			switch (state) {
584 			case XenbusStateInitWait:
585 			case XenbusStateConnected:
586 				backend_switch_state(be, XenbusStateInitWait);
587 				break;
588 			case XenbusStateClosing:
589 				backend_switch_state(be, XenbusStateClosing);
590 				break;
591 			default:
592 				BUG();
593 			}
594 			break;
595 		case XenbusStateInitWait:
596 			switch (state) {
597 			case XenbusStateConnected:
598 				backend_connect(be);
599 				backend_switch_state(be, XenbusStateConnected);
600 				break;
601 			case XenbusStateClosing:
602 			case XenbusStateClosed:
603 				backend_switch_state(be, XenbusStateClosing);
604 				break;
605 			default:
606 				BUG();
607 			}
608 			break;
609 		case XenbusStateConnected:
610 			switch (state) {
611 			case XenbusStateInitWait:
612 			case XenbusStateClosing:
613 			case XenbusStateClosed:
614 				backend_disconnect(be);
615 				backend_switch_state(be, XenbusStateClosing);
616 				break;
617 			default:
618 				BUG();
619 			}
620 			break;
621 		case XenbusStateClosing:
622 			switch (state) {
623 			case XenbusStateInitWait:
624 			case XenbusStateConnected:
625 			case XenbusStateClosed:
626 				backend_switch_state(be, XenbusStateClosed);
627 				break;
628 			default:
629 				BUG();
630 			}
631 			break;
632 		default:
633 			BUG();
634 		}
635 	}
636 }
637 
638 /**
639  * Callback received when the frontend's state changes.
640  */
641 static void frontend_changed(struct xenbus_device *dev,
642 			     enum xenbus_state frontend_state)
643 {
644 	struct backend_info *be = dev_get_drvdata(&dev->dev);
645 
646 	pr_debug("%s -> %s\n", dev->otherend, xenbus_strstate(frontend_state));
647 
648 	be->frontend_state = frontend_state;
649 
650 	switch (frontend_state) {
651 	case XenbusStateInitialising:
652 		set_backend_state(be, XenbusStateInitWait);
653 		break;
654 
655 	case XenbusStateInitialised:
656 		break;
657 
658 	case XenbusStateConnected:
659 		set_backend_state(be, XenbusStateConnected);
660 		break;
661 
662 	case XenbusStateClosing:
663 		set_backend_state(be, XenbusStateClosing);
664 		break;
665 
666 	case XenbusStateClosed:
667 		set_backend_state(be, XenbusStateClosed);
668 		if (xenbus_dev_is_online(dev))
669 			break;
670 		/* fall through if not online */
671 	case XenbusStateUnknown:
672 		set_backend_state(be, XenbusStateClosed);
673 		device_unregister(&dev->dev);
674 		break;
675 
676 	default:
677 		xenbus_dev_fatal(dev, -EINVAL, "saw state %d at frontend",
678 				 frontend_state);
679 		break;
680 	}
681 }
682 
683 
684 static void xen_net_read_rate(struct xenbus_device *dev,
685 			      unsigned long *bytes, unsigned long *usec)
686 {
687 	char *s, *e;
688 	unsigned long b, u;
689 	char *ratestr;
690 
691 	/* Default to unlimited bandwidth. */
692 	*bytes = ~0UL;
693 	*usec = 0;
694 
695 	ratestr = xenbus_read(XBT_NIL, dev->nodename, "rate", NULL);
696 	if (IS_ERR(ratestr))
697 		return;
698 
699 	s = ratestr;
700 	b = simple_strtoul(s, &e, 10);
701 	if ((s == e) || (*e != ','))
702 		goto fail;
703 
704 	s = e + 1;
705 	u = simple_strtoul(s, &e, 10);
706 	if ((s == e) || (*e != '\0'))
707 		goto fail;
708 
709 	*bytes = b;
710 	*usec = u;
711 
712 	kfree(ratestr);
713 	return;
714 
715  fail:
716 	pr_warn("Failed to parse network rate limit. Traffic unlimited.\n");
717 	kfree(ratestr);
718 }
719 
720 static int xen_net_read_mac(struct xenbus_device *dev, u8 mac[])
721 {
722 	char *s, *e, *macstr;
723 	int i;
724 
725 	macstr = s = xenbus_read(XBT_NIL, dev->nodename, "mac", NULL);
726 	if (IS_ERR(macstr))
727 		return PTR_ERR(macstr);
728 
729 	for (i = 0; i < ETH_ALEN; i++) {
730 		mac[i] = simple_strtoul(s, &e, 16);
731 		if ((s == e) || (*e != ((i == ETH_ALEN-1) ? '\0' : ':'))) {
732 			kfree(macstr);
733 			return -ENOENT;
734 		}
735 		s = e+1;
736 	}
737 
738 	kfree(macstr);
739 	return 0;
740 }
741 
742 static void xen_net_rate_changed(struct xenbus_watch *watch,
743 				 const char *path, const char *token)
744 {
745 	struct xenvif *vif = container_of(watch, struct xenvif, credit_watch);
746 	struct xenbus_device *dev = xenvif_to_xenbus_device(vif);
747 	unsigned long   credit_bytes;
748 	unsigned long   credit_usec;
749 	unsigned int queue_index;
750 
751 	xen_net_read_rate(dev, &credit_bytes, &credit_usec);
752 	for (queue_index = 0; queue_index < vif->num_queues; queue_index++) {
753 		struct xenvif_queue *queue = &vif->queues[queue_index];
754 
755 		queue->credit_bytes = credit_bytes;
756 		queue->credit_usec = credit_usec;
757 		if (!mod_timer_pending(&queue->credit_timeout, jiffies) &&
758 			queue->remaining_credit > queue->credit_bytes) {
759 			queue->remaining_credit = queue->credit_bytes;
760 		}
761 	}
762 }
763 
764 static int xen_register_credit_watch(struct xenbus_device *dev,
765 				     struct xenvif *vif)
766 {
767 	int err = 0;
768 	char *node;
769 	unsigned maxlen = strlen(dev->nodename) + sizeof("/rate");
770 
771 	if (vif->credit_watch.node)
772 		return -EADDRINUSE;
773 
774 	node = kmalloc(maxlen, GFP_KERNEL);
775 	if (!node)
776 		return -ENOMEM;
777 	snprintf(node, maxlen, "%s/rate", dev->nodename);
778 	vif->credit_watch.node = node;
779 	vif->credit_watch.callback = xen_net_rate_changed;
780 	err = register_xenbus_watch(&vif->credit_watch);
781 	if (err) {
782 		pr_err("Failed to set watcher %s\n", vif->credit_watch.node);
783 		kfree(node);
784 		vif->credit_watch.node = NULL;
785 		vif->credit_watch.callback = NULL;
786 	}
787 	return err;
788 }
789 
790 static void xen_unregister_credit_watch(struct xenvif *vif)
791 {
792 	if (vif->credit_watch.node) {
793 		unregister_xenbus_watch(&vif->credit_watch);
794 		kfree(vif->credit_watch.node);
795 		vif->credit_watch.node = NULL;
796 	}
797 }
798 
799 static void xen_mcast_ctrl_changed(struct xenbus_watch *watch,
800 				   const char *path, const char *token)
801 {
802 	struct xenvif *vif = container_of(watch, struct xenvif,
803 					  mcast_ctrl_watch);
804 	struct xenbus_device *dev = xenvif_to_xenbus_device(vif);
805 
806 	vif->multicast_control = !!xenbus_read_unsigned(dev->otherend,
807 					"request-multicast-control", 0);
808 }
809 
810 static int xen_register_mcast_ctrl_watch(struct xenbus_device *dev,
811 					 struct xenvif *vif)
812 {
813 	int err = 0;
814 	char *node;
815 	unsigned maxlen = strlen(dev->otherend) +
816 		sizeof("/request-multicast-control");
817 
818 	if (vif->mcast_ctrl_watch.node) {
819 		pr_err_ratelimited("Watch is already registered\n");
820 		return -EADDRINUSE;
821 	}
822 
823 	node = kmalloc(maxlen, GFP_KERNEL);
824 	if (!node) {
825 		pr_err("Failed to allocate memory for watch\n");
826 		return -ENOMEM;
827 	}
828 	snprintf(node, maxlen, "%s/request-multicast-control",
829 		 dev->otherend);
830 	vif->mcast_ctrl_watch.node = node;
831 	vif->mcast_ctrl_watch.callback = xen_mcast_ctrl_changed;
832 	err = register_xenbus_watch(&vif->mcast_ctrl_watch);
833 	if (err) {
834 		pr_err("Failed to set watcher %s\n",
835 		       vif->mcast_ctrl_watch.node);
836 		kfree(node);
837 		vif->mcast_ctrl_watch.node = NULL;
838 		vif->mcast_ctrl_watch.callback = NULL;
839 	}
840 	return err;
841 }
842 
843 static void xen_unregister_mcast_ctrl_watch(struct xenvif *vif)
844 {
845 	if (vif->mcast_ctrl_watch.node) {
846 		unregister_xenbus_watch(&vif->mcast_ctrl_watch);
847 		kfree(vif->mcast_ctrl_watch.node);
848 		vif->mcast_ctrl_watch.node = NULL;
849 	}
850 }
851 
852 static void xen_register_watchers(struct xenbus_device *dev,
853 				  struct xenvif *vif)
854 {
855 	xen_register_credit_watch(dev, vif);
856 	xen_register_mcast_ctrl_watch(dev, vif);
857 }
858 
859 static void xen_unregister_watchers(struct xenvif *vif)
860 {
861 	xen_unregister_mcast_ctrl_watch(vif);
862 	xen_unregister_credit_watch(vif);
863 }
864 
865 static void unregister_hotplug_status_watch(struct backend_info *be)
866 {
867 	if (be->have_hotplug_status_watch) {
868 		unregister_xenbus_watch(&be->hotplug_status_watch);
869 		kfree(be->hotplug_status_watch.node);
870 	}
871 	be->have_hotplug_status_watch = 0;
872 }
873 
874 static void hotplug_status_changed(struct xenbus_watch *watch,
875 				   const char *path,
876 				   const char *token)
877 {
878 	struct backend_info *be = container_of(watch,
879 					       struct backend_info,
880 					       hotplug_status_watch);
881 	char *str;
882 	unsigned int len;
883 
884 	str = xenbus_read(XBT_NIL, be->dev->nodename, "hotplug-status", &len);
885 	if (IS_ERR(str))
886 		return;
887 	if (len == sizeof("connected")-1 && !memcmp(str, "connected", len)) {
888 		/* Complete any pending state change */
889 		xenbus_switch_state(be->dev, be->state);
890 
891 		/* Not interested in this watch anymore. */
892 		unregister_hotplug_status_watch(be);
893 	}
894 	kfree(str);
895 }
896 
897 static int connect_ctrl_ring(struct backend_info *be)
898 {
899 	struct xenbus_device *dev = be->dev;
900 	struct xenvif *vif = be->vif;
901 	unsigned int val;
902 	grant_ref_t ring_ref;
903 	unsigned int evtchn;
904 	int err;
905 
906 	err = xenbus_scanf(XBT_NIL, dev->otherend,
907 			   "ctrl-ring-ref", "%u", &val);
908 	if (err < 0)
909 		goto done; /* The frontend does not have a control ring */
910 
911 	ring_ref = val;
912 
913 	err = xenbus_scanf(XBT_NIL, dev->otherend,
914 			   "event-channel-ctrl", "%u", &val);
915 	if (err < 0) {
916 		xenbus_dev_fatal(dev, err,
917 				 "reading %s/event-channel-ctrl",
918 				 dev->otherend);
919 		goto fail;
920 	}
921 
922 	evtchn = val;
923 
924 	err = xenvif_connect_ctrl(vif, ring_ref, evtchn);
925 	if (err) {
926 		xenbus_dev_fatal(dev, err,
927 				 "mapping shared-frame %u port %u",
928 				 ring_ref, evtchn);
929 		goto fail;
930 	}
931 
932 done:
933 	return 0;
934 
935 fail:
936 	return err;
937 }
938 
939 static void connect(struct backend_info *be)
940 {
941 	int err;
942 	struct xenbus_device *dev = be->dev;
943 	unsigned long credit_bytes, credit_usec;
944 	unsigned int queue_index;
945 	unsigned int requested_num_queues;
946 	struct xenvif_queue *queue;
947 
948 	/* Check whether the frontend requested multiple queues
949 	 * and read the number requested.
950 	 */
951 	requested_num_queues = xenbus_read_unsigned(dev->otherend,
952 					"multi-queue-num-queues", 1);
953 	if (requested_num_queues > xenvif_max_queues) {
954 		/* buggy or malicious guest */
955 		xenbus_dev_fatal(dev, -EINVAL,
956 				 "guest requested %u queues, exceeding the maximum of %u.",
957 				 requested_num_queues, xenvif_max_queues);
958 		return;
959 	}
960 
961 	err = xen_net_read_mac(dev, be->vif->fe_dev_addr);
962 	if (err) {
963 		xenbus_dev_fatal(dev, err, "parsing %s/mac", dev->nodename);
964 		return;
965 	}
966 
967 	xen_net_read_rate(dev, &credit_bytes, &credit_usec);
968 	xen_unregister_watchers(be->vif);
969 	xen_register_watchers(dev, be->vif);
970 	read_xenbus_vif_flags(be);
971 
972 	err = connect_ctrl_ring(be);
973 	if (err) {
974 		xenbus_dev_fatal(dev, err, "connecting control ring");
975 		return;
976 	}
977 
978 	/* Use the number of queues requested by the frontend */
979 	be->vif->queues = vzalloc(array_size(requested_num_queues,
980 					     sizeof(struct xenvif_queue)));
981 	if (!be->vif->queues) {
982 		xenbus_dev_fatal(dev, -ENOMEM,
983 				 "allocating queues");
984 		return;
985 	}
986 
987 	be->vif->num_queues = requested_num_queues;
988 	be->vif->stalled_queues = requested_num_queues;
989 
990 	for (queue_index = 0; queue_index < requested_num_queues; ++queue_index) {
991 		queue = &be->vif->queues[queue_index];
992 		queue->vif = be->vif;
993 		queue->id = queue_index;
994 		snprintf(queue->name, sizeof(queue->name), "%s-q%u",
995 				be->vif->dev->name, queue->id);
996 
997 		err = xenvif_init_queue(queue);
998 		if (err) {
999 			/* xenvif_init_queue() cleans up after itself on
1000 			 * failure, but we need to clean up any previously
1001 			 * initialised queues. Set num_queues to i so that
1002 			 * earlier queues can be destroyed using the regular
1003 			 * disconnect logic.
1004 			 */
1005 			be->vif->num_queues = queue_index;
1006 			goto err;
1007 		}
1008 
1009 		queue->credit_bytes = credit_bytes;
1010 		queue->remaining_credit = credit_bytes;
1011 		queue->credit_usec = credit_usec;
1012 
1013 		err = connect_data_rings(be, queue);
1014 		if (err) {
1015 			/* connect_data_rings() cleans up after itself on
1016 			 * failure, but we need to clean up after
1017 			 * xenvif_init_queue() here, and also clean up any
1018 			 * previously initialised queues.
1019 			 */
1020 			xenvif_deinit_queue(queue);
1021 			be->vif->num_queues = queue_index;
1022 			goto err;
1023 		}
1024 	}
1025 
1026 #ifdef CONFIG_DEBUG_FS
1027 	xenvif_debugfs_addif(be->vif);
1028 #endif /* CONFIG_DEBUG_FS */
1029 
1030 	/* Initialisation completed, tell core driver the number of
1031 	 * active queues.
1032 	 */
1033 	rtnl_lock();
1034 	netif_set_real_num_tx_queues(be->vif->dev, requested_num_queues);
1035 	netif_set_real_num_rx_queues(be->vif->dev, requested_num_queues);
1036 	rtnl_unlock();
1037 
1038 	xenvif_carrier_on(be->vif);
1039 
1040 	unregister_hotplug_status_watch(be);
1041 	err = xenbus_watch_pathfmt(dev, &be->hotplug_status_watch,
1042 				   hotplug_status_changed,
1043 				   "%s/%s", dev->nodename, "hotplug-status");
1044 	if (!err)
1045 		be->have_hotplug_status_watch = 1;
1046 
1047 	netif_tx_wake_all_queues(be->vif->dev);
1048 
1049 	return;
1050 
1051 err:
1052 	if (be->vif->num_queues > 0)
1053 		xenvif_disconnect_data(be->vif); /* Clean up existing queues */
1054 	for (queue_index = 0; queue_index < be->vif->num_queues; ++queue_index)
1055 		xenvif_deinit_queue(&be->vif->queues[queue_index]);
1056 	vfree(be->vif->queues);
1057 	be->vif->queues = NULL;
1058 	be->vif->num_queues = 0;
1059 	xenvif_disconnect_ctrl(be->vif);
1060 	return;
1061 }
1062 
1063 
1064 static int connect_data_rings(struct backend_info *be,
1065 			      struct xenvif_queue *queue)
1066 {
1067 	struct xenbus_device *dev = be->dev;
1068 	unsigned int num_queues = queue->vif->num_queues;
1069 	unsigned long tx_ring_ref, rx_ring_ref;
1070 	unsigned int tx_evtchn, rx_evtchn;
1071 	int err;
1072 	char *xspath;
1073 	size_t xspathsize;
1074 	const size_t xenstore_path_ext_size = 11; /* sufficient for "/queue-NNN" */
1075 
1076 	/* If the frontend requested 1 queue, or we have fallen back
1077 	 * to single queue due to lack of frontend support for multi-
1078 	 * queue, expect the remaining XenStore keys in the toplevel
1079 	 * directory. Otherwise, expect them in a subdirectory called
1080 	 * queue-N.
1081 	 */
1082 	if (num_queues == 1) {
1083 		xspath = kzalloc(strlen(dev->otherend) + 1, GFP_KERNEL);
1084 		if (!xspath) {
1085 			xenbus_dev_fatal(dev, -ENOMEM,
1086 					 "reading ring references");
1087 			return -ENOMEM;
1088 		}
1089 		strcpy(xspath, dev->otherend);
1090 	} else {
1091 		xspathsize = strlen(dev->otherend) + xenstore_path_ext_size;
1092 		xspath = kzalloc(xspathsize, GFP_KERNEL);
1093 		if (!xspath) {
1094 			xenbus_dev_fatal(dev, -ENOMEM,
1095 					 "reading ring references");
1096 			return -ENOMEM;
1097 		}
1098 		snprintf(xspath, xspathsize, "%s/queue-%u", dev->otherend,
1099 			 queue->id);
1100 	}
1101 
1102 	err = xenbus_gather(XBT_NIL, xspath,
1103 			    "tx-ring-ref", "%lu", &tx_ring_ref,
1104 			    "rx-ring-ref", "%lu", &rx_ring_ref, NULL);
1105 	if (err) {
1106 		xenbus_dev_fatal(dev, err,
1107 				 "reading %s/ring-ref",
1108 				 xspath);
1109 		goto err;
1110 	}
1111 
1112 	/* Try split event channels first, then single event channel. */
1113 	err = xenbus_gather(XBT_NIL, xspath,
1114 			    "event-channel-tx", "%u", &tx_evtchn,
1115 			    "event-channel-rx", "%u", &rx_evtchn, NULL);
1116 	if (err < 0) {
1117 		err = xenbus_scanf(XBT_NIL, xspath,
1118 				   "event-channel", "%u", &tx_evtchn);
1119 		if (err < 0) {
1120 			xenbus_dev_fatal(dev, err,
1121 					 "reading %s/event-channel(-tx/rx)",
1122 					 xspath);
1123 			goto err;
1124 		}
1125 		rx_evtchn = tx_evtchn;
1126 	}
1127 
1128 	/* Map the shared frame, irq etc. */
1129 	err = xenvif_connect_data(queue, tx_ring_ref, rx_ring_ref,
1130 				  tx_evtchn, rx_evtchn);
1131 	if (err) {
1132 		xenbus_dev_fatal(dev, err,
1133 				 "mapping shared-frames %lu/%lu port tx %u rx %u",
1134 				 tx_ring_ref, rx_ring_ref,
1135 				 tx_evtchn, rx_evtchn);
1136 		goto err;
1137 	}
1138 
1139 	err = 0;
1140 err: /* Regular return falls through with err == 0 */
1141 	kfree(xspath);
1142 	return err;
1143 }
1144 
1145 static int read_xenbus_vif_flags(struct backend_info *be)
1146 {
1147 	struct xenvif *vif = be->vif;
1148 	struct xenbus_device *dev = be->dev;
1149 	unsigned int rx_copy;
1150 	int err;
1151 
1152 	err = xenbus_scanf(XBT_NIL, dev->otherend, "request-rx-copy", "%u",
1153 			   &rx_copy);
1154 	if (err == -ENOENT) {
1155 		err = 0;
1156 		rx_copy = 0;
1157 	}
1158 	if (err < 0) {
1159 		xenbus_dev_fatal(dev, err, "reading %s/request-rx-copy",
1160 				 dev->otherend);
1161 		return err;
1162 	}
1163 	if (!rx_copy)
1164 		return -EOPNOTSUPP;
1165 
1166 	if (!xenbus_read_unsigned(dev->otherend, "feature-rx-notify", 0)) {
1167 		/* - Reduce drain timeout to poll more frequently for
1168 		 *   Rx requests.
1169 		 * - Disable Rx stall detection.
1170 		 */
1171 		be->vif->drain_timeout = msecs_to_jiffies(30);
1172 		be->vif->stall_timeout = 0;
1173 	}
1174 
1175 	vif->can_sg = !!xenbus_read_unsigned(dev->otherend, "feature-sg", 0);
1176 
1177 	vif->gso_mask = 0;
1178 
1179 	if (xenbus_read_unsigned(dev->otherend, "feature-gso-tcpv4", 0))
1180 		vif->gso_mask |= GSO_BIT(TCPV4);
1181 
1182 	if (xenbus_read_unsigned(dev->otherend, "feature-gso-tcpv6", 0))
1183 		vif->gso_mask |= GSO_BIT(TCPV6);
1184 
1185 	vif->ip_csum = !xenbus_read_unsigned(dev->otherend,
1186 					     "feature-no-csum-offload", 0);
1187 
1188 	vif->ipv6_csum = !!xenbus_read_unsigned(dev->otherend,
1189 						"feature-ipv6-csum-offload", 0);
1190 
1191 	return 0;
1192 }
1193 
1194 static const struct xenbus_device_id netback_ids[] = {
1195 	{ "vif" },
1196 	{ "" }
1197 };
1198 
1199 static struct xenbus_driver netback_driver = {
1200 	.ids = netback_ids,
1201 	.probe = netback_probe,
1202 	.remove = netback_remove,
1203 	.uevent = netback_uevent,
1204 	.otherend_changed = frontend_changed,
1205 };
1206 
1207 int xenvif_xenbus_init(void)
1208 {
1209 	return xenbus_register_backend(&netback_driver);
1210 }
1211 
1212 void xenvif_xenbus_fini(void)
1213 {
1214 	return xenbus_unregister_driver(&netback_driver);
1215 }
1216