tilepro.c 64.5 KB
Newer Older
1
/*
2
 * Copyright 2011 Tilera Corporation. All Rights Reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
 *
 *   This program is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU General Public License
 *   as published by the Free Software Foundation, version 2.
 *
 *   This program is distributed in the hope that it will be useful, but
 *   WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
 *   NON INFRINGEMENT.  See the GNU General Public License for
 *   more details.
 */

#include <linux/module.h>
#include <linux/init.h>
#include <linux/moduleparam.h>
#include <linux/sched.h>
#include <linux/kernel.h>      /* printk() */
#include <linux/slab.h>        /* kmalloc() */
#include <linux/errno.h>       /* error codes */
#include <linux/types.h>       /* size_t */
#include <linux/interrupt.h>
#include <linux/in.h>
#include <linux/netdevice.h>   /* struct device, and other headers */
#include <linux/etherdevice.h> /* eth_type_trans */
#include <linux/skbuff.h>
#include <linux/ioctl.h>
#include <linux/cdev.h>
#include <linux/hugetlb.h>
#include <linux/in6.h>
#include <linux/timer.h>
#include <linux/io.h>
#include <asm/checksum.h>
#include <asm/homecache.h>

#include <hv/drv_xgbe_intf.h>
#include <hv/drv_xgbe_impl.h>
#include <hv/hypervisor.h>
#include <hv/netio_intf.h>

/* For TSO */
#include <linux/ip.h>
#include <linux/tcp.h>


/*
 * First, "tile_net_init_module()" initializes all four "devices" which
 * can be used by linux.
 *
 * Then, "ifconfig DEVICE up" calls "tile_net_open()", which analyzes
 * the network cpus, then uses "tile_net_open_aux()" to initialize
 * LIPP/LEPP, and then uses "tile_net_open_inner()" to register all
 * the tiles, provide buffers to LIPP, allow ingress to start, and
 * turn on hypervisor interrupt handling (and NAPI) on all tiles.
 *
 * If registration fails due to the link being down, then "retry_work"
 * is used to keep calling "tile_net_open_inner()" until it succeeds.
 *
 * If "ifconfig DEVICE down" is called, it uses "tile_net_stop()" to
 * stop egress, drain the LIPP buffers, unregister all the tiles, stop
 * LIPP/LEPP, and wipe the LEPP queue.
 *
 * We start out with the ingress interrupt enabled on each CPU.  When
 * this interrupt fires, we disable it, and call "napi_schedule()".
 * This will cause "tile_net_poll()" to be called, which will pull
 * packets from the netio queue, filtering them out, or passing them
 * to "netif_receive_skb()".  If our budget is exhausted, we will
 * return, knowing we will be called again later.  Otherwise, we
 * reenable the ingress interrupt, and call "napi_complete()".
 *
72 73 74
 * HACK: Since disabling the ingress interrupt is not reliable, we
 * ignore the interrupt if the global "active" flag is false.
 *
75 76
 *
 * NOTE: The use of "native_driver" ensures that EPP exists, and that
77
 * we are using "LIPP" and "LEPP".
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
 *
 * NOTE: Failing to free completions for an arbitrarily long time
 * (which is defined to be illegal) does in fact cause bizarre
 * problems.  The "egress_timer" helps prevent this from happening.
 */


/* HACK: Allow use of "jumbo" packets. */
/* This should be 1500 if "jumbo" is not set in LIPP. */
/* This should be at most 10226 (10240 - 14) if "jumbo" is set in LIPP. */
/* ISSUE: This has not been thoroughly tested (except at 1500). */
#define TILE_NET_MTU 1500

/* HACK: Define to support GSO. */
/* ISSUE: This may actually hurt performance of the TCP blaster. */
/* #define TILE_NET_GSO */

/* Define this to collapse "duplicate" acks. */
/* #define IGNORE_DUP_ACKS */

/* HACK: Define this to verify incoming packets. */
/* #define TILE_NET_VERIFY_INGRESS */

/* Use 3000 to enable the Linux Traffic Control (QoS) layer, else 0. */
#define TILE_NET_TX_QUEUE_LEN 0

/* Define to dump packets (prints out the whole packet on tx and rx). */
/* #define TILE_NET_DUMP_PACKETS */

/* Define to enable debug spew (all PDEBUG's are enabled). */
/* #define TILE_NET_DEBUG */


/* Define to activate paranoia checks. */
/* #define TILE_NET_PARANOIA */

/* Default transmit lockup timeout period, in jiffies. */
#define TILE_NET_TIMEOUT (5 * HZ)

/* Default retry interval for bringing up the NetIO interface, in jiffies. */
#define TILE_NET_RETRY_INTERVAL (5 * HZ)

/* Number of ports (xgbe0, xgbe1, gbe0, gbe1). */
#define TILE_NET_DEVS 4



/* Paranoia. */
#if NET_IP_ALIGN != LIPP_PACKET_PADDING
#error "NET_IP_ALIGN must match LIPP_PACKET_PADDING."
#endif


/* Debug print. */
#ifdef TILE_NET_DEBUG
#define PDEBUG(fmt, args...) net_printk(fmt, ## args)
#else
#define PDEBUG(fmt, args...)
#endif


MODULE_AUTHOR("Tilera");
MODULE_LICENSE("GPL");

142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
/*
 * Queue of incoming packets for a specific cpu and device.
 *
 * Includes a pointer to the "system" data, and the actual "user" data.
 */
struct tile_netio_queue {
	netio_queue_impl_t *__system_part;
	netio_queue_user_impl_t __user_part;

};


/*
 * Statistics counters for a specific cpu and device.
 */
struct tile_net_stats_t {
	u32 rx_packets;
	u32 rx_bytes;
	u32 tx_packets;
	u32 tx_bytes;
};


/*
 * Info for a specific cpu and device.
 *
 * ISSUE: There is a "dev" pointer in "napi" as well.
 */
struct tile_net_cpu {
	/* The NAPI struct. */
	struct napi_struct napi;
	/* Packet queue. */
	struct tile_netio_queue queue;
	/* Statistics. */
	struct tile_net_stats_t stats;
178
	/* True iff NAPI is enabled. */
179
	bool napi_enabled;
180
	/* True if this tile has successfully registered with the IPP. */
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
	bool registered;
	/* True if the link was down last time we tried to register. */
	bool link_down;
	/* True if "egress_timer" is scheduled. */
	bool egress_timer_scheduled;
	/* Number of small sk_buffs which must still be provided. */
	unsigned int num_needed_small_buffers;
	/* Number of large sk_buffs which must still be provided. */
	unsigned int num_needed_large_buffers;
	/* A timer for handling egress completions. */
	struct timer_list egress_timer;
};


/*
 * Info for a specific device.
 */
struct tile_net_priv {
	/* Our network device. */
	struct net_device *dev;
201 202 203 204 205 206
	/* Pages making up the egress queue. */
	struct page *eq_pages;
	/* Address of the actual egress queue. */
	lepp_queue_t *eq;
	/* Protects "eq". */
	spinlock_t eq_lock;
207 208 209 210 211
	/* The hypervisor handle for this interface. */
	int hv_devhdl;
	/* The intr bit mask that IDs this device. */
	u32 intr_id;
	/* True iff "tile_net_open_aux()" has succeeded. */
212 213 214
	bool partly_opened;
	/* True iff the device is "active". */
	bool active;
215 216 217 218 219 220 221 222 223 224 225 226 227 228
	/* Effective network cpus. */
	struct cpumask network_cpus_map;
	/* Number of network cpus. */
	int network_cpus_count;
	/* Credits per network cpu. */
	int network_cpus_credits;
	/* Network stats. */
	struct net_device_stats stats;
	/* For NetIO bringup retries. */
	struct delayed_work retry_work;
	/* Quick access to per cpu data. */
	struct tile_net_cpu *cpu[NR_CPUS];
};

229 230 231 232
/* Log2 of the number of small pages needed for the egress queue. */
#define EQ_ORDER  get_order(sizeof(lepp_queue_t))
/* Size of the egress queue's pages. */
#define EQ_SIZE   (1 << (PAGE_SHIFT + EQ_ORDER))
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

/*
 * The actual devices (xgbe0, xgbe1, gbe0, gbe1).
 */
static struct net_device *tile_net_devs[TILE_NET_DEVS];

/*
 * The "tile_net_cpu" structures for each device.
 */
static DEFINE_PER_CPU(struct tile_net_cpu, hv_xgbe0);
static DEFINE_PER_CPU(struct tile_net_cpu, hv_xgbe1);
static DEFINE_PER_CPU(struct tile_net_cpu, hv_gbe0);
static DEFINE_PER_CPU(struct tile_net_cpu, hv_gbe1);


/*
 * True if "network_cpus" was specified.
 */
static bool network_cpus_used;

/*
 * The actual cpus in "network_cpus".
 */
static struct cpumask network_cpus_map;



#ifdef TILE_NET_DEBUG
/*
 * printk with extra stuff.
 *
 * We print the CPU we're running in brackets.
 */
static void net_printk(char *fmt, ...)
{
	int i;
	int len;
	va_list args;
	static char buf[256];

	len = sprintf(buf, "tile_net[%2.2d]: ", smp_processor_id());
	va_start(args, fmt);
	i = vscnprintf(buf + len, sizeof(buf) - len - 1, fmt, args);
	va_end(args);
	buf[255] = '\0';
	pr_notice(buf);
}
#endif


#ifdef TILE_NET_DUMP_PACKETS
/*
 * Dump a packet.
 */
static void dump_packet(unsigned char *data, unsigned long length, char *s)
{
289 290
	int my_cpu = smp_processor_id();

291
	unsigned long i;
292 293
	char buf[128];

294 295 296 297 298 299 300 301 302
	static unsigned int count;

	pr_info("dump_packet(data %p, length 0x%lx s %s count 0x%x)\n",
	       data, length, s, count++);

	pr_info("\n");

	for (i = 0; i < length; i++) {
		if ((i & 0xf) == 0)
303
			sprintf(buf, "[%02d] %8.8lx:", my_cpu, i);
304
		sprintf(buf + strlen(buf), " %2.2x", data[i]);
305 306 307 308
		if ((i & 0xf) == 0xf || i == length - 1) {
			strcat(buf, "\n");
			pr_info("%s", buf);
		}
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
	}
}
#endif


/*
 * Provide support for the __netio_fastio1() swint
 * (see <hv/drv_xgbe_intf.h> for how it is used).
 *
 * The fastio swint2 call may clobber all the caller-saved registers.
 * It rarely clobbers memory, but we allow for the possibility in
 * the signature just to be on the safe side.
 *
 * Also, gcc doesn't seem to allow an input operand to be
 * clobbered, so we fake it with dummy outputs.
 *
 * This function can't be static because of the way it is declared
 * in the netio header.
 */
inline int __netio_fastio1(u32 fastio_index, u32 arg0)
{
	long result, clobber_r1, clobber_r10;
	asm volatile("swint2"
		     : "=R00" (result),
		       "=R01" (clobber_r1), "=R10" (clobber_r10)
		     : "R10" (fastio_index), "R01" (arg0)
		     : "memory", "r2", "r3", "r4",
		       "r5", "r6", "r7", "r8", "r9",
		       "r11", "r12", "r13", "r14",
		       "r15", "r16", "r17", "r18", "r19",
		       "r20", "r21", "r22", "r23", "r24",
		       "r25", "r26", "r27", "r28", "r29");
	return result;
}


345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
static void tile_net_return_credit(struct tile_net_cpu *info)
{
	struct tile_netio_queue *queue = &info->queue;
	netio_queue_user_impl_t *qup = &queue->__user_part;

	/* Return four credits after every fourth packet. */
	if (--qup->__receive_credit_remaining == 0) {
		u32 interval = qup->__receive_credit_interval;
		qup->__receive_credit_remaining = interval;
		__netio_fastio_return_credits(qup->__fastio_index, interval);
	}
}



360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
/*
 * Provide a linux buffer to LIPP.
 */
static void tile_net_provide_linux_buffer(struct tile_net_cpu *info,
					  void *va, bool small)
{
	struct tile_netio_queue *queue = &info->queue;

	/* Convert "va" and "small" to "linux_buffer_t". */
	unsigned int buffer = ((unsigned int)(__pa(va) >> 7) << 1) + small;

	__netio_fastio_free_buffer(queue->__user_part.__fastio_index, buffer);
}


/*
 * Provide a linux buffer for LIPP.
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
 *
 * Note that the ACTUAL allocation for each buffer is a "struct sk_buff",
 * plus a chunk of memory that includes not only the requested bytes, but
 * also NET_SKB_PAD bytes of initial padding, and a "struct skb_shared_info".
 *
 * Note that "struct skb_shared_info" is 88 bytes with 64K pages and
 * 268 bytes with 4K pages (since the frags[] array needs 18 entries).
 *
 * Without jumbo packets, the maximum packet size will be 1536 bytes,
 * and we use 2 bytes (NET_IP_ALIGN) of padding.  ISSUE: If we told
 * the hardware to clip at 1518 bytes instead of 1536 bytes, then we
 * could save an entire cache line, but in practice, we don't need it.
 *
 * Since CPAs are 38 bits, and we can only encode the high 31 bits in
 * a "linux_buffer_t", the low 7 bits must be zero, and thus, we must
 * align the actual "va" mod 128.
 *
 * We assume that the underlying "head" will be aligned mod 64.  Note
 * that in practice, we have seen "head" NOT aligned mod 128 even when
 * using 2048 byte allocations, which is surprising.
 *
 * If "head" WAS always aligned mod 128, we could change LIPP to
 * assume that the low SIX bits are zero, and the 7th bit is one, that
 * is, align the actual "va" mod 128 plus 64, which would be "free".
 *
 * For now, the actual "head" pointer points at NET_SKB_PAD bytes of
 * padding, plus 28 or 92 bytes of extra padding, plus the sk_buff
 * pointer, plus the NET_IP_ALIGN padding, plus 126 or 1536 bytes for
 * the actual packet, plus 62 bytes of empty padding, plus some
 * padding and the "struct skb_shared_info".
 *
 * With 64K pages, a large buffer thus needs 32+92+4+2+1536+62+88
 * bytes, or 1816 bytes, which fits comfortably into 2048 bytes.
 *
 * With 64K pages, a small buffer thus needs 32+92+4+2+126+88
 * bytes, or 344 bytes, which means we are wasting 64+ bytes, and
 * could presumably increase the size of small buffers.
 *
 * With 4K pages, a large buffer thus needs 32+92+4+2+1536+62+268
 * bytes, or 1996 bytes, which fits comfortably into 2048 bytes.
 *
 * With 4K pages, a small buffer thus needs 32+92+4+2+126+268
 * bytes, or 524 bytes, which is annoyingly wasteful.
 *
 * Maybe we should increase LIPP_SMALL_PACKET_SIZE to 192?
 *
 * ISSUE: Maybe we should increase "NET_SKB_PAD" to 64?
424 425 426 427
 */
static bool tile_net_provide_needed_buffer(struct tile_net_cpu *info,
					   bool small)
{
428 429 430 431 432
#if TILE_NET_MTU <= 1536
	/* Without "jumbo", 2 + 1536 should be sufficient. */
	unsigned int large_size = NET_IP_ALIGN + 1536;
#else
	/* ISSUE: This has not been tested. */
433
	unsigned int large_size = NET_IP_ALIGN + TILE_NET_MTU + 100;
434
#endif
435

436
	/* Avoid "false sharing" with last cache line. */
437
	/* ISSUE: This is already done by "netdev_alloc_skb()". */
438
	unsigned int len =
439 440 441
		 (((small ? LIPP_SMALL_PACKET_SIZE : large_size) +
		   CHIP_L2_LINE_SIZE() - 1) & -CHIP_L2_LINE_SIZE());

442 443
	unsigned int padding = 128 - NET_SKB_PAD;
	unsigned int align;
444 445 446 447 448 449

	struct sk_buff *skb;
	void *va;

	struct sk_buff **skb_ptr;

450
	/* Request 96 extra bytes for alignment purposes. */
451
	skb = netdev_alloc_skb(info->napi.dev, len + padding);
452 453
	if (skb == NULL)
		return false;
454

455 456 457 458
	/* Skip 32 or 96 bytes to align "data" mod 128. */
	align = -(long)skb->data & (128 - 1);
	BUG_ON(align > padding);
	skb_reserve(skb, align);
459

460 461
	/* This address is given to IPP. */
	va = skb->data;
462

463 464
	/* Buffers must not span a huge page. */
	BUG_ON(((((long)va & ~HPAGE_MASK) + len) & HPAGE_MASK) != 0);
465

466 467 468 469 470 471 472
#ifdef TILE_NET_PARANOIA
#if CHIP_HAS_CBOX_HOME_MAP()
	if (hash_default) {
		HV_PTE pte = *virt_to_pte(current->mm, (unsigned long)va);
		if (hv_pte_get_mode(pte) != HV_PTE_MODE_CACHE_HASH_L3)
			panic("Non-HFH ingress buffer! VA=%p Mode=%d PTE=%llx",
			      va, hv_pte_get_mode(pte), hv_pte_val(pte));
473
	}
474 475 476 477 478 479
#endif
#endif

	/* Invalidate the packet buffer. */
	if (!hash_default)
		__inv_buffer(va, len);
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

	/* Skip two bytes to satisfy LIPP assumptions. */
	/* Note that this aligns IP on a 16 byte boundary. */
	/* ISSUE: Do this when the packet arrives? */
	skb_reserve(skb, NET_IP_ALIGN);

	/* Save a back-pointer to 'skb'. */
	skb_ptr = va - sizeof(*skb_ptr);
	*skb_ptr = skb;

	/* Make sure "skb_ptr" has been flushed. */
	__insn_mf();

	/* Provide the new buffer. */
	tile_net_provide_linux_buffer(info, va, small);

	return true;
}


/*
 * Provide linux buffers for LIPP.
 */
static void tile_net_provide_needed_buffers(struct tile_net_cpu *info)
{
	while (info->num_needed_small_buffers != 0) {
		if (!tile_net_provide_needed_buffer(info, true))
			goto oops;
		info->num_needed_small_buffers--;
	}

	while (info->num_needed_large_buffers != 0) {
		if (!tile_net_provide_needed_buffer(info, false))
			goto oops;
		info->num_needed_large_buffers--;
	}

	return;

oops:

	/* Add a description to the page allocation failure dump. */
	pr_notice("Could not provide a linux buffer to LIPP.\n");
}


/*
 * Grab some LEPP completions, and store them in "comps", of size
 * "comps_size", and return the number of completions which were
 * stored, so the caller can free them.
 */
531
static unsigned int tile_net_lepp_grab_comps(lepp_queue_t *eq,
532 533
					     struct sk_buff *comps[],
					     unsigned int comps_size,
534
					     unsigned int min_size)
535 536 537
{
	unsigned int n = 0;

538 539
	unsigned int comp_head = eq->comp_head;
	unsigned int comp_busy = eq->comp_busy;
540 541 542 543 544 545

	while (comp_head != comp_busy && n < comps_size) {
		comps[n++] = eq->comps[comp_head];
		LEPP_QINC(comp_head);
	}

546 547
	if (n < min_size)
		return 0;
548 549 550 551 552 553 554

	eq->comp_head = comp_head;

	return n;
}


555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
/*
 * Free some comps, and return true iff there are still some pending.
 */
static bool tile_net_lepp_free_comps(struct net_device *dev, bool all)
{
	struct tile_net_priv *priv = netdev_priv(dev);

	lepp_queue_t *eq = priv->eq;

	struct sk_buff *olds[64];
	unsigned int wanted = 64;
	unsigned int i, n;
	bool pending;

	spin_lock(&priv->eq_lock);

	if (all)
		eq->comp_busy = eq->comp_tail;

	n = tile_net_lepp_grab_comps(eq, olds, wanted, 0);

	pending = (eq->comp_head != eq->comp_tail);

	spin_unlock(&priv->eq_lock);

	for (i = 0; i < n; i++)
		kfree_skb(olds[i]);

	return pending;
}


587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
/*
 * Make sure the egress timer is scheduled.
 *
 * Note that we use "schedule if not scheduled" logic instead of the more
 * obvious "reschedule" logic, because "reschedule" is fairly expensive.
 */
static void tile_net_schedule_egress_timer(struct tile_net_cpu *info)
{
	if (!info->egress_timer_scheduled) {
		mod_timer_pinned(&info->egress_timer, jiffies + 1);
		info->egress_timer_scheduled = true;
	}
}


/*
 * The "function" for "info->egress_timer".
 *
 * This timer will reschedule itself as long as there are any pending
 * completions expected (on behalf of any tile).
 *
 * ISSUE: Realistically, will the timer ever stop scheduling itself?
 *
 * ISSUE: This timer is almost never actually needed, so just use a global
 * timer that can run on any tile.
 *
 * ISSUE: Maybe instead track number of expected completions, and free
 * only that many, resetting to zero if "pending" is ever false.
 */
static void tile_net_handle_egress_timer(unsigned long arg)
{
	struct tile_net_cpu *info = (struct tile_net_cpu *)arg;
	struct net_device *dev = info->napi.dev;

	/* The timer is no longer scheduled. */
	info->egress_timer_scheduled = false;

624 625
	/* Free comps, and reschedule timer if more are pending. */
	if (tile_net_lepp_free_comps(dev, false))
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
		tile_net_schedule_egress_timer(info);
}


#ifdef IGNORE_DUP_ACKS

/*
 * Help detect "duplicate" ACKs.  These are sequential packets (for a
 * given flow) which are exactly 66 bytes long, sharing everything but
 * ID=2@0x12, Hsum=2@0x18, Ack=4@0x2a, WinSize=2@0x30, Csum=2@0x32,
 * Tstamps=10@0x38.  The ID's are +1, the Hsum's are -1, the Ack's are
 * +N, and the Tstamps are usually identical.
 *
 * NOTE: Apparently truly duplicate acks (with identical "ack" values),
 * should not be collapsed, as they are used for some kind of flow control.
 */
static bool is_dup_ack(char *s1, char *s2, unsigned int len)
{
	int i;

	unsigned long long ignorable = 0;

	/* Identification. */
	ignorable |= (1ULL << 0x12);
	ignorable |= (1ULL << 0x13);

	/* Header checksum. */
	ignorable |= (1ULL << 0x18);
	ignorable |= (1ULL << 0x19);

	/* ACK. */
	ignorable |= (1ULL << 0x2a);
	ignorable |= (1ULL << 0x2b);
	ignorable |= (1ULL << 0x2c);
	ignorable |= (1ULL << 0x2d);

	/* WinSize. */
	ignorable |= (1ULL << 0x30);
	ignorable |= (1ULL << 0x31);

	/* Checksum. */
	ignorable |= (1ULL << 0x32);
	ignorable |= (1ULL << 0x33);

	for (i = 0; i < len; i++, ignorable >>= 1) {

		if ((ignorable & 1) || (s1[i] == s2[i]))
			continue;

#ifdef TILE_NET_DEBUG
		/* HACK: Mention non-timestamp diffs. */
		if (i < 0x38 && i != 0x2f &&
		    net_ratelimit())
			pr_info("Diff at 0x%x\n", i);
#endif

		return false;
	}

#ifdef TILE_NET_NO_SUPPRESS_DUP_ACKS
	/* HACK: Do not suppress truly duplicate ACKs. */
	/* ISSUE: Is this actually necessary or helpful? */
	if (s1[0x2a] == s2[0x2a] &&
	    s1[0x2b] == s2[0x2b] &&
	    s1[0x2c] == s2[0x2c] &&
	    s1[0x2d] == s2[0x2d]) {
		return false;
	}
#endif

	return true;
}

#endif



703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
static void tile_net_discard_aux(struct tile_net_cpu *info, int index)
{
	struct tile_netio_queue *queue = &info->queue;
	netio_queue_impl_t *qsp = queue->__system_part;
	netio_queue_user_impl_t *qup = &queue->__user_part;

	int index2_aux = index + sizeof(netio_pkt_t);
	int index2 =
		((index2_aux ==
		  qsp->__packet_receive_queue.__last_packet_plus_one) ?
		 0 : index2_aux);

	netio_pkt_t *pkt = (netio_pkt_t *)((unsigned long) &qsp[1] + index);

	/* Extract the "linux_buffer_t". */
	unsigned int buffer = pkt->__packet.word;

	/* Convert "linux_buffer_t" to "va". */
	void *va = __va((phys_addr_t)(buffer >> 1) << 7);

	/* Acquire the associated "skb". */
	struct sk_buff **skb_ptr = va - sizeof(*skb_ptr);
	struct sk_buff *skb = *skb_ptr;

	kfree_skb(skb);

	/* Consume this packet. */
	qup->__packet_receive_read = index2;
}


734
/*
735
 * Like "tile_net_poll()", but just discard packets.
736 737 738 739 740 741 742 743 744 745 746 747 748
 */
static void tile_net_discard_packets(struct net_device *dev)
{
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info = priv->cpu[my_cpu];
	struct tile_netio_queue *queue = &info->queue;
	netio_queue_impl_t *qsp = queue->__system_part;
	netio_queue_user_impl_t *qup = &queue->__user_part;

	while (qup->__packet_receive_read !=
	       qsp->__packet_receive_queue.__packet_write) {
		int index = qup->__packet_receive_read;
749
		tile_net_discard_aux(info, index);
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
	}
}


/*
 * Handle the next packet.  Return true if "processed", false if "filtered".
 */
static bool tile_net_poll_aux(struct tile_net_cpu *info, int index)
{
	struct net_device *dev = info->napi.dev;

	struct tile_netio_queue *queue = &info->queue;
	netio_queue_impl_t *qsp = queue->__system_part;
	netio_queue_user_impl_t *qup = &queue->__user_part;
	struct tile_net_stats_t *stats = &info->stats;

	int filter;

	int index2_aux = index + sizeof(netio_pkt_t);
	int index2 =
		((index2_aux ==
		  qsp->__packet_receive_queue.__last_packet_plus_one) ?
		 0 : index2_aux);

	netio_pkt_t *pkt = (netio_pkt_t *)((unsigned long) &qsp[1] + index);

	netio_pkt_metadata_t *metadata = NETIO_PKT_METADATA(pkt);

778 779
	/* Extract the packet size.  FIXME: Shouldn't the second line */
	/* get subtracted?  Mostly moot, since it should be "zero". */
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
	unsigned long len =
		(NETIO_PKT_CUSTOM_LENGTH(pkt) +
		 NET_IP_ALIGN - NETIO_PACKET_PADDING);

	/* Extract the "linux_buffer_t". */
	unsigned int buffer = pkt->__packet.word;

	/* Extract "small" (vs "large"). */
	bool small = ((buffer & 1) != 0);

	/* Convert "linux_buffer_t" to "va". */
	void *va = __va((phys_addr_t)(buffer >> 1) << 7);

	/* Extract the packet data pointer. */
	/* Compare to "NETIO_PKT_CUSTOM_DATA(pkt)". */
	unsigned char *buf = va + NET_IP_ALIGN;

	/* Invalidate the packet buffer. */
	if (!hash_default)
		__inv_buffer(buf, len);

	/* ISSUE: Is this needed? */
	dev->last_rx = jiffies;

#ifdef TILE_NET_DUMP_PACKETS
	dump_packet(buf, len, "rx");
#endif /* TILE_NET_DUMP_PACKETS */

#ifdef TILE_NET_VERIFY_INGRESS
	if (!NETIO_PKT_L4_CSUM_CORRECT_M(metadata, pkt) &&
	    NETIO_PKT_L4_CSUM_CALCULATED_M(metadata, pkt)) {
811
		/* Bug 6624: Includes UDP packets with a "zero" checksum. */
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
		pr_warning("Bad L4 checksum on %d byte packet.\n", len);
	}
	if (!NETIO_PKT_L3_CSUM_CORRECT_M(metadata, pkt) &&
	    NETIO_PKT_L3_CSUM_CALCULATED_M(metadata, pkt)) {
		dump_packet(buf, len, "rx");
		panic("Bad L3 checksum.");
	}
	switch (NETIO_PKT_STATUS_M(metadata, pkt)) {
	case NETIO_PKT_STATUS_OVERSIZE:
		if (len >= 64) {
			dump_packet(buf, len, "rx");
			panic("Unexpected OVERSIZE.");
		}
		break;
	case NETIO_PKT_STATUS_BAD:
827
		pr_warning("Unexpected BAD %ld byte packet.\n", len);
828 829 830 831 832
	}
#endif

	filter = 0;

833 834
	/* ISSUE: Filter TCP packets with "bad" checksums? */

835 836 837
	if (!(dev->flags & IFF_UP)) {
		/* Filter packets received before we're up. */
		filter = 1;
838 839 840
	} else if (NETIO_PKT_STATUS_M(metadata, pkt) == NETIO_PKT_STATUS_BAD) {
		/* Filter "truncated" packets. */
		filter = 1;
841
	} else if (!(dev->flags & IFF_PROMISC)) {
842 843
		/* FIXME: Implement HW multicast filter. */
		if (!is_multicast_ether_addr(buf)) {
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
			/* Filter packets not for our address. */
			const u8 *mine = dev->dev_addr;
			filter = compare_ether_addr(mine, buf);
		}
	}

	if (filter) {

		/* ISSUE: Update "drop" statistics? */

		tile_net_provide_linux_buffer(info, va, small);

	} else {

		/* Acquire the associated "skb". */
		struct sk_buff **skb_ptr = va - sizeof(*skb_ptr);
		struct sk_buff *skb = *skb_ptr;

		/* Paranoia. */
		if (skb->data != buf)
			panic("Corrupt linux buffer from LIPP! "
			      "VA=%p, skb=%p, skb->data=%p\n",
			      va, skb, skb->data);

		/* Encode the actual packet length. */
		skb_put(skb, len);

		/* NOTE: This call also sets "skb->dev = dev". */
		skb->protocol = eth_type_trans(skb, dev);

874
		/* Avoid recomputing "good" TCP/UDP checksums. */
875 876 877 878 879 880 881 882 883
		if (NETIO_PKT_L4_CSUM_CORRECT_M(metadata, pkt))
			skb->ip_summed = CHECKSUM_UNNECESSARY;

		netif_receive_skb(skb);

		stats->rx_packets++;
		stats->rx_bytes += len;
	}

884 885 886
	/* ISSUE: It would be nice to defer this until the packet has */
	/* actually been processed. */
	tile_net_return_credit(info);
887 888 889 890 891 892 893 894 895 896 897

	/* Consume this packet. */
	qup->__packet_receive_read = index2;

	return !filter;
}


/*
 * Handle some packets for the given device on the current CPU.
 *
898 899 900 901 902 903 904 905
 * If "tile_net_stop()" is called on some other tile while this
 * function is running, we will return, hopefully before that
 * other tile asks us to call "napi_disable()".
 *
 * The "rotting packet" race condition occurs if a packet arrives
 * during the extremely narrow window between the queue appearing to
 * be empty, and the ingress interrupt being re-enabled.  This happens
 * a LOT under heavy network load.
906 907 908 909 910 911 912 913 914 915 916 917 918
 */
static int tile_net_poll(struct napi_struct *napi, int budget)
{
	struct net_device *dev = napi->dev;
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info = priv->cpu[my_cpu];
	struct tile_netio_queue *queue = &info->queue;
	netio_queue_impl_t *qsp = queue->__system_part;
	netio_queue_user_impl_t *qup = &queue->__user_part;

	unsigned int work = 0;

919
	while (priv->active) {
920 921 922 923 924 925 926 927 928 929 930 931
		int index = qup->__packet_receive_read;
		if (index == qsp->__packet_receive_queue.__packet_write)
			break;

		if (tile_net_poll_aux(info, index)) {
			if (++work >= budget)
				goto done;
		}
	}

	napi_complete(&info->napi);

932 933 934 935
	if (!priv->active)
		goto done;

	/* Re-enable the ingress interrupt. */
936
	enable_percpu_irq(priv->intr_id, 0);
937

938
	/* HACK: Avoid the "rotting packet" problem (see above). */
939
	if (qup->__packet_receive_read !=
940 941 942 943 944
	    qsp->__packet_receive_queue.__packet_write) {
		/* ISSUE: Sometimes this returns zero, presumably */
		/* because an interrupt was handled for this tile. */
		(void)napi_reschedule(&info->napi);
	}
945 946 947

done:

948 949
	if (priv->active)
		tile_net_provide_needed_buffers(info);
950 951 952 953 954 955 956

	return work;
}


/*
 * Handle an ingress interrupt for the given device on the current cpu.
957 958 959 960 961 962
 *
 * ISSUE: Sometimes this gets called after "disable_percpu_irq()" has
 * been called!  This is probably due to "pending hypervisor downcalls".
 *
 * ISSUE: Is there any race condition between the "napi_schedule()" here
 * and the "napi_complete()" call above?
963 964 965 966 967 968 969 970
 */
static irqreturn_t tile_net_handle_ingress_interrupt(int irq, void *dev_ptr)
{
	struct net_device *dev = (struct net_device *)dev_ptr;
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info = priv->cpu[my_cpu];

971
	/* Disable the ingress interrupt. */
972 973
	disable_percpu_irq(priv->intr_id);

974 975 976 977 978 979
	/* Ignore unwanted interrupts. */
	if (!priv->active)
		return IRQ_HANDLED;

	/* ISSUE: Sometimes "info->napi_enabled" is false here. */

980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
	napi_schedule(&info->napi);

	return IRQ_HANDLED;
}


/*
 * One time initialization per interface.
 */
static int tile_net_open_aux(struct net_device *dev)
{
	struct tile_net_priv *priv = netdev_priv(dev);

	int ret;
	int dummy;
	unsigned int epp_lotar;

	/*
	 * Find out where EPP memory should be homed.
	 */
	ret = hv_dev_pread(priv->hv_devhdl, 0,
			   (HV_VirtAddr)&epp_lotar, sizeof(epp_lotar),
			   NETIO_EPP_SHM_OFF);
	if (ret < 0) {
		pr_err("could not read epp_shm_queue lotar.\n");
		return -EIO;
	}

	/*
	 * Home the page on the EPP.
	 */
	{
		int epp_home = hv_lotar_to_cpu(epp_lotar);
1013
		homecache_change_page_home(priv->eq_pages, EQ_ORDER, epp_home);
1014 1015 1016 1017 1018 1019 1020 1021
	}

	/*
	 * Register the EPP shared memory queue.
	 */
	{
		netio_ipp_address_t ea = {
			.va = 0,
1022
			.pa = __pa(priv->eq),
1023
			.pte = hv_pte(0),
1024
			.size = EQ_SIZE,
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
		};
		ea.pte = hv_pte_set_lotar(ea.pte, epp_lotar);
		ea.pte = hv_pte_set_mode(ea.pte, HV_PTE_MODE_CACHE_TILE_L3);
		ret = hv_dev_pwrite(priv->hv_devhdl, 0,
				    (HV_VirtAddr)&ea,
				    sizeof(ea),
				    NETIO_EPP_SHM_OFF);
		if (ret < 0)
			return -EIO;
	}

	/*
	 * Start LIPP/LEPP.
	 */
	if (hv_dev_pwrite(priv->hv_devhdl, 0, (HV_VirtAddr)&dummy,
			  sizeof(dummy), NETIO_IPP_START_SHIM_OFF) < 0) {
		pr_warning("Failed to start LIPP/LEPP.\n");
		return -EIO;
	}

	return 0;
}


/*
1050
 * Register with hypervisor on the current CPU.
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
 *
 * Strangely, this function does important things even if it "fails",
 * which is especially common if the link is not up yet.  Hopefully
 * these things are all "harmless" if done twice!
 */
static void tile_net_register(void *dev_ptr)
{
	struct net_device *dev = (struct net_device *)dev_ptr;
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info;

	struct tile_netio_queue *queue;

	/* Only network cpus can receive packets. */
	int queue_id =
		cpumask_test_cpu(my_cpu, &priv->network_cpus_map) ? 0 : 255;

	netio_input_config_t config = {
		.flags = 0,
		.num_receive_packets = priv->network_cpus_credits,
		.queue_id = queue_id
	};

	int ret = 0;
	netio_queue_impl_t *queuep;

	PDEBUG("tile_net_register(queue_id %d)\n", queue_id);

	if (!strcmp(dev->name, "xgbe0"))
		info = &__get_cpu_var(hv_xgbe0);
	else if (!strcmp(dev->name, "xgbe1"))
		info = &__get_cpu_var(hv_xgbe1);
	else if (!strcmp(dev->name, "gbe0"))
		info = &__get_cpu_var(hv_gbe0);
	else if (!strcmp(dev->name, "gbe1"))
		info = &__get_cpu_var(hv_gbe1);
	else
		BUG();

	/* Initialize the egress timer. */
	init_timer(&info->egress_timer);
	info->egress_timer.data = (long)info;
	info->egress_timer.function = tile_net_handle_egress_timer;

	priv->cpu[my_cpu] = info;

	/*
1099 1100
	 * Register ourselves with LIPP.  This does a lot of stuff,
	 * including invoking the LIPP registration code.
1101 1102 1103 1104 1105 1106 1107 1108
	 */
	ret = hv_dev_pwrite(priv->hv_devhdl, 0,
			    (HV_VirtAddr)&config,
			    sizeof(netio_input_config_t),
			    NETIO_IPP_INPUT_REGISTER_OFF);
	PDEBUG("hv_dev_pwrite(NETIO_IPP_INPUT_REGISTER_OFF) returned %d\n",
	       ret);
	if (ret < 0) {
1109 1110 1111 1112 1113
		if (ret != NETIO_LINK_DOWN) {
			printk(KERN_DEBUG "hv_dev_pwrite "
			       "NETIO_IPP_INPUT_REGISTER_OFF failure %d\n",
			       ret);
		}
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
		info->link_down = (ret == NETIO_LINK_DOWN);
		return;
	}

	/*
	 * Get the pointer to our queue's system part.
	 */

	ret = hv_dev_pread(priv->hv_devhdl, 0,
			   (HV_VirtAddr)&queuep,
			   sizeof(netio_queue_impl_t *),
			   NETIO_IPP_INPUT_REGISTER_OFF);
	PDEBUG("hv_dev_pread(NETIO_IPP_INPUT_REGISTER_OFF) returned %d\n",
	       ret);
	PDEBUG("queuep %p\n", queuep);
	if (ret <= 0) {
		/* ISSUE: Shouldn't this be a fatal error? */
		pr_err("hv_dev_pread NETIO_IPP_INPUT_REGISTER_OFF failure\n");
		return;
	}

	queue = &info->queue;

	queue->__system_part = queuep;

	memset(&queue->__user_part, 0, sizeof(netio_queue_user_impl_t));

	/* This is traditionally "config.num_receive_packets / 2". */
	queue->__user_part.__receive_credit_interval = 4;
	queue->__user_part.__receive_credit_remaining =
		queue->__user_part.__receive_credit_interval;

	/*
	 * Get a fastio index from the hypervisor.
	 * ISSUE: Shouldn't this check the result?
	 */
	ret = hv_dev_pread(priv->hv_devhdl, 0,
			   (HV_VirtAddr)&queue->__user_part.__fastio_index,
			   sizeof(queue->__user_part.__fastio_index),
			   NETIO_IPP_GET_FASTIO_OFF);
	PDEBUG("hv_dev_pread(NETIO_IPP_GET_FASTIO_OFF) returned %d\n", ret);

	/* Now we are registered. */
	info->registered = true;
}


/*
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
 * Deregister with hypervisor on the current CPU.
 *
 * This simply discards all our credits, so no more packets will be
 * delivered to this tile.  There may still be packets in our queue.
 *
 * Also, disable the ingress interrupt.
 */
static void tile_net_deregister(void *dev_ptr)
{
	struct net_device *dev = (struct net_device *)dev_ptr;
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info = priv->cpu[my_cpu];

	/* Disable the ingress interrupt. */
	disable_percpu_irq(priv->intr_id);

	/* Do nothing else if not registered. */
	if (info == NULL || !info->registered)
		return;

	{
		struct tile_netio_queue *queue = &info->queue;
		netio_queue_user_impl_t *qup = &queue->__user_part;

		/* Discard all our credits. */
		__netio_fastio_return_credits(qup->__fastio_index, -1);
	}
}


/*
 * Unregister with hypervisor on the current CPU.
 *
 * Also, disable the ingress interrupt.
1197 1198 1199 1200 1201 1202 1203 1204
 */
static void tile_net_unregister(void *dev_ptr)
{
	struct net_device *dev = (struct net_device *)dev_ptr;
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info = priv->cpu[my_cpu];

1205
	int ret;
1206 1207
	int dummy = 0;

1208 1209
	/* Disable the ingress interrupt. */
	disable_percpu_irq(priv->intr_id);
1210

1211 1212
	/* Do nothing else if not registered. */
	if (info == NULL || !info->registered)
1213 1214
		return;

1215
	/* Unregister ourselves with LIPP/LEPP. */
1216 1217
	ret = hv_dev_pwrite(priv->hv_devhdl, 0, (HV_VirtAddr)&dummy,
			    sizeof(dummy), NETIO_IPP_INPUT_UNREGISTER_OFF);
1218 1219
	if (ret < 0)
		panic("Failed to unregister with LIPP/LEPP!\n");
1220

1221
	/* Discard all packets still in our NetIO queue. */
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
	tile_net_discard_packets(dev);

	/* Reset state. */
	info->num_needed_small_buffers = 0;
	info->num_needed_large_buffers = 0;

	/* Cancel egress timer. */
	del_timer(&info->egress_timer);
	info->egress_timer_scheduled = false;
}


/*
 * Helper function for "tile_net_stop()".
 *
 * Also used to handle registration failure in "tile_net_open_inner()",
1238
 * when the various extra steps in "tile_net_stop()" are not necessary.
1239 1240 1241 1242
 */
static void tile_net_stop_aux(struct net_device *dev)
{
	struct tile_net_priv *priv = netdev_priv(dev);
1243
	int i;
1244 1245 1246

	int dummy = 0;

1247 1248 1249 1250 1251
	/*
	 * Unregister all tiles, so LIPP will stop delivering packets.
	 * Also, delete all the "napi" objects (sequentially, to protect
	 * "dev->napi_list").
	 */
1252
	on_each_cpu(tile_net_unregister, (void *)dev, 1);
1253 1254 1255 1256 1257 1258 1259
	for_each_online_cpu(i) {
		struct tile_net_cpu *info = priv->cpu[i];
		if (info != NULL && info->registered) {
			netif_napi_del(&info->napi);
			info->registered = false;
		}
	}
1260 1261 1262 1263 1264 1265

	/* Stop LIPP/LEPP. */
	if (hv_dev_pwrite(priv->hv_devhdl, 0, (HV_VirtAddr)&dummy,
			  sizeof(dummy), NETIO_IPP_STOP_SHIM_OFF) < 0)
		panic("Failed to stop LIPP/LEPP!\n");

1266
	priv->partly_opened = false;
1267 1268 1269 1270
}


/*
1271
 * Disable NAPI for the given device on the current cpu.
1272
 */
1273
static void tile_net_stop_disable(void *dev_ptr)
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
{
	struct net_device *dev = (struct net_device *)dev_ptr;
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info = priv->cpu[my_cpu];

	/* Disable NAPI if needed. */
	if (info != NULL && info->napi_enabled) {
		napi_disable(&info->napi);
		info->napi_enabled = false;
	}
}


/*
1289 1290 1291 1292
 * Enable NAPI and the ingress interrupt for the given device
 * on the current cpu.
 *
 * ISSUE: Only do this for "network cpus"?
1293
 */
1294
static void tile_net_open_enable(void *dev_ptr)
1295 1296 1297 1298 1299 1300 1301 1302 1303
{
	struct net_device *dev = (struct net_device *)dev_ptr;
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info = priv->cpu[my_cpu];

	/* Enable NAPI. */
	napi_enable(&info->napi);
	info->napi_enabled = true;
1304 1305

	/* Enable the ingress interrupt. */
1306
	enable_percpu_irq(priv->intr_id, 0);
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
}


/*
 * tile_net_open_inner does most of the work of bringing up the interface.
 * It's called from tile_net_open(), and also from tile_net_retry_open().
 * The return value is 0 if the interface was brought up, < 0 if
 * tile_net_open() should return the return value as an error, and > 0 if
 * tile_net_open() should return success and schedule a work item to
 * periodically retry the bringup.
 */
static int tile_net_open_inner(struct net_device *dev)
{
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info;
	struct tile_netio_queue *queue;
1324
	int result = 0;
1325
	int i;
1326
	int dummy = 0;
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343

	/*
	 * First try to register just on the local CPU, and handle any
	 * semi-expected "link down" failure specially.  Note that we
	 * do NOT call "tile_net_stop_aux()", unlike below.
	 */
	tile_net_register(dev);
	info = priv->cpu[my_cpu];
	if (!info->registered) {
		if (info->link_down)
			return 1;
		return -EAGAIN;
	}

	/*
	 * Now register everywhere else.  If any registration fails,
	 * even for "link down" (which might not be possible), we
1344 1345 1346
	 * clean up using "tile_net_stop_aux()".  Also, add all the
	 * "napi" objects (sequentially, to protect "dev->napi_list").
	 * ISSUE: Only use "netif_napi_add()" for "network cpus"?
1347 1348 1349
	 */
	smp_call_function(tile_net_register, (void *)dev, 1);
	for_each_online_cpu(i) {
1350 1351 1352 1353 1354 1355 1356 1357 1358
		struct tile_net_cpu *info = priv->cpu[i];
		if (info->registered)
			netif_napi_add(dev, &info->napi, tile_net_poll, 64);
		else
			result = -EAGAIN;
	}
	if (result != 0) {
		tile_net_stop_aux(dev);
		return result;
1359 1360 1361 1362
	}

	queue = &info->queue;

1363 1364
	if (priv->intr_id == 0) {
		unsigned int irq;
1365

1366 1367 1368 1369 1370 1371 1372 1373
		/*
		 * Acquire the irq allocated by the hypervisor.  Every
		 * queue gets the same irq.  The "__intr_id" field is
		 * "1 << irq", so we use "__ffs()" to extract "irq".
		 */
		priv->intr_id = queue->__system_part->__intr_id;
		BUG_ON(priv->intr_id == 0);
		irq = __ffs(priv->intr_id);
1374

1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
		/*
		 * Register the ingress interrupt handler for this
		 * device, permanently.
		 *
		 * We used to call "free_irq()" in "tile_net_stop()",
		 * and then re-register the handler here every time,
		 * but that caused DNP errors in "handle_IRQ_event()"
		 * because "desc->action" was NULL.  See bug 9143.
		 */
		tile_irq_activate(irq, TILE_IRQ_PERCPU);
		BUG_ON(request_irq(irq, tile_net_handle_ingress_interrupt,
				   0, dev->name, (void *)dev) != 0);
	}
1388

1389
	{
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
		/* Allocate initial buffers. */

		int max_buffers =
			priv->network_cpus_count * priv->network_cpus_credits;

		info->num_needed_small_buffers =
			min(LIPP_SMALL_BUFFERS, max_buffers);

		info->num_needed_large_buffers =
			min(LIPP_LARGE_BUFFERS, max_buffers);

		tile_net_provide_needed_buffers(info);

		if (info->num_needed_small_buffers != 0 ||
		    info->num_needed_large_buffers != 0)
			panic("Insufficient memory for buffer stack!");
1406
	}
1407

1408 1409
	/* We are about to be active. */
	priv->active = true;
1410

1411 1412
	/* Make sure "active" is visible to all tiles. */
	mb();
1413

1414 1415 1416 1417 1418 1419 1420
	/* On each tile, enable NAPI and the ingress interrupt. */
	on_each_cpu(tile_net_open_enable, (void *)dev, 1);

	/* Start LIPP/LEPP and activate "ingress" at the shim. */
	if (hv_dev_pwrite(priv->hv_devhdl, 0, (HV_VirtAddr)&dummy,
			  sizeof(dummy), NETIO_IPP_INPUT_INIT_OFF) < 0)
		panic("Failed to activate the LIPP Shim!\n");
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445

	/* Start our transmit queue. */
	netif_start_queue(dev);

	return 0;
}


/*
 * Called periodically to retry bringing up the NetIO interface,
 * if it doesn't come up cleanly during tile_net_open().
 */
static void tile_net_open_retry(struct work_struct *w)
{
	struct delayed_work *dw =
		container_of(w, struct delayed_work, work);

	struct tile_net_priv *priv =
		container_of(dw, struct tile_net_priv, retry_work);

	/*
	 * Try to bring the NetIO interface up.  If it fails, reschedule
	 * ourselves to try again later; otherwise, tell Linux we now have
	 * a working link.  ISSUE: What if the return value is negative?
	 */
1446 1447 1448
	if (tile_net_open_inner(priv->dev) != 0)
		schedule_delayed_work(&priv->retry_work,
				      TILE_NET_RETRY_INTERVAL);
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
	else
		netif_carrier_on(priv->dev);
}


/*
 * Called when a network interface is made active.
 *
 * Returns 0 on success, negative value on failure.
 *
 * The open entry point is called when a network interface is made
 * active by the system (IFF_UP).  At this point all resources needed
 * for transmit and receive operations are allocated, the interrupt
1462 1463
 * handler is registered with the OS (if needed), the watchdog timer
 * is started, and the stack is notified that the interface is ready.
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
 *
 * If the actual link is not available yet, then we tell Linux that
 * we have no carrier, and we keep checking until the link comes up.
 */
static int tile_net_open(struct net_device *dev)
{
	int ret = 0;
	struct tile_net_priv *priv = netdev_priv(dev);

	/*
	 * We rely on priv->partly_opened to tell us if this is the
	 * first time this interface is being brought up. If it is
	 * set, the IPP was already initialized and should not be
	 * initialized again.
	 */
	if (!priv->partly_opened) {

		int count;
		int credits;

		/* Initialize LIPP/LEPP, and start the Shim. */
		ret = tile_net_open_aux(dev);
		if (ret < 0) {
			pr_err("tile_net_open_aux failed: %d\n", ret);
			return ret;
		}

		/* Analyze the network cpus. */

		if (network_cpus_used)
			cpumask_copy(&priv->network_cpus_map,
				     &network_cpus_map);
		else
			cpumask_copy(&priv->network_cpus_map, cpu_online_mask);


		count = cpumask_weight(&priv->network_cpus_map);

		/* Limit credits to available buffers, and apply min. */
		credits = max(16, (LIPP_LARGE_BUFFERS / count) & ~1);

		/* Apply "GBE" max limit. */
		/* ISSUE: Use higher limit for XGBE? */
		credits = min(NETIO_MAX_RECEIVE_PKTS, credits);

		priv->network_cpus_count = count;
		priv->network_cpus_credits = credits;

#ifdef TILE_NET_DEBUG
		pr_info("Using %d network cpus, with %d credits each\n",
		       priv->network_cpus_count, priv->network_cpus_credits);
#endif

1517
		priv->partly_opened = true;
1518 1519 1520 1521

	} else {
		/* FIXME: Is this possible? */
		/* printk("Already partly opened.\n"); */
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
	}

	/*
	 * Attempt to bring up the link.
	 */
	ret = tile_net_open_inner(dev);
	if (ret <= 0) {
		if (ret == 0)
			netif_carrier_on(dev);
		return ret;
	}

	/*
	 * We were unable to bring up the NetIO interface, but we want to
	 * try again in a little bit.  Tell Linux that we have no carrier
	 * so it doesn't try to use the interface before the link comes up
	 * and then remember to try again later.
	 */
	netif_carrier_off(dev);
1541
	schedule_delayed_work(&priv->retry_work, TILE_NET_RETRY_INTERVAL);
1542 1543 1544 1545 1546

	return 0;
}


1547
static int tile_net_drain_lipp_buffers(struct tile_net_priv *priv)
1548
{
1549
	int n = 0;
1550

1551
	/* Drain all the LIPP buffers. */
1552
	while (true) {
1553
		unsigned int buffer;
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573

		/* NOTE: This should never fail. */
		if (hv_dev_pread(priv->hv_devhdl, 0, (HV_VirtAddr)&buffer,
				 sizeof(buffer), NETIO_IPP_DRAIN_OFF) < 0)
			break;

		/* Stop when done. */
		if (buffer == 0)
			break;

		{
			/* Convert "linux_buffer_t" to "va". */
			void *va = __va((phys_addr_t)(buffer >> 1) << 7);

			/* Acquire the associated "skb". */
			struct sk_buff **skb_ptr = va - sizeof(*skb_ptr);
			struct sk_buff *skb = *skb_ptr;

			kfree_skb(skb);
		}
1574 1575

		n++;
1576 1577
	}

1578 1579
	return n;
}
1580 1581


1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
/*
 * Disables a network interface.
 *
 * Returns 0, this is not allowed to fail.
 *
 * The close entry point is called when an interface is de-activated
 * by the OS.  The hardware is still under the drivers control, but
 * needs to be disabled.  A global MAC reset is issued to stop the
 * hardware, and all transmit and receive resources are freed.
 *
 * ISSUE: How closely does "netif_running(dev)" mirror "priv->active"?
 *
 * Before we are called by "__dev_close()", "netif_running()" will
 * have been cleared, so no NEW calls to "tile_net_poll()" will be
 * made by "netpoll_poll_dev()".
 *
 * Often, this can cause some tiles to still have packets in their
 * queues, so we must call "tile_net_discard_packets()" later.
 *
 * Note that some other tile may still be INSIDE "tile_net_poll()",
 * and in fact, many will be, if there is heavy network load.
 *
 * Calling "on_each_cpu(tile_net_stop_disable, (void *)dev, 1)" when
 * any tile is still "napi_schedule()"'d will induce a horrible crash
 * when "msleep()" is called.  This includes tiles which are inside
 * "tile_net_poll()" which have not yet called "napi_complete()".
 *
 * So, we must first try to wait long enough for other tiles to finish
 * with any current "tile_net_poll()" call, and, hopefully, to clear
 * the "scheduled" flag.  ISSUE: It is unclear what happens to tiles
 * which have called "napi_schedule()" but which had not yet tried to
 * call "tile_net_poll()", or which exhausted their budget inside
 * "tile_net_poll()" just before this function was called.
 */
static int tile_net_stop(struct net_device *dev)
{
	struct tile_net_priv *priv = netdev_priv(dev);

	PDEBUG("tile_net_stop()\n");
1621

1622 1623 1624 1625 1626
	/* Start discarding packets. */
	priv->active = false;

	/* Make sure "active" is visible to all tiles. */
	mb();
1627 1628

	/*
1629 1630 1631 1632 1633 1634
	 * On each tile, make sure no NEW packets get delivered, and
	 * disable the ingress interrupt.
	 *
	 * Note that the ingress interrupt can fire AFTER this,
	 * presumably due to packets which were recently delivered,
	 * but it will have no effect.
1635
	 */
1636
	on_each_cpu(tile_net_deregister, (void *)dev, 1);
1637

1638 1639
	/* Optimistically drain LIPP buffers. */
	(void)tile_net_drain_lipp_buffers(priv);
1640

1641 1642
	/* ISSUE: Only needed if not yet fully open. */
	cancel_delayed_work_sync(&priv->retry_work);
1643

1644 1645
	/* Can't transmit any more. */
	netif_stop_queue(dev);
1646

1647 1648 1649 1650 1651 1652 1653 1654 1655
	/* Disable NAPI on each tile. */
	on_each_cpu(tile_net_stop_disable, (void *)dev, 1);

	/*
	 * Drain any remaining LIPP buffers.  NOTE: This "printk()"
	 * has never been observed, but in theory it could happen.
	 */
	if (tile_net_drain_lipp_buffers(priv) != 0)
		printk("Had to drain some extra LIPP buffers!\n");
1656

1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
	/* Stop LIPP/LEPP. */
	tile_net_stop_aux(dev);

	/*
	 * ISSUE: It appears that, in practice anyway, by the time we
	 * get here, there are no pending completions, but just in case,
	 * we free (all of) them anyway.
	 */
	while (tile_net_lepp_free_comps(dev, true))
		/* loop */;
1667

1668
	/* Wipe the EPP queue, and wait till the stores hit the EPP. */
1669
	memset(priv->eq, 0, sizeof(lepp_queue_t));
1670
	mb();
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693

	return 0;
}


/*
 * Prepare the "frags" info for the resulting LEPP command.
 *
 * If needed, flush the memory used by the frags.
 */
static unsigned int tile_net_tx_frags(lepp_frag_t *frags,
				      struct sk_buff *skb,
				      void *b_data, unsigned int b_len)
{
	unsigned int i, n = 0;

	struct skb_shared_info *sh = skb_shinfo(skb);

	phys_addr_t cpa;

	if (b_len != 0) {

		if (!hash_default)
1694
			finv_buffer_remote(b_data, b_len, 0);
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706

		cpa = __pa(b_data);
		frags[n].cpa_lo = cpa;
		frags[n].cpa_hi = cpa >> 32;
		frags[n].length = b_len;
		frags[n].hash_for_home = hash_default;
		n++;
	}

	for (i = 0; i < sh->nr_frags; i++) {

		skb_frag_t *f = &sh->frags[i];
1707
		unsigned long pfn = page_to_pfn(skb_frag_page(f));
1708 1709 1710 1711 1712 1713 1714 1715

		/* FIXME: Compute "hash_for_home" properly. */
		/* ISSUE: The hypervisor checks CHIP_HAS_REV1_DMA_PACKETS(). */
		int hash_for_home = hash_default;

		/* FIXME: Hmmm. */
		if (!hash_default) {
			void *va = pfn_to_kaddr(pfn) + f->page_offset;
1716
			BUG_ON(PageHighMem(skb_frag_page(f)));
1717
			finv_buffer_remote(va, skb_frag_size(f), 0);
1718 1719 1720 1721 1722
		}

		cpa = ((phys_addr_t)pfn << PAGE_SHIFT) + f->page_offset;
		frags[n].cpa_lo = cpa;
		frags[n].cpa_hi = cpa >> 32;
E
Eric Dumazet 已提交
1723
		frags[n].length = skb_frag_size(f);
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
		frags[n].hash_for_home = hash_for_home;
		n++;
	}

	return n;
}


/*
 * This function takes "skb", consisting of a header template and a
 * payload, and hands it to LEPP, to emit as one or more segments,
 * each consisting of a possibly modified header, plus a piece of the
 * payload, via a process known as "tcp segmentation offload".
 *
 * Usually, "data" will contain the header template, of size "sh_len",
 * and "sh->frags" will contain "skb->data_len" bytes of payload, and
 * there will be "sh->gso_segs" segments.
 *
 * Sometimes, if "sendfile()" requires copying, we will be called with
 * "data" containing the header and payload, with "frags" being empty.
 *
1745 1746
 * Sometimes, for example when using NFS over TCP, a single segment can
 * span 3 fragments, which must be handled carefully in LEPP.
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
 *
 * See "emulate_large_send_offload()" for some reference code, which
 * does not handle checksumming.
 *
 * ISSUE: How do we make sure that high memory DMA does not migrate?
 */
static int tile_net_tx_tso(struct sk_buff *skb, struct net_device *dev)
{
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info = priv->cpu[my_cpu];
	struct tile_net_stats_t *stats = &info->stats;

	struct skb_shared_info *sh = skb_shinfo(skb);

	unsigned char *data = skb->data;

	/* The ip header follows the ethernet header. */
	struct iphdr *ih = ip_hdr(skb);
	unsigned int ih_len = ih->ihl * 4;

	/* Note that "nh == ih", by definition. */
	unsigned char *nh = skb_network_header(skb);
	unsigned int eh_len = nh - data;

	/* The tcp header follows the ip header. */
	struct tcphdr *th = (struct tcphdr *)(nh + ih_len);
	unsigned int th_len = th->doff * 4;

	/* The total number of header bytes. */
	/* NOTE: This may be less than skb_headlen(skb). */
	unsigned int sh_len = eh_len + ih_len + th_len;

	/* The number of payload bytes at "skb->data + sh_len". */
	/* This is non-zero for sendfile() without HIGHDMA. */
	unsigned int b_len = skb_headlen(skb) - sh_len;

	/* The total number of payload bytes. */
	unsigned int d_len = b_len + skb->data_len;

	/* The maximum payload size. */
	unsigned int p_len = sh->gso_size;

	/* The total number of segments. */
	unsigned int num_segs = sh->gso_segs;

	/* The temporary copy of the command. */
	u32 cmd_body[(LEPP_MAX_CMD_SIZE + 3) / 4];
	lepp_tso_cmd_t *cmd = (lepp_tso_cmd_t *)cmd_body;

	/* Analyze the "frags". */
	unsigned int num_frags =
		tile_net_tx_frags(cmd->frags, skb, data + sh_len, b_len);

	/* The size of the command, including frags and header. */
	size_t cmd_size = LEPP_TSO_CMD_SIZE(num_frags, sh_len);

	/* The command header. */
	lepp_tso_cmd_t cmd_init = {
		.tso = true,
		.header_size = sh_len,
		.ip_offset = eh_len,
		.tcp_offset = eh_len + ih_len,
		.payload_size = p_len,
		.num_frags = num_frags,
	};

	unsigned long irqflags;

1816
	lepp_queue_t *eq = priv->eq;
1817

1818 1819
	struct sk_buff *olds[8];
	unsigned int wanted = 8;
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
	unsigned int i, nolds = 0;

	unsigned int cmd_head, cmd_tail, cmd_next;
	unsigned int comp_tail;


	/* Paranoia. */
	BUG_ON(skb->protocol != htons(ETH_P_IP));
	BUG_ON(ih->protocol != IPPROTO_TCP);
	BUG_ON(skb->ip_summed != CHECKSUM_PARTIAL);
	BUG_ON(num_frags > LEPP_MAX_FRAGS);
	/*--BUG_ON(num_segs != (d_len + (p_len - 1)) / p_len); */
	BUG_ON(num_segs <= 1);


	/* Finish preparing the command. */

	/* Copy the command header. */
	*cmd = cmd_init;

	/* Copy the "header". */
	memcpy(&cmd->frags[num_frags], data, sh_len);


	/* Prefetch and wait, to minimize time spent holding the spinlock. */
	prefetch_L1(&eq->comp_tail);
	prefetch_L1(&eq->cmd_tail);
	mb();


	/* Enqueue the command. */

1852
	spin_lock_irqsave(&priv->eq_lock, irqflags);
1853

1854 1855
	/* Handle completions if needed to make room. */
	/* NOTE: Return NETDEV_TX_BUSY if there is still no room. */
1856 1857 1858 1859 1860 1861 1862
	if (lepp_num_free_comp_slots(eq) == 0) {
		nolds = tile_net_lepp_grab_comps(eq, olds, wanted, 0);
		if (nolds == 0) {
busy:
			spin_unlock_irqrestore(&priv->eq_lock, irqflags);
			return NETDEV_TX_BUSY;
		}
1863 1864 1865 1866 1867 1868
	}

	cmd_head = eq->cmd_head;
	cmd_tail = eq->cmd_tail;

	/* Prepare to advance, detecting full queue. */
1869
	/* NOTE: Return NETDEV_TX_BUSY if the queue is full. */
1870 1871
	cmd_next = cmd_tail + cmd_size;
	if (cmd_tail < cmd_head && cmd_next >= cmd_head)
1872
		goto busy;
1873 1874 1875
	if (cmd_next > LEPP_CMD_LIMIT) {
		cmd_next = 0;
		if (cmd_next == cmd_head)
1876
			goto busy;
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
	}

	/* Copy the command. */
	memcpy(&eq->cmds[cmd_tail], cmd, cmd_size);

	/* Advance. */
	cmd_tail = cmd_next;

	/* Record "skb" for eventual freeing. */
	comp_tail = eq->comp_tail;
	eq->comps[comp_tail] = skb;
	LEPP_QINC(comp_tail);
	eq->comp_tail = comp_tail;

	/* Flush before allowing LEPP to handle the command. */
1892
	/* ISSUE: Is this the optimal location for the flush? */
1893 1894 1895 1896
	__insn_mf();

	eq->cmd_tail = cmd_tail;

1897 1898 1899
	/* NOTE: Using "4" here is more efficient than "0" or "2", */
	/* and, strangely, more efficient than pre-checking the number */
	/* of available completions, and comparing it to 4. */
1900
	if (nolds == 0)
1901 1902 1903
		nolds = tile_net_lepp_grab_comps(eq, olds, wanted, 4);

	spin_unlock_irqrestore(&priv->eq_lock, irqflags);
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936

	/* Handle completions. */
	for (i = 0; i < nolds; i++)
		kfree_skb(olds[i]);

	/* Update stats. */
	stats->tx_packets += num_segs;
	stats->tx_bytes += (num_segs * sh_len) + d_len;

	/* Make sure the egress timer is scheduled. */
	tile_net_schedule_egress_timer(info);

	return NETDEV_TX_OK;
}


/*
 * Transmit a packet (called by the kernel via "hard_start_xmit" hook).
 */
static int tile_net_tx(struct sk_buff *skb, struct net_device *dev)
{
	struct tile_net_priv *priv = netdev_priv(dev);
	int my_cpu = smp_processor_id();
	struct tile_net_cpu *info = priv->cpu[my_cpu];
	struct tile_net_stats_t *stats = &info->stats;

	unsigned long irqflags;

	struct skb_shared_info *sh = skb_shinfo(skb);

	unsigned int len = skb->len;
	unsigned char *data = skb->data;

1937
	unsigned int csum_start = skb_checksum_start_offset(skb);
1938 1939 1940 1941 1942

	lepp_frag_t frags[LEPP_MAX_FRAGS];

	unsigned int num_frags;

1943
	lepp_queue_t *eq = priv->eq;
1944

1945 1946
	struct sk_buff *olds[8];
	unsigned int wanted = 8;
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
	unsigned int i, nolds = 0;

	unsigned int cmd_size = sizeof(lepp_cmd_t);

	unsigned int cmd_head, cmd_tail, cmd_next;
	unsigned int comp_tail;

	lepp_cmd_t cmds[LEPP_MAX_FRAGS];


	/*
	 * This is paranoia, since we think that if the link doesn't come
	 * up, telling Linux we have no carrier will keep it from trying
	 * to transmit.  If it does, though, we can't execute this routine,
	 * since data structures we depend on aren't set up yet.
	 */
	if (!info->registered)
		return NETDEV_TX_BUSY;


	/* Save the timestamp. */
	dev->trans_start = jiffies;


#ifdef TILE_NET_PARANOIA
#if CHIP_HAS_CBOX_HOME_MAP()
	if (hash_default) {
		HV_PTE pte = *virt_to_pte(current->mm, (unsigned long)data);
		if (hv_pte_get_mode(pte) != HV_PTE_MODE_CACHE_HASH_L3)
1976 1977
			panic("Non-HFH egress buffer! VA=%p Mode=%d PTE=%llx",
			      data, hv_pte_get_mode(pte), hv_pte_val(pte));
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
	}
#endif
#endif


#ifdef TILE_NET_DUMP_PACKETS
	/* ISSUE: Does not dump the "frags". */
	dump_packet(data, skb_headlen(skb), "tx");
#endif /* TILE_NET_DUMP_PACKETS */


	if (sh->gso_size != 0)
		return tile_net_tx_tso(skb, dev);


	/* Prepare the commands. */

	num_frags = tile_net_tx_frags(frags, skb, data, skb_headlen(skb));

	for (i = 0; i < num_frags; i++) {

		bool final = (i == num_frags - 1);

		lepp_cmd_t cmd = {
			.cpa_lo = frags[i].cpa_lo,
			.cpa_hi = frags[i].cpa_hi,
			.length = frags[i].length,
			.hash_for_home = frags[i].hash_for_home,
			.send_completion = final,
			.end_of_packet = final
		};

		if (i == 0 && skb->ip_summed == CHECKSUM_PARTIAL) {
			cmd.compute_checksum = 1;
			cmd.checksum_data.bits.start_byte = csum_start;
			cmd.checksum_data.bits.count = len - csum_start;
			cmd.checksum_data.bits.destination_byte =
				csum_start + skb->csum_offset;
		}

		cmds[i] = cmd;
	}


	/* Prefetch and wait, to minimize time spent holding the spinlock. */
	prefetch_L1(&eq->comp_tail);
	prefetch_L1(&eq->cmd_tail);
	mb();


	/* Enqueue the commands. */

2030
	spin_lock_irqsave(&priv->eq_lock, irqflags);
2031

2032 2033
	/* Handle completions if needed to make room. */
	/* NOTE: Return NETDEV_TX_BUSY if there is still no room. */
2034 2035 2036 2037 2038 2039 2040
	if (lepp_num_free_comp_slots(eq) == 0) {
		nolds = tile_net_lepp_grab_comps(eq, olds, wanted, 0);
		if (nolds == 0) {
busy:
			spin_unlock_irqrestore(&priv->eq_lock, irqflags);
			return NETDEV_TX_BUSY;
		}
2041 2042 2043 2044 2045 2046
	}

	cmd_head = eq->cmd_head;
	cmd_tail = eq->cmd_tail;

	/* Copy the commands, or fail. */
2047
	/* NOTE: Return NETDEV_TX_BUSY if the queue is full. */
2048 2049 2050 2051 2052
	for (i = 0; i < num_frags; i++) {

		/* Prepare to advance, detecting full queue. */
		cmd_next = cmd_tail + cmd_size;
		if (cmd_tail < cmd_head && cmd_next >= cmd_head)
2053
			goto busy;
2054 2055 2056
		if (cmd_next > LEPP_CMD_LIMIT) {
			cmd_next = 0;
			if (cmd_next == cmd_head)
2057
				goto busy;
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
		}

		/* Copy the command. */
		*(lepp_cmd_t *)&eq->cmds[cmd_tail] = cmds[i];

		/* Advance. */
		cmd_tail = cmd_next;
	}

	/* Record "skb" for eventual freeing. */
	comp_tail = eq->comp_tail;
	eq->comps[comp_tail] = skb;
	LEPP_QINC(comp_tail);
	eq->comp_tail = comp_tail;

	/* Flush before allowing LEPP to handle the command. */
2074
	/* ISSUE: Is this the optimal location for the flush? */
2075 2076 2077 2078
	__insn_mf();

	eq->cmd_tail = cmd_tail;

2079 2080 2081
	/* NOTE: Using "4" here is more efficient than "0" or "2", */
	/* and, strangely, more efficient than pre-checking the number */
	/* of available completions, and comparing it to 4. */
2082
	if (nolds == 0)
2083 2084 2085
		nolds = tile_net_lepp_grab_comps(eq, olds, wanted, 4);

	spin_unlock_irqrestore(&priv->eq_lock, irqflags);
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193

	/* Handle completions. */
	for (i = 0; i < nolds; i++)
		kfree_skb(olds[i]);

	/* HACK: Track "expanded" size for short packets (e.g. 42 < 60). */
	stats->tx_packets++;
	stats->tx_bytes += ((len >= ETH_ZLEN) ? len : ETH_ZLEN);

	/* Make sure the egress timer is scheduled. */
	tile_net_schedule_egress_timer(info);

	return NETDEV_TX_OK;
}


/*
 * Deal with a transmit timeout.
 */
static void tile_net_tx_timeout(struct net_device *dev)
{
	PDEBUG("tile_net_tx_timeout()\n");
	PDEBUG("Transmit timeout at %ld, latency %ld\n", jiffies,
	       jiffies - dev->trans_start);

	/* XXX: ISSUE: This doesn't seem useful for us. */
	netif_wake_queue(dev);
}


/*
 * Ioctl commands.
 */
static int tile_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
	return -EOPNOTSUPP;
}


/*
 * Get System Network Statistics.
 *
 * Returns the address of the device statistics structure.
 */
static struct net_device_stats *tile_net_get_stats(struct net_device *dev)
{
	struct tile_net_priv *priv = netdev_priv(dev);
	u32 rx_packets = 0;
	u32 tx_packets = 0;
	u32 rx_bytes = 0;
	u32 tx_bytes = 0;
	int i;

	for_each_online_cpu(i) {
		if (priv->cpu[i]) {
			rx_packets += priv->cpu[i]->stats.rx_packets;
			rx_bytes += priv->cpu[i]->stats.rx_bytes;
			tx_packets += priv->cpu[i]->stats.tx_packets;
			tx_bytes += priv->cpu[i]->stats.tx_bytes;
		}
	}

	priv->stats.rx_packets = rx_packets;
	priv->stats.rx_bytes = rx_bytes;
	priv->stats.tx_packets = tx_packets;
	priv->stats.tx_bytes = tx_bytes;

	return &priv->stats;
}


/*
 * Change the "mtu".
 *
 * The "change_mtu" method is usually not needed.
 * If you need it, it must be like this.
 */
static int tile_net_change_mtu(struct net_device *dev, int new_mtu)
{
	PDEBUG("tile_net_change_mtu()\n");

	/* Check ranges. */
	if ((new_mtu < 68) || (new_mtu > 1500))
		return -EINVAL;

	/* Accept the value. */
	dev->mtu = new_mtu;

	return 0;
}


/*
 * Change the Ethernet Address of the NIC.
 *
 * The hypervisor driver does not support changing MAC address.  However,
 * the IPP does not do anything with the MAC address, so the address which
 * gets used on outgoing packets, and which is accepted on incoming packets,
 * is completely up to the NetIO program or kernel driver which is actually
 * handling them.
 *
 * Returns 0 on success, negative on failure.
 */
static int tile_net_set_mac_address(struct net_device *dev, void *p)
{
	struct sockaddr *addr = p;

	if (!is_valid_ether_addr(addr->sa_data))
2194
		return -EADDRNOTAVAIL;
2195 2196 2197

	/* ISSUE: Note that "dev_addr" is now a pointer. */
	memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
2198
	dev->addr_assign_type &= ~NET_ADDR_RANDOM;
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262

	return 0;
}


/*
 * Obtain the MAC address from the hypervisor.
 * This must be done before opening the device.
 */
static int tile_net_get_mac(struct net_device *dev)
{
	struct tile_net_priv *priv = netdev_priv(dev);

	char hv_dev_name[32];
	int len;

	__netio_getset_offset_t offset = { .word = NETIO_IPP_PARAM_OFF };

	int ret;

	/* For example, "xgbe0". */
	strcpy(hv_dev_name, dev->name);
	len = strlen(hv_dev_name);

	/* For example, "xgbe/0". */
	hv_dev_name[len] = hv_dev_name[len - 1];
	hv_dev_name[len - 1] = '/';
	len++;

	/* For example, "xgbe/0/native_hash". */
	strcpy(hv_dev_name + len, hash_default ? "/native_hash" : "/native");

	/* Get the hypervisor handle for this device. */
	priv->hv_devhdl = hv_dev_open((HV_VirtAddr)hv_dev_name, 0);
	PDEBUG("hv_dev_open(%s) returned %d %p\n",
	       hv_dev_name, priv->hv_devhdl, &priv->hv_devhdl);
	if (priv->hv_devhdl < 0) {
		if (priv->hv_devhdl == HV_ENODEV)
			printk(KERN_DEBUG "Ignoring unconfigured device %s\n",
				 hv_dev_name);
		else
			printk(KERN_DEBUG "hv_dev_open(%s) returned %d\n",
				 hv_dev_name, priv->hv_devhdl);
		return -1;
	}

	/*
	 * Read the hardware address from the hypervisor.
	 * ISSUE: Note that "dev_addr" is now a pointer.
	 */
	offset.bits.class = NETIO_PARAM;
	offset.bits.addr = NETIO_PARAM_MAC;
	ret = hv_dev_pread(priv->hv_devhdl, 0,
			   (HV_VirtAddr)dev->dev_addr, dev->addr_len,
			   offset.word);
	PDEBUG("hv_dev_pread(NETIO_PARAM_MAC) returned %d\n", ret);
	if (ret <= 0) {
		printk(KERN_DEBUG "hv_dev_pread(NETIO_PARAM_MAC) %s failed\n",
		       dev->name);
		/*
		 * Since the device is configured by the hypervisor but we
		 * can't get its MAC address, we are most likely running
		 * the simulator, so let's generate a random MAC address.
		 */
2263
		eth_hw_addr_random(dev);
2264 2265 2266 2267 2268
	}

	return 0;
}

2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285

#ifdef CONFIG_NET_POLL_CONTROLLER
/*
 * Polling 'interrupt' - used by things like netconsole to send skbs
 * without having to re-enable interrupts. It's not called while
 * the interrupt routine is executing.
 */
static void tile_net_netpoll(struct net_device *dev)
{
	struct tile_net_priv *priv = netdev_priv(dev);
	disable_percpu_irq(priv->intr_id);
	tile_net_handle_ingress_interrupt(priv->intr_id, dev);
	enable_percpu_irq(priv->intr_id, 0);
}
#endif


2286
static const struct net_device_ops tile_net_ops = {
2287 2288 2289 2290 2291 2292 2293
	.ndo_open = tile_net_open,
	.ndo_stop = tile_net_stop,
	.ndo_start_xmit = tile_net_tx,
	.ndo_do_ioctl = tile_net_ioctl,
	.ndo_get_stats = tile_net_get_stats,
	.ndo_change_mtu = tile_net_change_mtu,
	.ndo_tx_timeout = tile_net_tx_timeout,
2294 2295 2296 2297
	.ndo_set_mac_address = tile_net_set_mac_address,
#ifdef CONFIG_NET_POLL_CONTROLLER
	.ndo_poll_controller = tile_net_netpoll,
#endif
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
};


/*
 * The setup function.
 *
 * This uses ether_setup() to assign various fields in dev, including
 * setting IFF_BROADCAST and IFF_MULTICAST, then sets some extra fields.
 */
static void tile_net_setup(struct net_device *dev)
{
	PDEBUG("tile_net_setup()\n");

	ether_setup(dev);

	dev->netdev_ops = &tile_net_ops;

	dev->watchdog_timeo = TILE_NET_TIMEOUT;

	/* We want lockless xmit. */
	dev->features |= NETIF_F_LLTX;

	/* We support hardware tx checksums. */
	dev->features |= NETIF_F_HW_CSUM;

	/* We support scatter/gather. */
	dev->features |= NETIF_F_SG;

	/* We support TSO. */
	dev->features |= NETIF_F_TSO;

#ifdef TILE_NET_GSO
	/* We support GSO. */
	dev->features |= NETIF_F_GSO;
#endif

	if (hash_default)
		dev->features |= NETIF_F_HIGHDMA;

	/* ISSUE: We should support NETIF_F_UFO. */

	dev->tx_queue_len = TILE_NET_TX_QUEUE_LEN;

	dev->mtu = TILE_NET_MTU;
}


/*
 * Allocate the device structure, register the device, and obtain the
 * MAC address from the hypervisor.
 */
static struct net_device *tile_net_dev_init(const char *name)
{
	int ret;
	struct net_device *dev;
	struct tile_net_priv *priv;

	/*
	 * Allocate the device structure.  This allocates "priv", calls
	 * tile_net_setup(), and saves "name".  Normally, "name" is a
	 * template, instantiated by register_netdev(), but not for us.
	 */
	dev = alloc_netdev(sizeof(*priv), name, tile_net_setup);
	if (!dev) {
		pr_err("alloc_netdev(%s) failed\n", name);
		return NULL;
	}

	priv = netdev_priv(dev);

	/* Initialize "priv". */

	memset(priv, 0, sizeof(*priv));

	/* Save "dev" for "tile_net_open_retry()". */
	priv->dev = dev;

	INIT_DELAYED_WORK(&priv->retry_work, tile_net_open_retry);

2377
	spin_lock_init(&priv->eq_lock);
2378

2379 2380 2381
	/* Allocate "eq". */
	priv->eq_pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, EQ_ORDER);
	if (!priv->eq_pages) {
2382 2383 2384
		free_netdev(dev);
		return NULL;
	}
2385
	priv->eq = page_address(priv->eq_pages);
2386 2387 2388 2389 2390

	/* Register the network device. */
	ret = register_netdev(dev);
	if (ret) {
		pr_err("register_netdev %s failed %d\n", dev->name, ret);
2391
		__free_pages(priv->eq_pages, EQ_ORDER);
2392 2393 2394 2395 2396 2397 2398 2399
		free_netdev(dev);
		return NULL;
	}

	/* Get the MAC address. */
	ret = tile_net_get_mac(dev);
	if (ret < 0) {
		unregister_netdev(dev);
2400
		__free_pages(priv->eq_pages, EQ_ORDER);
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
		free_netdev(dev);
		return NULL;
	}

	return dev;
}


/*
 * Module cleanup.
2411 2412 2413
 *
 * FIXME: If compiled as a module, this module cannot be "unloaded",
 * because the "ingress interrupt handler" is registered permanently.
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
 */
static void tile_net_cleanup(void)
{
	int i;

	for (i = 0; i < TILE_NET_DEVS; i++) {
		if (tile_net_devs[i]) {
			struct net_device *dev = tile_net_devs[i];
			struct tile_net_priv *priv = netdev_priv(dev);
			unregister_netdev(dev);
2424
			finv_buffer_remote(priv->eq, EQ_SIZE, 0);
2425
			__free_pages(priv->eq_pages, EQ_ORDER);
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
			free_netdev(dev);
		}
	}
}


/*
 * Module initialization.
 */
static int tile_net_init_module(void)
{
2437
	pr_info("Tilera Network Driver\n");
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447

	tile_net_devs[0] = tile_net_dev_init("xgbe0");
	tile_net_devs[1] = tile_net_dev_init("xgbe1");
	tile_net_devs[2] = tile_net_dev_init("gbe0");
	tile_net_devs[3] = tile_net_dev_init("gbe1");

	return 0;
}


2448 2449 2450 2451
module_init(tile_net_init_module);
module_exit(tile_net_cleanup);


2452
#ifndef MODULE
2453

2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489
/*
 * The "network_cpus" boot argument specifies the cpus that are dedicated
 * to handle ingress packets.
 *
 * The parameter should be in the form "network_cpus=m-n[,x-y]", where
 * m, n, x, y are integer numbers that represent the cpus that can be
 * neither a dedicated cpu nor a dataplane cpu.
 */
static int __init network_cpus_setup(char *str)
{
	int rc = cpulist_parse_crop(str, &network_cpus_map);
	if (rc != 0) {
		pr_warning("network_cpus=%s: malformed cpu list\n",
		       str);
	} else {

		/* Remove dedicated cpus. */
		cpumask_and(&network_cpus_map, &network_cpus_map,
			    cpu_possible_mask);


		if (cpumask_empty(&network_cpus_map)) {
			pr_warning("Ignoring network_cpus='%s'.\n",
			       str);
		} else {
			char buf[1024];
			cpulist_scnprintf(buf, sizeof(buf), &network_cpus_map);
			pr_info("Linux network CPUs: %s\n", buf);
			network_cpus_used = true;
		}
	}

	return 0;
}
__setup("network_cpus=", network_cpus_setup);

2490
#endif