aboutsummaryrefslogtreecommitdiffstats
path: root/fs/ubifs/commit.c
blob: 26b69b2d4a452488405f7ccbc2a4f179c1961bbf (plain) (blame)
1
2
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
72
73
74
75
76
77
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
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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
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
624
625
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
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
734
/*
 * This file is part of UBIFS.
 *
 * Copyright (C) 2006-2008 Nokia Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published by
 * the Free Software Foundation.
 *
 * 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.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * Authors: Adrian Hunter
 *          Artem Bityutskiy (Битюцкий Артём)
 */

/*
 * This file implements functions that manage the running of the commit process.
 * Each affected module has its own functions to accomplish their part in the
 * commit and those functions are called here.
 *
 * The commit is the process whereby all updates to the index and LEB properties
 * are written out together and the journal becomes empty. This keeps the
 * file system consistent - at all times the state can be recreated by reading
 * the index and LEB properties and then replaying the journal.
 *
 * The commit is split into two parts named "commit start" and "commit end".
 * During commit start, the commit process has exclusive access to the journal
 * by holding the commit semaphore down for writing. As few I/O operations as
 * possible are performed during commit start, instead the nodes that are to be
 * written are merely identified. During commit end, the commit semaphore is no
 * longer held and the journal is again in operation, allowing users to continue
 * to use the file system while the bulk of the commit I/O is performed. The
 * purpose of this two-step approach is to prevent the commit from causing any
 * latency blips. Note that in any case, the commit does not prevent lookups
 * (as permitted by the TNC mutex), or access to VFS data structures e.g. page
 * cache.
 */

#include <linux/freezer.h>
#include <linux/kthread.h>
#include <linux/slab.h>
#include "ubifs.h"

/*
 * nothing_to_commit - check if there is nothing to commit.
 * @c: UBIFS file-system description object
 *
 * This is a helper function which checks if there is anything to commit. It is
 * used as an optimization to avoid starting the commit if it is not really
 * necessary. Indeed, the commit operation always assumes flash I/O (e.g.,
 * writing the commit start node to the log), and it is better to avoid doing
 * this unnecessarily. E.g., 'ubifs_sync_fs()' runs the commit, but if there is
 * nothing to commit, it is more optimal to avoid any flash I/O.
 *
 * This function has to be called with @c->commit_sem locked for writing -
 * this function does not take LPT/TNC locks because the @c->commit_sem
 * guarantees that we have exclusive access to the TNC and LPT data structures.
 *
 * This function returns %1 if there is nothing to commit and %0 otherwise.
 */
static int nothing_to_commit(struct ubifs_info *c)
{
	/*
	 * During mounting or remounting from R/O mode to R/W mode we may
	 * commit for various recovery-related reasons.
	 */
	if (c->mounting || c->remounting_rw)
		return 0;

	/*
	 * If the root TNC node is dirty, we definitely have something to
	 * commit.
	 */
	if (c->zroot.znode && ubifs_zn_dirty(c->zroot.znode))
		return 0;

	/*
	 * Even though the TNC is clean, the LPT tree may have dirty nodes. For
	 * example, this may happen if the budgeting subsystem invoked GC to
	 * make some free space, and the GC found an LEB with only dirty and
	 * free space. In this case GC would just change the lprops of this
	 * LEB (by turning all space into free space) and unmap it.
	 */
	if (c->nroot && test_bit(DIRTY_CNODE, &c->nroot->flags))
		return 0;

	ubifs_assert(atomic_long_read(&c->dirty_zn_cnt) == 0);
	ubifs_assert(c->dirty_pn_cnt == 0);
	ubifs_assert(c->dirty_nn_cnt == 0);

	return 1;
}

/**
 * do_commit - commit the journal.
 * @c: UBIFS file-system description object
 *
 * This function implements UBIFS commit. It has to be called with commit lock
 * locked. Returns zero in case of success and a negative error code in case of
 * failure.
 */
static int do_commit(struct ubifs_info *c)
{
	int err, new_ltail_lnum, old_ltail_lnum, i;
	struct ubifs_zbranch zroot;
	struct ubifs_lp_stats lst;

	dbg_cmt("start");
	ubifs_assert(!c->ro_media && !c->ro_mount);

	if (c->ro_error) {
		err = -EROFS;
		goto out_up;
	}

	if (nothing_to_commit(c)) {
		up_write(&c->commit_sem);
		err = 0;
		goto out_cancel;
	}

	/* Sync all write buffers (necessary for recovery) */
	for (i = 0; i < c->jhead_cnt; i++) {
		err = ubifs_wbuf_sync(&c->jheads[i].wbuf);
		if (err)
			goto out_up;
	}

	c->cmt_no += 1;
	err = ubifs_gc_start_commit(c);
	if (err)
		goto out_up;
	err = dbg_check_lprops(c);
	if (err)
		goto out_up;
	err = ubifs_log_start_commit(c, &new_ltail_lnum);
	if (err)
		goto out_up;
	err = ubifs_tnc_start_commit(c, &zroot);
	if (err)
		goto out_up;
	err = ubifs_lpt_start_commit(c);
	if (err)
		goto out_up;
	err = ubifs_orphan_start_commit(c);
	if (err)
		goto out_up;

	ubifs_get_lp_stats(c, &lst);

	up_write(&c->commit_sem);

	err = ubifs_tnc_end_commit(c);
	if (err)
		goto out;
	err = ubifs_lpt_end_commit(c);
	if (err)
		goto out;
	err = ubifs_orphan_end_commit(c);
	if (err)
		goto out;
	err = dbg_check_old_index(c, &zroot);
	if (err)
		goto out;

	c->mst_node->cmt_no      = cpu_to_le64(c->cmt_no);
	c->mst_node->log_lnum    = cpu_to_le32(new_ltail_lnum);
	c->mst_node->root_lnum   = cpu_to_le32(zroot.lnum);
	c->mst_node->root_offs   = cpu_to_le32(zroot.offs);
	c->mst_node->root_len    = cpu_to_le32(zroot.len);
	c->mst_node->ihead_lnum  = cpu_to_le32(c->ihead_lnum);
	c->mst_node->ihead_offs  = cpu_to_le32(c->ihead_offs);
	c->mst_node->index_size  = cpu_to_le64(c->bi.old_idx_sz);
	c->mst_node->lpt_lnum    = cpu_to_le32(c->lpt_lnum);
	c->mst_node->lpt_offs    = cpu_to_le32(c->lpt_offs);
	c->mst_node->nhead_lnum  = cpu_to_le32(c->nhead_lnum);
	c->mst_node->nhead_offs  = cpu_to_le32(c->nhead_offs);
	c->mst_node->ltab_lnum   = cpu_to_le32(c->ltab_lnum);
	c->mst_node->ltab_offs   = cpu_to_le32(c->ltab_offs);
	c->mst_node->lsave_lnum  = cpu_to_le32(c->lsave_lnum);
	c->mst_node->lsave_offs  = cpu_to_le32(c->lsave_offs);
	c->mst_node->lscan_lnum  = cpu_to_le32(c->lscan_lnum);
	c->mst_node->empty_lebs  = cpu_to_le32(lst.empty_lebs);
	c->mst_node->idx_lebs    = cpu_to_le32(lst.idx_lebs);
	c->mst_node->total_free  = cpu_to_le64(lst.total_free);
	c->mst_node->total_dirty = cpu_to_le64(lst.total_dirty);
	c->mst_node->total_used  = cpu_to_le64(lst.total_used);
	c->mst_node->total_dead  = cpu_to_le64(lst.total_dead);
	c->mst_node->total_dark  = cpu_to_le64(lst.total_dark);
	if (c->no_orphs)
		c->mst_node->flags |= cpu_to_le32(UBIFS_MST_NO_ORPHS);
	else
		c->mst_node->flags &= ~cpu_to_le32(UBIFS_MST_NO_ORPHS);

	old_ltail_lnum = c->ltail_lnum;
	err = ubifs_log_end_commit(c, new_ltail_lnum);
	if (err)
		goto out;

	err = ubifs_log_post_commit(c, old_ltail_lnum);
	if (err)
		goto out;
	err = ubifs_gc_end_commit(c);
	if (err)
		goto out;
	err = ubifs_lpt_post_commit(c);
	if (err)
		goto out;

out_cancel:
	spin_lock(&c->cs_lock);
	c->cmt_state = COMMIT_RESTING;
	wake_up(&c->cmt_wq);
	dbg_cmt("commit end");
	spin_unlock(&c->cs_lock);
	return 0;

out_up:
	up_write(&c->commit_sem);
out:
	ubifs_err("commit failed, error %d", err);
	spin_lock(&c->cs_lock);
	c->cmt_state = COMMIT_BROKEN;
	wake_up(&c->cmt_wq);
	spin_unlock(&c->cs_lock);
	ubifs_ro_mode(c, err);
	return err;
}

/**
 * run_bg_commit - run background commit if it is needed.
 * @c: UBIFS file-system description object
 *
 * This function runs background commit if it is needed. Returns zero in case
 * of success and a negative error code in case of failure.
 */
static int run_bg_commit(struct ubifs_info *c)
{
	spin_lock(&c->cs_lock);
	/*
	 * Run background commit only if background commit was requested or if
	 * commit is required.
	 */
	if (c->cmt_state != COMMIT_BACKGROUND &&
	    c->cmt_state != COMMIT_REQUIRED)
		goto out;
	spin_unlock(&c->cs_lock);

	down_write(&c->commit_sem);
	spin_lock(&c->cs_lock);
	if (c->cmt_state == COMMIT_REQUIRED)
		c->cmt_state = COMMIT_RUNNING_REQUIRED;
	else if (c->cmt_state == COMMIT_BACKGROUND)
		c->cmt_state = COMMIT_RUNNING_BACKGROUND;
	else
		goto out_cmt_unlock;
	spin_unlock(&c->cs_lock);

	return do_commit(c);

out_cmt_unlock:
	up_write(&c->commit_sem);
out:
	spin_unlock(&c->cs_lock);
	return 0;
}

/**
 * ubifs_bg_thread - UBIFS background thread function.
 * @info: points to the file-system description object
 *
 * This function implements various file-system background activities:
 * o when a write-buffer timer expires it synchronizes the appropriate
 *   write-buffer;
 * o when the journal is about to be full, it starts in-advance commit.
 *
 * Note, other stuff like background garbage collection may be added here in
 * future.
 */
int ubifs_bg_thread(void *info)
{
	int err;
	struct ubifs_info *c = info;

	ubifs_msg("background thread \"%s\" started, PID %d",
		  c->bgt_name, current->pid);
	set_freezable();

	while (1) {
		if (kthread_should_stop())
			break;

		if (try_to_freeze())
			continue;

		set_current_state(TASK_INTERRUPTIBLE);
		/* Check if there is something to do */
		if (!c->need_bgt) {
			/*
			 * Nothing prevents us from going sleep now and
			 * be never woken up and block the task which
			 * could wait in 'kthread_stop()' forever.
			 */
			if (kthread_should_stop())
				break;
			schedule();
			continue;
		} else
			__set_current_state(TASK_RUNNING);

		c->need_bgt = 0;
		err = ubifs_bg_wbufs_sync(c);
		if (err)
			ubifs_ro_mode(c, err);

		run_bg_commit(c);
		cond_resched();
	}

	ubifs_msg("background thread \"%s\" stops", c->bgt_name);
	return 0;
}

/**
 * ubifs_commit_required - set commit state to "required".
 * @c: UBIFS file-system description object
 *
 * This function is called if a commit is required but cannot be done from the
 * calling function, so it is just flagged instead.
 */
void ubifs_commit_required(struct ubifs_info *c)
{
	spin_lock(&c->cs_lock);
	switch (c->cmt_state) {
	case COMMIT_RESTING:
	case COMMIT_BACKGROUND:
		dbg_cmt("old: %s, new: %s", dbg_cstate(c->cmt_state),
			dbg_cstate(COMMIT_REQUIRED));
		c->cmt_state = COMMIT_REQUIRED;
		break;
	case COMMIT_RUNNING_BACKGROUND:
		dbg_cmt("old: %s, new: %s", dbg_cstate(c->cmt_state),
			dbg_cstate(COMMIT_RUNNING_REQUIRED));
		c->cmt_state = COMMIT_RUNNING_REQUIRED;
		break;
	case COMMIT_REQUIRED:
	case COMMIT_RUNNING_REQUIRED:
	case COMMIT_BROKEN:
		break;
	}
	spin_unlock(&c->cs_lock);
}

/**
 * ubifs_request_bg_commit - notify the background thread to do a commit.
 * @c: UBIFS file-system description object
 *
 * This function is called if the journal is full enough to make a commit
 * worthwhile, so background thread is kicked to start it.
 */
void ubifs_request_bg_commit(struct ubifs_info *c)
{
	spin_lock(&c->cs_lock);
	if (c->cmt_state == COMMIT_RESTING) {
		dbg_cmt("old: %s, new: %s", dbg_cstate(c->cmt_state),
			dbg_cstate(COMMIT_BACKGROUND));
		c->cmt_state = COMMIT_BACKGROUND;
		spin_unlock(&c->cs_lock);
		ubifs_wake_up_bgt(c);
	} else
		spin_unlock(&c->cs_lock);
}

/**
 * wait_for_commit - wait for commit.
 * @c: UBIFS file-system description object
 *
 * This function sleeps until the commit operation is no longer running.
 */
static int wait_for_commit(struct ubifs_info *c)
{
	dbg_cmt("pid %d goes sleep", current->pid);

	/*
	 * The following sleeps if the condition is false, and will be woken
	 * when the commit ends. It is possible, although very unlikely, that we
	 * will wake up and see the subsequent commit running, rather than the
	 * one we were waiting for, and go back to sleep.  However, we will be
	 * woken again, so there is no danger of sleeping forever.
	 */
	wait_event(c->cmt_wq, c->cmt_state != COMMIT_RUNNING_BACKGROUND &&
			      c->cmt_state != COMMIT_RUNNING_REQUIRED);
	dbg_cmt("commit finished, pid %d woke up", current->pid);
	return 0;
}

/**
 * ubifs_run_commit - run or wait for commit.
 * @c: UBIFS file-system description object
 *
 * This function runs commit and returns zero in case of success and a negative
 * error code in case of failure.
 */
int ubifs_run_commit(struct ubifs_info *c)
{
	int err = 0;

	spin_lock(&c->cs_lock);
	if (c->cmt_state == COMMIT_BROKEN) {
		err = -EROFS;
		goto out;
	}

	if (c->cmt_state == COMMIT_RUNNING_BACKGROUND)
		/*
		 * We set the commit state to 'running required' to indicate
		 * that we want it to complete as quickly as possible.
		 */
		c->cmt_state = COMMIT_RUNNING_REQUIRED;

	if (c->cmt_state == COMMIT_RUNNING_REQUIRED) {
		spin_unlock(&c->cs_lock);
		return wait_for_commit(c);
	}
	spin_unlock(&c->cs_lock);

	/* Ok, the commit is indeed needed */

	down_write(&c->commit_sem);
	spin_lock(&c->cs_lock);
	/*
	 * Since we unlocked 'c->cs_lock', the state may have changed, so
	 * re-check it.
	 */
	if (c->cmt_state == COMMIT_BROKEN) {
		err = -EROFS;
		goto out_cmt_unlock;
	}

	if (c->cmt_state == COMMIT_RUNNING_BACKGROUND)
		c->cmt_state = COMMIT_RUNNING_REQUIRED;

	if (c->cmt_state == COMMIT_RUNNING_REQUIRED) {
		up_write(&c->commit_sem);
		spin_unlock(&c->cs_lock);
		return wait_for_commit(c);
	}
	c->cmt_state = COMMIT_RUNNING_REQUIRED;
	spin_unlock(&c->cs_lock);

	err = do_commit(c);
	return err;

out_cmt_unlock:
	up_write(&c->commit_sem);
out:
	spin_unlock(&c->cs_lock);
	return err;
}

/**
 * ubifs_gc_should_commit - determine if it is time for GC to run commit.
 * @c: UBIFS file-system description object
 *
 * This function is called by garbage collection to determine if commit should
 * be run. If commit state is @COMMIT_BACKGROUND, which means that the journal
 * is full enough to start commit, this function returns true. It is not
 * absolutely necessary to commit yet, but it feels like this should be better
 * then to keep doing GC. This function returns %1 if GC has to initiate commit
 * and %0 if not.
 */
int ubifs_gc_should_commit(struct ubifs_info *c)
{
	int ret = 0;

	spin_lock(&c->cs_lock);
	if (c->cmt_state == COMMIT_BACKGROUND) {
		dbg_cmt("commit required now");
		c->cmt_state = COMMIT_REQUIRED;
	} else
		dbg_cmt("commit not requested");
	if (c->cmt_state == COMMIT_REQUIRED)
		ret = 1;
	spin_unlock(&c->cs_lock);
	return ret;
}

/*
 * Everything below is related to debugging.
 */

/**
 * struct idx_node - hold index nodes during index tree traversal.
 * @list: list
 * @iip: index in parent (slot number of this indexing node in the parent
 *       indexing node)
 * @upper_key: all keys in this indexing node have to be less or equivalent to
 *             this key
 * @idx: index node (8-byte aligned because all node structures must be 8-byte
 *       aligned)
 */
struct idx_node {
	struct list_head list;
	int iip;
	union ubifs_key upper_key;
	struct ubifs_idx_node idx __aligned(8);
};

/**
 * dbg_old_index_check_init - get information for the next old index check.
 * @c: UBIFS file-system description object
 * @zroot: root of the index
 *
 * This function records information about the index that will be needed for the
 * next old index check i.e. 'dbg_check_old_index()'.
 *
 * This function returns %0 on success and a negative error code on failure.
 */
int dbg_old_index_check_init(struct ubifs_info *c, struct ubifs_zbranch *zroot)
{
	struct ubifs_idx_node *idx;
	int lnum, offs, len, err = 0;
	struct ubifs_debug_info *d = c->dbg;

	d->old_zroot = *zroot;
	lnum = d->old_zroot.lnum;
	offs = d->old_zroot.offs;
	len = d->old_zroot.len;

	idx = kmalloc(c->max_idx_node_sz, GFP_NOFS);
	if (!idx)
		return -ENOMEM;

	err = ubifs_read_node(c, idx, UBIFS_IDX_NODE, len, lnum, offs);
	if (err)
		goto out;

	d->old_zroot_level = le16_to_cpu(idx->level);
	d->old_zroot_sqnum = le64_to_cpu(idx->ch.sqnum);
out:
	kfree(idx);
	return err;
}

/**
 * dbg_check_old_index - check the old copy of the index.
 * @c: UBIFS file-system description object
 * @zroot: root of the new index
 *
 * In order to be able to recover from an unclean unmount, a complete copy of
 * the index must exist on flash. This is the "old" index. The commit process
 * must write the "new" index to flash without overwriting or destroying any
 * part of the old index. This function is run at commit end in order to check
 * that the old index does indeed exist completely intact.
 *
 * This function returns %0 on success and a negative error code on failure.
 */
int dbg_check_old_index(struct ubifs_info *c, struct ubifs_zbranch *zroot)
{
	int lnum, offs, len, err = 0, uninitialized_var(last_level), child_cnt;
	int first = 1, iip;
	struct ubifs_debug_info *d = c->dbg;
	union ubifs_key uninitialized_var(lower_key), upper_key, l_key, u_key;
	unsigned long long uninitialized_var(last_sqnum);
	struct ubifs_idx_node *idx;
	struct list_head list;
	struct idx_node *i;
	size_t sz;

	if (!dbg_is_chk_index(c))
		return 0;

	INIT_LIST_HEAD(&list);

	sz = sizeof(struct idx_node) + ubifs_idx_node_sz(c, c->fanout) -
	     UBIFS_IDX_NODE_SZ;

	/* Start at the old zroot */
	lnum = d->old_zroot.lnum;
	offs = d->old_zroot.offs;
	len = d->old_zroot.len;
	iip = 0;

	/*
	 * Traverse the index tree preorder depth-first i.e. do a node and then
	 * its subtrees from left to right.
	 */
	while (1) {
		struct ubifs_branch *br;

		/* Get the next index node */
		i = kmalloc(sz, GFP_NOFS);
		if (!i) {
			err = -ENOMEM;
			goto out_free;
		}
		i->iip = iip;
		/* Keep the index nodes on our path in a linked list */
		list_add_tail(&i->list, &list);
		/* Read the index node */
		idx = &i->idx;
		err = ubifs_read_node(c, idx, UBIFS_IDX_NODE, len, lnum, offs);
		if (err)
			goto out_free;
		/* Validate index node */
		child_cnt = le16_to_cpu(idx->child_cnt);
		if (child_cnt < 1 || child_cnt > c->fanout) {
			err = 1;
			goto out_dump;
		}
		if (first) {
			first = 0;
			/* Check root level and sqnum */
			if (le16_to_cpu(idx->level) != d->old_zroot_level) {
				err = 2;
				goto out_dump;
			}
			if (le64_to_cpu(idx->ch.sqnum) != d->old_zroot_sqnum) {
				err = 3;
				goto out_dump;
			}
			/* Set last values as though root had a parent */
			last_level = le16_to_cpu(idx->level) + 1;
			last_sqnum = le64_to_cpu(idx->ch.sqnum) + 1;
			key_read(c, ubifs_idx_key(c, idx), &lower_key);
			highest_ino_key(c, &upper_key, INUM_WATERMARK);
		}
		key_copy(c, &upper_key, &i->upper_key);
		if (le16_to_cpu(idx->level) != last_level - 1) {
			err = 3;
			goto out_dump;
		}
		/*
		 * The index is always written bottom up hence a child's sqnum
		 * is always less than the parents.
		 */
		if (le64_to_cpu(idx->ch.sqnum) >= last_sqnum) {
			err = 4;
			goto out_dump;
		}
		/* Check key range */
		key_read(c, ubifs_idx_key(c, idx), &l_key);
		br = ubifs_idx_branch(c, idx, child_cnt - 1);
		key_read(c, &br->key, &u_key);
		if (keys_cmp(c, &lower_key, &l_key) > 0) {
			err = 5;
			goto out_dump;
		}
		if (keys_cmp(c, &upper_key, &u_key) < 0) {
			err = 6;
			goto out_dump;
		}
		if (keys_cmp(c, &upper_key, &u_key) == 0)
			if (!is_hash_key(c, &u_key)) {
				err = 7;
				goto out_dump;
			}
		/* Go to next index node */
		if (le16_to_cpu(idx->level) == 0) {
			/* At the bottom, so go up until can go right */
			while (1) {
				/* Drop the bottom of the list */
				list_del(&i->list);
				kfree(i);
				/* No more list means we are done */
				if (list_empty(&list))
					goto out;
				/* Look at the new bottom */
				i = list_entry(list.prev, struct idx_node,
					       list);
				idx = &i->idx;
				/* Can we go right */
				if (iip + 1 < le16_to_cpu(idx->child_cnt)) {
					iip = iip + 1;
					break;
				} else
					/* Nope, so go up again */
					iip = i->iip;
			}
		} else
			/* Go down left */
			iip = 0;
		/*
		 * We have the parent in 'idx' and now we set up for reading the
		 * child pointed to by slot 'iip'.
		 */
		last_level = le16_to_cpu(idx->level);
		last_sqnum = le64_to_cpu(idx->ch.sqnum);
		br = ubifs_idx_branch(c, idx, iip);
		lnum = le32_to_cpu(br->lnum);
		offs = le32_to_cpu(br->offs);
		len = le32_to_cpu(br->len);
		key_read(c, &br->key, &lower_key);
		if (iip + 1 < le16_to_cpu(idx->child_cnt)) {
			br = ubifs_idx_branch(c, idx, iip + 1);
			key_read(c, &br->key, &upper_key);
		} else
			key_copy(c, &i->upper_key, &upper_key);
	}
out:
	err = dbg_old_index_check_init(c, zroot);
	if (err)
		goto out_free;

	return 0;

out_dump:
	ubifs_err("dumping index node (iip=%d)", i->iip);
	ubifs_dump_node(c, idx);
	list_del(&i->list);
	kfree(i);
	if (!list_empty(&list)) {
		i = list_entry(list.prev, struct idx_node, list);
		ubifs_err("dumping parent index node");
		ubifs_dump_node(c, &i->idx);
	}
out_free:
	while (!list_empty(&list)) {
		i = list_entry(list.next, struct idx_node, list);
		list_del(&i->list);
		kfree(i);
	}
	ubifs_err("failed, error %d", err);
	if (err > 0)
		err = -EINVAL;
	return err;
}
ef='#n2942'>2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428
/*
 * Copyright (c) 2012 Intel Corporation.  All rights reserved.
 * Copyright (c) 2008 - 2012 QLogic Corporation. All rights reserved.
 *
 * This software is available to you under a choice of one of two
 * licenses.  You may choose to be licensed under the terms of the GNU
 * General Public License (GPL) Version 2, available from the file
 * COPYING in the main directory of this source tree, or the
 * OpenIB.org BSD license below:
 *
 *     Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *      - Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *
 *      - Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/*
 * This file contains all of the code that is specific to the
 * InfiniPath 7322 chip
 */

#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <rdma/ib_verbs.h>
#include <rdma/ib_smi.h>
#ifdef CONFIG_INFINIBAND_QIB_DCA
#include <linux/dca.h>
#endif

#include "qib.h"
#include "qib_7322_regs.h"
#include "qib_qsfp.h"

#include "qib_mad.h"
#include "qib_verbs.h"

#undef pr_fmt
#define pr_fmt(fmt) QIB_DRV_NAME " " fmt

static void qib_setup_7322_setextled(struct qib_pportdata *, u32);
static void qib_7322_handle_hwerrors(struct qib_devdata *, char *, size_t);
static void sendctrl_7322_mod(struct qib_pportdata *ppd, u32 op);
static irqreturn_t qib_7322intr(int irq, void *data);
static irqreturn_t qib_7322bufavail(int irq, void *data);
static irqreturn_t sdma_intr(int irq, void *data);
static irqreturn_t sdma_idle_intr(int irq, void *data);
static irqreturn_t sdma_progress_intr(int irq, void *data);
static irqreturn_t sdma_cleanup_intr(int irq, void *data);
static void qib_7322_txchk_change(struct qib_devdata *, u32, u32, u32,
				  struct qib_ctxtdata *rcd);
static u8 qib_7322_phys_portstate(u64);
static u32 qib_7322_iblink_state(u64);
static void qib_set_ib_7322_lstate(struct qib_pportdata *ppd, u16 linkcmd,
				   u16 linitcmd);
static void force_h1(struct qib_pportdata *);
static void adj_tx_serdes(struct qib_pportdata *);
static u32 qib_7322_setpbc_control(struct qib_pportdata *, u32, u8, u8);
static void qib_7322_mini_pcs_reset(struct qib_pportdata *);

static u32 ahb_mod(struct qib_devdata *, int, int, int, u32, u32);
static void ibsd_wr_allchans(struct qib_pportdata *, int, unsigned, unsigned);
static void serdes_7322_los_enable(struct qib_pportdata *, int);
static int serdes_7322_init_old(struct qib_pportdata *);
static int serdes_7322_init_new(struct qib_pportdata *);

#define BMASK(msb, lsb) (((1 << ((msb) + 1 - (lsb))) - 1) << (lsb))

/* LE2 serdes values for different cases */
#define LE2_DEFAULT 5
#define LE2_5m 4
#define LE2_QME 0

/* Below is special-purpose, so only really works for the IB SerDes blocks. */
#define IBSD(hw_pidx) (hw_pidx + 2)

/* these are variables for documentation and experimentation purposes */
static const unsigned rcv_int_timeout = 375;
static const unsigned rcv_int_count = 16;
static const unsigned sdma_idle_cnt = 64;

/* Time to stop altering Rx Equalization parameters, after link up. */
#define RXEQ_DISABLE_MSECS 2500

/*
 * Number of VLs we are configured to use (to allow for more
 * credits per vl, etc.)
 */
ushort qib_num_cfg_vls = 2;
module_param_named(num_vls, qib_num_cfg_vls, ushort, S_IRUGO);
MODULE_PARM_DESC(num_vls, "Set number of Virtual Lanes to use (1-8)");

static ushort qib_chase = 1;
module_param_named(chase, qib_chase, ushort, S_IRUGO);
MODULE_PARM_DESC(chase, "Enable state chase handling");

static ushort qib_long_atten = 10; /* 10 dB ~= 5m length */
module_param_named(long_attenuation, qib_long_atten, ushort, S_IRUGO);
MODULE_PARM_DESC(long_attenuation, \
		 "attenuation cutoff (dB) for long copper cable setup");

static ushort qib_singleport;
module_param_named(singleport, qib_singleport, ushort, S_IRUGO);
MODULE_PARM_DESC(singleport, "Use only IB port 1; more per-port buffer space");

static ushort qib_krcvq01_no_msi;
module_param_named(krcvq01_no_msi, qib_krcvq01_no_msi, ushort, S_IRUGO);
MODULE_PARM_DESC(krcvq01_no_msi, "No MSI for kctx < 2");

/*
 * Receive header queue sizes
 */
static unsigned qib_rcvhdrcnt;
module_param_named(rcvhdrcnt, qib_rcvhdrcnt, uint, S_IRUGO);
MODULE_PARM_DESC(rcvhdrcnt, "receive header count");

static unsigned qib_rcvhdrsize;
module_param_named(rcvhdrsize, qib_rcvhdrsize, uint, S_IRUGO);
MODULE_PARM_DESC(rcvhdrsize, "receive header size in 32-bit words");

static unsigned qib_rcvhdrentsize;
module_param_named(rcvhdrentsize, qib_rcvhdrentsize, uint, S_IRUGO);
MODULE_PARM_DESC(rcvhdrentsize, "receive header entry size in 32-bit words");

#define MAX_ATTEN_LEN 64 /* plenty for any real system */
/* for read back, default index is ~5m copper cable */
static char txselect_list[MAX_ATTEN_LEN] = "10";
static struct kparam_string kp_txselect = {
	.string = txselect_list,
	.maxlen = MAX_ATTEN_LEN
};
static int  setup_txselect(const char *, struct kernel_param *);
module_param_call(txselect, setup_txselect, param_get_string,
		  &kp_txselect, S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(txselect, \
		 "Tx serdes indices (for no QSFP or invalid QSFP data)");

#define BOARD_QME7342 5
#define BOARD_QMH7342 6
#define IS_QMH(dd) (SYM_FIELD((dd)->revision, Revision, BoardID) == \
		    BOARD_QMH7342)
#define IS_QME(dd) (SYM_FIELD((dd)->revision, Revision, BoardID) == \
		    BOARD_QME7342)

#define KREG_IDX(regname)     (QIB_7322_##regname##_OFFS / sizeof(u64))

#define KREG_IBPORT_IDX(regname) ((QIB_7322_##regname##_0_OFFS / sizeof(u64)))

#define MASK_ACROSS(lsb, msb) \
	(((1ULL << ((msb) + 1 - (lsb))) - 1) << (lsb))

#define SYM_RMASK(regname, fldname) ((u64)              \
	QIB_7322_##regname##_##fldname##_RMASK)

#define SYM_MASK(regname, fldname) ((u64)               \
	QIB_7322_##regname##_##fldname##_RMASK <<       \
	 QIB_7322_##regname##_##fldname##_LSB)

#define SYM_FIELD(value, regname, fldname) ((u64)	\
	(((value) >> SYM_LSB(regname, fldname)) &	\
	 SYM_RMASK(regname, fldname)))

/* useful for things like LaFifoEmpty_0...7, TxCreditOK_0...7, etc. */
#define SYM_FIELD_ACROSS(value, regname, fldname, nbits) \
	(((value) >> SYM_LSB(regname, fldname)) & MASK_ACROSS(0, nbits))

#define HWE_MASK(fldname) SYM_MASK(HwErrMask, fldname##Mask)
#define ERR_MASK(fldname) SYM_MASK(ErrMask, fldname##Mask)
#define ERR_MASK_N(fldname) SYM_MASK(ErrMask_0, fldname##Mask)
#define INT_MASK(fldname) SYM_MASK(IntMask, fldname##IntMask)
#define INT_MASK_P(fldname, port) SYM_MASK(IntMask, fldname##IntMask##_##port)
/* Below because most, but not all, fields of IntMask have that full suffix */
#define INT_MASK_PM(fldname, port) SYM_MASK(IntMask, fldname##Mask##_##port)


#define SYM_LSB(regname, fldname) (QIB_7322_##regname##_##fldname##_LSB)

/*
 * the size bits give us 2^N, in KB units.  0 marks as invalid,
 * and 7 is reserved.  We currently use only 2KB and 4KB
 */
#define IBA7322_TID_SZ_SHIFT QIB_7322_RcvTIDArray0_RT_BufSize_LSB
#define IBA7322_TID_SZ_2K (1UL<<IBA7322_TID_SZ_SHIFT) /* 2KB */
#define IBA7322_TID_SZ_4K (2UL<<IBA7322_TID_SZ_SHIFT) /* 4KB */
#define IBA7322_TID_PA_SHIFT 11U /* TID addr in chip stored w/o low bits */

#define SendIBSLIDAssignMask \
	QIB_7322_SendIBSLIDAssign_0_SendIBSLIDAssign_15_0_RMASK
#define SendIBSLMCMask \
	QIB_7322_SendIBSLIDMask_0_SendIBSLIDMask_15_0_RMASK

#define ExtLED_IB1_YEL SYM_MASK(EXTCtrl, LEDPort0YellowOn)
#define ExtLED_IB1_GRN SYM_MASK(EXTCtrl, LEDPort0GreenOn)
#define ExtLED_IB2_YEL SYM_MASK(EXTCtrl, LEDPort1YellowOn)
#define ExtLED_IB2_GRN SYM_MASK(EXTCtrl, LEDPort1GreenOn)
#define ExtLED_IB1_MASK (ExtLED_IB1_YEL | ExtLED_IB1_GRN)
#define ExtLED_IB2_MASK (ExtLED_IB2_YEL | ExtLED_IB2_GRN)

#define _QIB_GPIO_SDA_NUM 1
#define _QIB_GPIO_SCL_NUM 0
#define QIB_EEPROM_WEN_NUM 14
#define QIB_TWSI_EEPROM_DEV 0xA2 /* All Production 7322 cards. */

/* HW counter clock is at 4nsec */
#define QIB_7322_PSXMITWAIT_CHECK_RATE 4000

/* full speed IB port 1 only */
#define PORT_SPD_CAP (QIB_IB_SDR | QIB_IB_DDR | QIB_IB_QDR)
#define PORT_SPD_CAP_SHIFT 3

/* full speed featuremask, both ports */
#define DUAL_PORT_CAP (PORT_SPD_CAP | (PORT_SPD_CAP << PORT_SPD_CAP_SHIFT))

/*
 * This file contains almost all the chip-specific register information and
 * access functions for the FAKED QLogic InfiniPath 7322 PCI-Express chip.
 */

/* Use defines to tie machine-generated names to lower-case names */
#define kr_contextcnt KREG_IDX(ContextCnt)
#define kr_control KREG_IDX(Control)
#define kr_counterregbase KREG_IDX(CntrRegBase)
#define kr_errclear KREG_IDX(ErrClear)
#define kr_errmask KREG_IDX(ErrMask)
#define kr_errstatus KREG_IDX(ErrStatus)
#define kr_extctrl KREG_IDX(EXTCtrl)
#define kr_extstatus KREG_IDX(EXTStatus)
#define kr_gpio_clear KREG_IDX(GPIOClear)
#define kr_gpio_mask KREG_IDX(GPIOMask)
#define kr_gpio_out KREG_IDX(GPIOOut)
#define kr_gpio_status KREG_IDX(GPIOStatus)
#define kr_hwdiagctrl KREG_IDX(HwDiagCtrl)
#define kr_debugportval KREG_IDX(DebugPortValueReg)
#define kr_fmask KREG_IDX(feature_mask)
#define kr_act_fmask KREG_IDX(active_feature_mask)
#define kr_hwerrclear KREG_IDX(HwErrClear)
#define kr_hwerrmask KREG_IDX(HwErrMask)
#define kr_hwerrstatus KREG_IDX(HwErrStatus)
#define kr_intclear KREG_IDX(IntClear)
#define kr_intmask KREG_IDX(IntMask)
#define kr_intredirect KREG_IDX(IntRedirect0)
#define kr_intstatus KREG_IDX(IntStatus)
#define kr_pagealign KREG_IDX(PageAlign)
#define kr_rcvavailtimeout KREG_IDX(RcvAvailTimeOut0)
#define kr_rcvctrl KREG_IDX(RcvCtrl) /* Common, but chip also has per-port */
#define kr_rcvegrbase KREG_IDX(RcvEgrBase)
#define kr_rcvegrcnt KREG_IDX(RcvEgrCnt)
#define kr_rcvhdrcnt KREG_IDX(RcvHdrCnt)
#define kr_rcvhdrentsize KREG_IDX(RcvHdrEntSize)
#define kr_rcvhdrsize KREG_IDX(RcvHdrSize)
#define kr_rcvtidbase KREG_IDX(RcvTIDBase)
#define kr_rcvtidcnt KREG_IDX(RcvTIDCnt)
#define kr_revision KREG_IDX(Revision)
#define kr_scratch KREG_IDX(Scratch)
#define kr_sendbuffererror KREG_IDX(SendBufErr0) /* and base for 1 and 2 */
#define kr_sendcheckmask KREG_IDX(SendCheckMask0) /* and 1, 2 */
#define kr_sendctrl KREG_IDX(SendCtrl)
#define kr_sendgrhcheckmask KREG_IDX(SendGRHCheckMask0) /* and 1, 2 */
#define kr_sendibpktmask KREG_IDX(SendIBPacketMask0) /* and 1, 2 */
#define kr_sendpioavailaddr KREG_IDX(SendBufAvailAddr)
#define kr_sendpiobufbase KREG_IDX(SendBufBase)
#define kr_sendpiobufcnt KREG_IDX(SendBufCnt)
#define kr_sendpiosize KREG_IDX(SendBufSize)
#define kr_sendregbase KREG_IDX(SendRegBase)
#define kr_sendbufavail0 KREG_IDX(SendBufAvail0)
#define kr_userregbase KREG_IDX(UserRegBase)
#define kr_intgranted KREG_IDX(Int_Granted)
#define kr_vecclr_wo_int KREG_IDX(vec_clr_without_int)
#define kr_intblocked KREG_IDX(IntBlocked)
#define kr_r_access KREG_IDX(SPC_JTAG_ACCESS_REG)

/*
 * per-port kernel registers.  Access only with qib_read_kreg_port()
 * or qib_write_kreg_port()
 */
#define krp_errclear KREG_IBPORT_IDX(ErrClear)
#define krp_errmask KREG_IBPORT_IDX(ErrMask)
#define krp_errstatus KREG_IBPORT_IDX(ErrStatus)
#define krp_highprio_0 KREG_IBPORT_IDX(HighPriority0)
#define krp_highprio_limit KREG_IBPORT_IDX(HighPriorityLimit)
#define krp_hrtbt_guid KREG_IBPORT_IDX(HRTBT_GUID)
#define krp_ib_pcsconfig KREG_IBPORT_IDX(IBPCSConfig)
#define krp_ibcctrl_a KREG_IBPORT_IDX(IBCCtrlA)
#define krp_ibcctrl_b KREG_IBPORT_IDX(IBCCtrlB)
#define krp_ibcctrl_c KREG_IBPORT_IDX(IBCCtrlC)
#define krp_ibcstatus_a KREG_IBPORT_IDX(IBCStatusA)
#define krp_ibcstatus_b KREG_IBPORT_IDX(IBCStatusB)
#define krp_txestatus KREG_IBPORT_IDX(TXEStatus)
#define krp_lowprio_0 KREG_IBPORT_IDX(LowPriority0)
#define krp_ncmodectrl KREG_IBPORT_IDX(IBNCModeCtrl)
#define krp_partitionkey KREG_IBPORT_IDX(RcvPartitionKey)
#define krp_psinterval KREG_IBPORT_IDX(PSInterval)
#define krp_psstart KREG_IBPORT_IDX(PSStart)
#define krp_psstat KREG_IBPORT_IDX(PSStat)
#define krp_rcvbthqp KREG_IBPORT_IDX(RcvBTHQP)
#define krp_rcvctrl KREG_IBPORT_IDX(RcvCtrl)
#define krp_rcvpktledcnt KREG_IBPORT_IDX(RcvPktLEDCnt)
#define krp_rcvqpmaptable KREG_IBPORT_IDX(RcvQPMapTableA)
#define krp_rxcreditvl0 KREG_IBPORT_IDX(RxCreditVL0)
#define krp_rxcreditvl15 (KREG_IBPORT_IDX(RxCreditVL0)+15)
#define krp_sendcheckcontrol KREG_IBPORT_IDX(SendCheckControl)
#define krp_sendctrl KREG_IBPORT_IDX(SendCtrl)
#define krp_senddmabase KREG_IBPORT_IDX(SendDmaBase)
#define krp_senddmabufmask0 KREG_IBPORT_IDX(SendDmaBufMask0)
#define krp_senddmabufmask1 (KREG_IBPORT_IDX(SendDmaBufMask0) + 1)
#define krp_senddmabufmask2 (KREG_IBPORT_IDX(SendDmaBufMask0) + 2)
#define krp_senddmabuf_use0 KREG_IBPORT_IDX(SendDmaBufUsed0)
#define krp_senddmabuf_use1 (KREG_IBPORT_IDX(SendDmaBufUsed0) + 1)
#define krp_senddmabuf_use2 (KREG_IBPORT_IDX(SendDmaBufUsed0) + 2)
#define krp_senddmadesccnt KREG_IBPORT_IDX(SendDmaDescCnt)
#define krp_senddmahead KREG_IBPORT_IDX(SendDmaHead)
#define krp_senddmaheadaddr KREG_IBPORT_IDX(SendDmaHeadAddr)
#define krp_senddmaidlecnt KREG_IBPORT_IDX(SendDmaIdleCnt)
#define krp_senddmalengen KREG_IBPORT_IDX(SendDmaLenGen)
#define krp_senddmaprioritythld KREG_IBPORT_IDX(SendDmaPriorityThld)
#define krp_senddmareloadcnt KREG_IBPORT_IDX(SendDmaReloadCnt)
#define krp_senddmastatus KREG_IBPORT_IDX(SendDmaStatus)
#define krp_senddmatail KREG_IBPORT_IDX(SendDmaTail)
#define krp_sendhdrsymptom KREG_IBPORT_IDX(SendHdrErrSymptom)
#define krp_sendslid KREG_IBPORT_IDX(SendIBSLIDAssign)
#define krp_sendslidmask KREG_IBPORT_IDX(SendIBSLIDMask)
#define krp_ibsdtestiftx KREG_IBPORT_IDX(IB_SDTEST_IF_TX)
#define krp_adapt_dis_timer KREG_IBPORT_IDX(ADAPT_DISABLE_TIMER_THRESHOLD)
#define krp_tx_deemph_override KREG_IBPORT_IDX(IBSD_TX_DEEMPHASIS_OVERRIDE)
#define krp_serdesctrl KREG_IBPORT_IDX(IBSerdesCtrl)

/*
 * Per-context kernel registers.  Access only with qib_read_kreg_ctxt()
 * or qib_write_kreg_ctxt()
 */
#define krc_rcvhdraddr KREG_IDX(RcvHdrAddr0)
#define krc_rcvhdrtailaddr KREG_IDX(RcvHdrTailAddr0)

/*
 * TID Flow table, per context.  Reduces
 * number of hdrq updates to one per flow (or on errors).
 * context 0 and 1 share same memory, but have distinct
 * addresses.  Since for now, we never use expected sends
 * on kernel contexts, we don't worry about that (we initialize
 * those entries for ctxt 0/1 on driver load twice, for example).
 */
#define NUM_TIDFLOWS_CTXT 0x20 /* 0x20 per context; have to hardcode */
#define ur_rcvflowtable (KREG_IDX(RcvTIDFlowTable0) - KREG_IDX(RcvHdrTail0))

/* these are the error bits in the tid flows, and are W1C */
#define TIDFLOW_ERRBITS  ( \
	(SYM_MASK(RcvTIDFlowTable0, GenMismatch) << \
	SYM_LSB(RcvTIDFlowTable0, GenMismatch)) | \
	(SYM_MASK(RcvTIDFlowTable0, SeqMismatch) << \
	SYM_LSB(RcvTIDFlowTable0, SeqMismatch)))

/* Most (not all) Counters are per-IBport.
 * Requires LBIntCnt is at offset 0 in the group
 */
#define CREG_IDX(regname) \
((QIB_7322_##regname##_0_OFFS - QIB_7322_LBIntCnt_OFFS) / sizeof(u64))

#define crp_badformat CREG_IDX(RxVersionErrCnt)
#define crp_err_rlen CREG_IDX(RxLenErrCnt)
#define crp_erricrc CREG_IDX(RxICRCErrCnt)
#define crp_errlink CREG_IDX(RxLinkMalformCnt)
#define crp_errlpcrc CREG_IDX(RxLPCRCErrCnt)
#define crp_errpkey CREG_IDX(RxPKeyMismatchCnt)
#define crp_errvcrc CREG_IDX(RxVCRCErrCnt)
#define crp_excessbufferovfl CREG_IDX(ExcessBufferOvflCnt)
#define crp_iblinkdown CREG_IDX(IBLinkDownedCnt)
#define crp_iblinkerrrecov CREG_IDX(IBLinkErrRecoveryCnt)
#define crp_ibstatuschange CREG_IDX(IBStatusChangeCnt)
#define crp_ibsymbolerr CREG_IDX(IBSymbolErrCnt)
#define crp_invalidrlen CREG_IDX(RxMaxMinLenErrCnt)
#define crp_locallinkintegrityerr CREG_IDX(LocalLinkIntegrityErrCnt)
#define crp_pktrcv CREG_IDX(RxDataPktCnt)
#define crp_pktrcvflowctrl CREG_IDX(RxFlowPktCnt)
#define crp_pktsend CREG_IDX(TxDataPktCnt)
#define crp_pktsendflow CREG_IDX(TxFlowPktCnt)
#define crp_psrcvdatacount CREG_IDX(PSRcvDataCount)
#define crp_psrcvpktscount CREG_IDX(PSRcvPktsCount)
#define crp_psxmitdatacount CREG_IDX(PSXmitDataCount)
#define crp_psxmitpktscount CREG_IDX(PSXmitPktsCount)
#define crp_psxmitwaitcount CREG_IDX(PSXmitWaitCount)
#define crp_rcvebp CREG_IDX(RxEBPCnt)
#define crp_rcvflowctrlviol CREG_IDX(RxFlowCtrlViolCnt)
#define crp_rcvovfl CREG_IDX(RxBufOvflCnt)
#define crp_rxdlidfltr CREG_IDX(RxDlidFltrCnt)
#define crp_rxdroppkt CREG_IDX(RxDroppedPktCnt)
#define crp_rxotherlocalphyerr CREG_IDX(RxOtherLocalPhyErrCnt)
#define crp_rxqpinvalidctxt CREG_IDX(RxQPInvalidContextCnt)
#define crp_rxvlerr CREG_IDX(RxVlErrCnt)
#define crp_sendstall CREG_IDX(TxFlowStallCnt)
#define crp_txdroppedpkt CREG_IDX(TxDroppedPktCnt)
#define crp_txhdrerr CREG_IDX(TxHeadersErrCnt)
#define crp_txlenerr CREG_IDX(TxLenErrCnt)
#define crp_txminmaxlenerr CREG_IDX(TxMaxMinLenErrCnt)
#define crp_txsdmadesc CREG_IDX(TxSDmaDescCnt)
#define crp_txunderrun CREG_IDX(TxUnderrunCnt)
#define crp_txunsupvl CREG_IDX(TxUnsupVLErrCnt)
#define crp_vl15droppedpkt CREG_IDX(RxVL15DroppedPktCnt)
#define crp_wordrcv CREG_IDX(RxDwordCnt)
#define crp_wordsend CREG_IDX(TxDwordCnt)
#define crp_tx_creditstalls CREG_IDX(TxCreditUpToDateTimeOut)

/* these are the (few) counters that are not port-specific */
#define CREG_DEVIDX(regname) ((QIB_7322_##regname##_OFFS - \
			QIB_7322_LBIntCnt_OFFS) / sizeof(u64))
#define cr_base_egrovfl CREG_DEVIDX(RxP0HdrEgrOvflCnt)
#define cr_lbint CREG_DEVIDX(LBIntCnt)
#define cr_lbstall CREG_DEVIDX(LBFlowStallCnt)
#define cr_pcieretrydiag CREG_DEVIDX(PcieRetryBufDiagQwordCnt)
#define cr_rxtidflowdrop CREG_DEVIDX(RxTidFlowDropCnt)
#define cr_tidfull CREG_DEVIDX(RxTIDFullErrCnt)
#define cr_tidinvalid CREG_DEVIDX(RxTIDValidErrCnt)

/* no chip register for # of IB ports supported, so define */
#define NUM_IB_PORTS 2

/* 1 VL15 buffer per hardware IB port, no register for this, so define */
#define NUM_VL15_BUFS NUM_IB_PORTS

/*
 * context 0 and 1 are special, and there is no chip register that
 * defines this value, so we have to define it here.
 * These are all allocated to either 0 or 1 for single port
 * hardware configuration, otherwise each gets half
 */
#define KCTXT0_EGRCNT 2048

/* values for vl and port fields in PBC, 7322-specific */
#define PBC_PORT_SEL_LSB 26
#define PBC_PORT_SEL_RMASK 1
#define PBC_VL_NUM_LSB 27
#define PBC_VL_NUM_RMASK 7
#define PBC_7322_VL15_SEND (1ULL << 63) /* pbc; VL15, no credit check */
#define PBC_7322_VL15_SEND_CTRL (1ULL << 31) /* control version of same */

static u8 ib_rate_to_delay[IB_RATE_120_GBPS + 1] = {
	[IB_RATE_2_5_GBPS] = 16,
	[IB_RATE_5_GBPS] = 8,
	[IB_RATE_10_GBPS] = 4,
	[IB_RATE_20_GBPS] = 2,
	[IB_RATE_30_GBPS] = 2,
	[IB_RATE_40_GBPS] = 1
};

#define IBA7322_LINKSPEED_SHIFT SYM_LSB(IBCStatusA_0, LinkSpeedActive)
#define IBA7322_LINKWIDTH_SHIFT SYM_LSB(IBCStatusA_0, LinkWidthActive)

/* link training states, from IBC */
#define IB_7322_LT_STATE_DISABLED        0x00
#define IB_7322_LT_STATE_LINKUP          0x01
#define IB_7322_LT_STATE_POLLACTIVE      0x02
#define IB_7322_LT_STATE_POLLQUIET       0x03
#define IB_7322_LT_STATE_SLEEPDELAY      0x04
#define IB_7322_LT_STATE_SLEEPQUIET      0x05
#define IB_7322_LT_STATE_CFGDEBOUNCE     0x08
#define IB_7322_LT_STATE_CFGRCVFCFG      0x09
#define IB_7322_LT_STATE_CFGWAITRMT      0x0a
#define IB_7322_LT_STATE_CFGIDLE         0x0b
#define IB_7322_LT_STATE_RECOVERRETRAIN  0x0c
#define IB_7322_LT_STATE_TXREVLANES      0x0d
#define IB_7322_LT_STATE_RECOVERWAITRMT  0x0e
#define IB_7322_LT_STATE_RECOVERIDLE     0x0f
#define IB_7322_LT_STATE_CFGENH          0x10
#define IB_7322_LT_STATE_CFGTEST         0x11
#define IB_7322_LT_STATE_CFGWAITRMTTEST  0x12
#define IB_7322_LT_STATE_CFGWAITENH      0x13

/* link state machine states from IBC */
#define IB_7322_L_STATE_DOWN             0x0
#define IB_7322_L_STATE_INIT             0x1
#define IB_7322_L_STATE_ARM              0x2
#define IB_7322_L_STATE_ACTIVE           0x3
#define IB_7322_L_STATE_ACT_DEFER        0x4

static const u8 qib_7322_physportstate[0x20] = {
	[IB_7322_LT_STATE_DISABLED] = IB_PHYSPORTSTATE_DISABLED,
	[IB_7322_LT_STATE_LINKUP] = IB_PHYSPORTSTATE_LINKUP,
	[IB_7322_LT_STATE_POLLACTIVE] = IB_PHYSPORTSTATE_POLL,
	[IB_7322_LT_STATE_POLLQUIET] = IB_PHYSPORTSTATE_POLL,
	[IB_7322_LT_STATE_SLEEPDELAY] = IB_PHYSPORTSTATE_SLEEP,
	[IB_7322_LT_STATE_SLEEPQUIET] = IB_PHYSPORTSTATE_SLEEP,
	[IB_7322_LT_STATE_CFGDEBOUNCE] = IB_PHYSPORTSTATE_CFG_TRAIN,
	[IB_7322_LT_STATE_CFGRCVFCFG] =
		IB_PHYSPORTSTATE_CFG_TRAIN,
	[IB_7322_LT_STATE_CFGWAITRMT] =
		IB_PHYSPORTSTATE_CFG_TRAIN,
	[IB_7322_LT_STATE_CFGIDLE] = IB_PHYSPORTSTATE_CFG_IDLE,
	[IB_7322_LT_STATE_RECOVERRETRAIN] =
		IB_PHYSPORTSTATE_LINK_ERR_RECOVER,
	[IB_7322_LT_STATE_RECOVERWAITRMT] =
		IB_PHYSPORTSTATE_LINK_ERR_RECOVER,
	[IB_7322_LT_STATE_RECOVERIDLE] =
		IB_PHYSPORTSTATE_LINK_ERR_RECOVER,
	[IB_7322_LT_STATE_CFGENH] = IB_PHYSPORTSTATE_CFG_ENH,
	[IB_7322_LT_STATE_CFGTEST] = IB_PHYSPORTSTATE_CFG_TRAIN,
	[IB_7322_LT_STATE_CFGWAITRMTTEST] =
		IB_PHYSPORTSTATE_CFG_TRAIN,
	[IB_7322_LT_STATE_CFGWAITENH] =
		IB_PHYSPORTSTATE_CFG_WAIT_ENH,
	[0x14] = IB_PHYSPORTSTATE_CFG_TRAIN,
	[0x15] = IB_PHYSPORTSTATE_CFG_TRAIN,
	[0x16] = IB_PHYSPORTSTATE_CFG_TRAIN,
	[0x17] = IB_PHYSPORTSTATE_CFG_TRAIN
};

#ifdef CONFIG_INFINIBAND_QIB_DCA
struct qib_irq_notify {
	int rcv;
	void *arg;
	struct irq_affinity_notify notify;
};
#endif

struct qib_chip_specific {
	u64 __iomem *cregbase;
	u64 *cntrs;
	spinlock_t rcvmod_lock; /* protect rcvctrl shadow changes */
	spinlock_t gpio_lock; /* RMW of shadows/regs for ExtCtrl and GPIO */
	u64 main_int_mask;      /* clear bits which have dedicated handlers */
	u64 int_enable_mask;  /* for per port interrupts in single port mode */
	u64 errormask;
	u64 hwerrmask;
	u64 gpio_out; /* shadow of kr_gpio_out, for rmw ops */
	u64 gpio_mask; /* shadow the gpio mask register */
	u64 extctrl; /* shadow the gpio output enable, etc... */
	u32 ncntrs;
	u32 nportcntrs;
	u32 cntrnamelen;
	u32 portcntrnamelen;
	u32 numctxts;
	u32 rcvegrcnt;
	u32 updthresh; /* current AvailUpdThld */
	u32 updthresh_dflt; /* default AvailUpdThld */
	u32 r1;
	int irq;
	u32 num_msix_entries;
	u32 sdmabufcnt;
	u32 lastbuf_for_pio;
	u32 stay_in_freeze;
	u32 recovery_ports_initted;
#ifdef CONFIG_INFINIBAND_QIB_DCA
	u32 dca_ctrl;
	int rhdr_cpu[18];
	int sdma_cpu[2];
	u64 dca_rcvhdr_ctrl[5]; /* B, C, D, E, F */
#endif
	struct qib_msix_entry *msix_entries;
	unsigned long *sendchkenable;
	unsigned long *sendgrhchk;
	unsigned long *sendibchk;
	u32 rcvavail_timeout[18];
	char emsgbuf[128]; /* for device error interrupt msg buffer */
};

/* Table of entries in "human readable" form Tx Emphasis. */
struct txdds_ent {
	u8 amp;
	u8 pre;
	u8 main;
	u8 post;
};

struct vendor_txdds_ent {
	u8 oui[QSFP_VOUI_LEN];
	u8 *partnum;
	struct txdds_ent sdr;
	struct txdds_ent ddr;
	struct txdds_ent qdr;
};

static void write_tx_serdes_param(struct qib_pportdata *, struct txdds_ent *);

#define TXDDS_TABLE_SZ 16 /* number of entries per speed in onchip table */
#define TXDDS_EXTRA_SZ 13 /* number of extra tx settings entries */
#define TXDDS_MFG_SZ 2    /* number of mfg tx settings entries */
#define SERDES_CHANS 4 /* yes, it's obvious, but one less magic number */

#define H1_FORCE_VAL 8
#define H1_FORCE_QME 1 /*  may be overridden via setup_txselect() */
#define H1_FORCE_QMH 7 /*  may be overridden via setup_txselect() */

/* The static and dynamic registers are paired, and the pairs indexed by spd */
#define krp_static_adapt_dis(spd) (KREG_IBPORT_IDX(ADAPT_DISABLE_STATIC_SDR) \
	+ ((spd) * 2))

#define QDR_DFE_DISABLE_DELAY 4000 /* msec after LINKUP */
#define QDR_STATIC_ADAPT_DOWN 0xf0f0f0f0ULL /* link down, H1-H4 QDR adapts */
#define QDR_STATIC_ADAPT_DOWN_R1 0ULL /* r1 link down, H1-H4 QDR adapts */
#define QDR_STATIC_ADAPT_INIT 0xffffffffffULL /* up, disable H0,H1-8, LE */
#define QDR_STATIC_ADAPT_INIT_R1 0xf0ffffffffULL /* r1 up, disable H0,H1-8 */

struct qib_chippport_specific {
	u64 __iomem *kpregbase;
	u64 __iomem *cpregbase;
	u64 *portcntrs;
	struct qib_pportdata *ppd;
	wait_queue_head_t autoneg_wait;
	struct delayed_work autoneg_work;
	struct delayed_work ipg_work;
	struct timer_list chase_timer;
	/*
	 * these 5 fields are used to establish deltas for IB symbol
	 * errors and linkrecovery errors.  They can be reported on
	 * some chips during link negotiation prior to INIT, and with
	 * DDR when faking DDR negotiations with non-IBTA switches.
	 * The chip counters are adjusted at driver unload if there is
	 * a non-zero delta.
	 */
	u64 ibdeltainprog;
	u64 ibsymdelta;
	u64 ibsymsnap;
	u64 iblnkerrdelta;
	u64 iblnkerrsnap;
	u64 iblnkdownsnap;
	u64 iblnkdowndelta;
	u64 ibmalfdelta;
	u64 ibmalfsnap;
	u64 ibcctrl_a; /* krp_ibcctrl_a shadow */
	u64 ibcctrl_b; /* krp_ibcctrl_b shadow */
	unsigned long qdr_dfe_time;
	unsigned long chase_end;
	u32 autoneg_tries;
	u32 recovery_init;
	u32 qdr_dfe_on;
	u32 qdr_reforce;
	/*
	 * Per-bay per-channel rcv QMH H1 values and Tx values for QDR.
	 * entry zero is unused, to simplify indexing
	 */
	u8 h1_val;
	u8 no_eep;  /* txselect table index to use if no qsfp info */
	u8 ipg_tries;
	u8 ibmalfusesnap;
	struct qib_qsfp_data qsfp_data;
	char epmsgbuf[192]; /* for port error interrupt msg buffer */
};

static struct {
	const char *name;
	irq_handler_t handler;
	int lsb;
	int port; /* 0 if not port-specific, else port # */
	int dca;
} irq_table[] = {
	{ "", qib_7322intr, -1, 0, 0 },
	{ " (buf avail)", qib_7322bufavail,
		SYM_LSB(IntStatus, SendBufAvail), 0, 0},
	{ " (sdma 0)", sdma_intr,
		SYM_LSB(IntStatus, SDmaInt_0), 1, 1 },
	{ " (sdma 1)", sdma_intr,
		SYM_LSB(IntStatus, SDmaInt_1), 2, 1 },
	{ " (sdmaI 0)", sdma_idle_intr,
		SYM_LSB(IntStatus, SDmaIdleInt_0), 1, 1},
	{ " (sdmaI 1)", sdma_idle_intr,
		SYM_LSB(IntStatus, SDmaIdleInt_1), 2, 1},
	{ " (sdmaP 0)", sdma_progress_intr,
		SYM_LSB(IntStatus, SDmaProgressInt_0), 1, 1 },
	{ " (sdmaP 1)", sdma_progress_intr,
		SYM_LSB(IntStatus, SDmaProgressInt_1), 2, 1 },
	{ " (sdmaC 0)", sdma_cleanup_intr,
		SYM_LSB(IntStatus, SDmaCleanupDone_0), 1, 0 },
	{ " (sdmaC 1)", sdma_cleanup_intr,
		SYM_LSB(IntStatus, SDmaCleanupDone_1), 2 , 0},
};

#ifdef CONFIG_INFINIBAND_QIB_DCA

static const struct dca_reg_map {
	int     shadow_inx;
	int     lsb;
	u64     mask;
	u16     regno;
} dca_rcvhdr_reg_map[] = {
	{ 0, SYM_LSB(DCACtrlB, RcvHdrq0DCAOPH),
	   ~SYM_MASK(DCACtrlB, RcvHdrq0DCAOPH) , KREG_IDX(DCACtrlB) },
	{ 0, SYM_LSB(DCACtrlB, RcvHdrq1DCAOPH),
	   ~SYM_MASK(DCACtrlB, RcvHdrq1DCAOPH) , KREG_IDX(DCACtrlB) },
	{ 0, SYM_LSB(DCACtrlB, RcvHdrq2DCAOPH),
	   ~SYM_MASK(DCACtrlB, RcvHdrq2DCAOPH) , KREG_IDX(DCACtrlB) },
	{ 0, SYM_LSB(DCACtrlB, RcvHdrq3DCAOPH),
	   ~SYM_MASK(DCACtrlB, RcvHdrq3DCAOPH) , KREG_IDX(DCACtrlB) },
	{ 1, SYM_LSB(DCACtrlC, RcvHdrq4DCAOPH),
	   ~SYM_MASK(DCACtrlC, RcvHdrq4DCAOPH) , KREG_IDX(DCACtrlC) },
	{ 1, SYM_LSB(DCACtrlC, RcvHdrq5DCAOPH),
	   ~SYM_MASK(DCACtrlC, RcvHdrq5DCAOPH) , KREG_IDX(DCACtrlC) },
	{ 1, SYM_LSB(DCACtrlC, RcvHdrq6DCAOPH),
	   ~SYM_MASK(DCACtrlC, RcvHdrq6DCAOPH) , KREG_IDX(DCACtrlC) },
	{ 1, SYM_LSB(DCACtrlC, RcvHdrq7DCAOPH),
	   ~SYM_MASK(DCACtrlC, RcvHdrq7DCAOPH) , KREG_IDX(DCACtrlC) },
	{ 2, SYM_LSB(DCACtrlD, RcvHdrq8DCAOPH),
	   ~SYM_MASK(DCACtrlD, RcvHdrq8DCAOPH) , KREG_IDX(DCACtrlD) },
	{ 2, SYM_LSB(DCACtrlD, RcvHdrq9DCAOPH),
	   ~SYM_MASK(DCACtrlD, RcvHdrq9DCAOPH) , KREG_IDX(DCACtrlD) },
	{ 2, SYM_LSB(DCACtrlD, RcvHdrq10DCAOPH),
	   ~SYM_MASK(DCACtrlD, RcvHdrq10DCAOPH) , KREG_IDX(DCACtrlD) },
	{ 2, SYM_LSB(DCACtrlD, RcvHdrq11DCAOPH),
	   ~SYM_MASK(DCACtrlD, RcvHdrq11DCAOPH) , KREG_IDX(DCACtrlD) },
	{ 3, SYM_LSB(DCACtrlE, RcvHdrq12DCAOPH),
	   ~SYM_MASK(DCACtrlE, RcvHdrq12DCAOPH) , KREG_IDX(DCACtrlE) },
	{ 3, SYM_LSB(DCACtrlE, RcvHdrq13DCAOPH),
	   ~SYM_MASK(DCACtrlE, RcvHdrq13DCAOPH) , KREG_IDX(DCACtrlE) },
	{ 3, SYM_LSB(DCACtrlE, RcvHdrq14DCAOPH),
	   ~SYM_MASK(DCACtrlE, RcvHdrq14DCAOPH) , KREG_IDX(DCACtrlE) },
	{ 3, SYM_LSB(DCACtrlE, RcvHdrq15DCAOPH),
	   ~SYM_MASK(DCACtrlE, RcvHdrq15DCAOPH) , KREG_IDX(DCACtrlE) },
	{ 4, SYM_LSB(DCACtrlF, RcvHdrq16DCAOPH),
	   ~SYM_MASK(DCACtrlF, RcvHdrq16DCAOPH) , KREG_IDX(DCACtrlF) },
	{ 4, SYM_LSB(DCACtrlF, RcvHdrq17DCAOPH),
	   ~SYM_MASK(DCACtrlF, RcvHdrq17DCAOPH) , KREG_IDX(DCACtrlF) },
};
#endif

/* ibcctrl bits */
#define QLOGIC_IB_IBCC_LINKINITCMD_DISABLE 1
/* cycle through TS1/TS2 till OK */
#define QLOGIC_IB_IBCC_LINKINITCMD_POLL 2
/* wait for TS1, then go on */
#define QLOGIC_IB_IBCC_LINKINITCMD_SLEEP 3
#define QLOGIC_IB_IBCC_LINKINITCMD_SHIFT 16

#define QLOGIC_IB_IBCC_LINKCMD_DOWN 1           /* move to 0x11 */
#define QLOGIC_IB_IBCC_LINKCMD_ARMED 2          /* move to 0x21 */
#define QLOGIC_IB_IBCC_LINKCMD_ACTIVE 3 /* move to 0x31 */

#define BLOB_7322_IBCHG 0x101

static inline void qib_write_kreg(const struct qib_devdata *dd,
				  const u32 regno, u64 value);
static inline u32 qib_read_kreg32(const struct qib_devdata *, const u32);
static void write_7322_initregs(struct qib_devdata *);
static void write_7322_init_portregs(struct qib_pportdata *);
static void setup_7322_link_recovery(struct qib_pportdata *, u32);
static void check_7322_rxe_status(struct qib_pportdata *);
static u32 __iomem *qib_7322_getsendbuf(struct qib_pportdata *, u64, u32 *);
#ifdef CONFIG_INFINIBAND_QIB_DCA
static void qib_setup_dca(struct qib_devdata *dd);
static void setup_dca_notifier(struct qib_devdata *dd,
			       struct qib_msix_entry *m);
static void reset_dca_notifier(struct qib_devdata *dd,
			       struct qib_msix_entry *m);
#endif

/**
 * qib_read_ureg32 - read 32-bit virtualized per-context register
 * @dd: device
 * @regno: register number
 * @ctxt: context number
 *
 * Return the contents of a register that is virtualized to be per context.
 * Returns -1 on errors (not distinguishable from valid contents at
 * runtime; we may add a separate error variable at some point).
 */
static inline u32 qib_read_ureg32(const struct qib_devdata *dd,
				  enum qib_ureg regno, int ctxt)
{
	if (!dd->kregbase || !(dd->flags & QIB_PRESENT))
		return 0;
	return readl(regno + (u64 __iomem *)(
		(dd->ureg_align * ctxt) + (dd->userbase ?
		 (char __iomem *)dd->userbase :
		 (char __iomem *)dd->kregbase + dd->uregbase)));
}

/**
 * qib_read_ureg - read virtualized per-context register
 * @dd: device
 * @regno: register number
 * @ctxt: context number
 *
 * Return the contents of a register that is virtualized to be per context.
 * Returns -1 on errors (not distinguishable from valid contents at
 * runtime; we may add a separate error variable at some point).
 */
static inline u64 qib_read_ureg(const struct qib_devdata *dd,
				enum qib_ureg regno, int ctxt)
{

	if (!dd->kregbase || !(dd->flags & QIB_PRESENT))
		return 0;
	return readq(regno + (u64 __iomem *)(
		(dd->ureg_align * ctxt) + (dd->userbase ?
		 (char __iomem *)dd->userbase :
		 (char __iomem *)dd->kregbase + dd->uregbase)));
}

/**
 * qib_write_ureg - write virtualized per-context register
 * @dd: device
 * @regno: register number
 * @value: value
 * @ctxt: context
 *
 * Write the contents of a register that is virtualized to be per context.
 */
static inline void qib_write_ureg(const struct qib_devdata *dd,
				  enum qib_ureg regno, u64 value, int ctxt)
{
	u64 __iomem *ubase;
	if (dd->userbase)
		ubase = (u64 __iomem *)
			((char __iomem *) dd->userbase +
			 dd->ureg_align * ctxt);
	else
		ubase = (u64 __iomem *)
			(dd->uregbase +
			 (char __iomem *) dd->kregbase +
			 dd->ureg_align * ctxt);

	if (dd->kregbase && (dd->flags & QIB_PRESENT))
		writeq(value, &ubase[regno]);
}

static inline u32 qib_read_kreg32(const struct qib_devdata *dd,
				  const u32 regno)
{
	if (!dd->kregbase || !(dd->flags & QIB_PRESENT))
		return -1;
	return readl((u32 __iomem *) &dd->kregbase[regno]);
}

static inline u64 qib_read_kreg64(const struct qib_devdata *dd,
				  const u32 regno)
{
	if (!dd->kregbase || !(dd->flags & QIB_PRESENT))
		return -1;
	return readq(&dd->kregbase[regno]);
}

static inline void qib_write_kreg(const struct qib_devdata *dd,
				  const u32 regno, u64 value)
{
	if (dd->kregbase && (dd->flags & QIB_PRESENT))
		writeq(value, &dd->kregbase[regno]);
}

/*
 * not many sanity checks for the port-specific kernel register routines,
 * since they are only used when it's known to be safe.
*/
static inline u64 qib_read_kreg_port(const struct qib_pportdata *ppd,
				     const u16 regno)
{
	if (!ppd->cpspec->kpregbase || !(ppd->dd->flags & QIB_PRESENT))
		return 0ULL;
	return readq(&ppd->cpspec->kpregbase[regno]);
}

static inline void qib_write_kreg_port(const struct qib_pportdata *ppd,
				       const u16 regno, u64 value)
{
	if (ppd->cpspec && ppd->dd && ppd->cpspec->kpregbase &&
	    (ppd->dd->flags & QIB_PRESENT))
		writeq(value, &ppd->cpspec->kpregbase[regno]);
}

/**
 * qib_write_kreg_ctxt - write a device's per-ctxt 64-bit kernel register
 * @dd: the qlogic_ib device
 * @regno: the register number to write
 * @ctxt: the context containing the register
 * @value: the value to write
 */
static inline void qib_write_kreg_ctxt(const struct qib_devdata *dd,
				       const u16 regno, unsigned ctxt,
				       u64 value)
{
	qib_write_kreg(dd, regno + ctxt, value);
}

static inline u64 read_7322_creg(const struct qib_devdata *dd, u16 regno)
{
	if (!dd->cspec->cregbase || !(dd->flags & QIB_PRESENT))
		return 0;
	return readq(&dd->cspec->cregbase[regno]);


}

static inline u32 read_7322_creg32(const struct qib_devdata *dd, u16 regno)
{
	if (!dd->cspec->cregbase || !(dd->flags & QIB_PRESENT))
		return 0;
	return readl(&dd->cspec->cregbase[regno]);


}

static inline void write_7322_creg_port(const struct qib_pportdata *ppd,
					u16 regno, u64 value)
{
	if (ppd->cpspec && ppd->cpspec->cpregbase &&
	    (ppd->dd->flags & QIB_PRESENT))
		writeq(value, &ppd->cpspec->cpregbase[regno]);
}

static inline u64 read_7322_creg_port(const struct qib_pportdata *ppd,
				      u16 regno)
{
	if (!ppd->cpspec || !ppd->cpspec->cpregbase ||
	    !(ppd->dd->flags & QIB_PRESENT))
		return 0;
	return readq(&ppd->cpspec->cpregbase[regno]);
}

static inline u32 read_7322_creg32_port(const struct qib_pportdata *ppd,
					u16 regno)
{
	if (!ppd->cpspec || !ppd->cpspec->cpregbase ||
	    !(ppd->dd->flags & QIB_PRESENT))
		return 0;
	return readl(&ppd->cpspec->cpregbase[regno]);
}

/* bits in Control register */
#define QLOGIC_IB_C_RESET SYM_MASK(Control, SyncReset)
#define QLOGIC_IB_C_SDMAFETCHPRIOEN SYM_MASK(Control, SDmaDescFetchPriorityEn)

/* bits in general interrupt regs */
#define QIB_I_RCVURG_LSB SYM_LSB(IntMask, RcvUrg0IntMask)
#define QIB_I_RCVURG_RMASK MASK_ACROSS(0, 17)
#define QIB_I_RCVURG_MASK (QIB_I_RCVURG_RMASK << QIB_I_RCVURG_LSB)
#define QIB_I_RCVAVAIL_LSB SYM_LSB(IntMask, RcvAvail0IntMask)
#define QIB_I_RCVAVAIL_RMASK MASK_ACROSS(0, 17)
#define QIB_I_RCVAVAIL_MASK (QIB_I_RCVAVAIL_RMASK << QIB_I_RCVAVAIL_LSB)
#define QIB_I_C_ERROR INT_MASK(Err)

#define QIB_I_SPIOSENT (INT_MASK_P(SendDone, 0) | INT_MASK_P(SendDone, 1))
#define QIB_I_SPIOBUFAVAIL INT_MASK(SendBufAvail)
#define QIB_I_GPIO INT_MASK(AssertGPIO)
#define QIB_I_P_SDMAINT(pidx) \
	(INT_MASK_P(SDma, pidx) | INT_MASK_P(SDmaIdle, pidx) | \
	 INT_MASK_P(SDmaProgress, pidx) | \
	 INT_MASK_PM(SDmaCleanupDone, pidx))

/* Interrupt bits that are "per port" */
#define QIB_I_P_BITSEXTANT(pidx) \
	(INT_MASK_P(Err, pidx) | INT_MASK_P(SendDone, pidx) | \
	INT_MASK_P(SDma, pidx) | INT_MASK_P(SDmaIdle, pidx) | \
	INT_MASK_P(SDmaProgress, pidx) | \
	INT_MASK_PM(SDmaCleanupDone, pidx))

/* Interrupt bits that are common to a device */
/* currently unused: QIB_I_SPIOSENT */
#define QIB_I_C_BITSEXTANT \
	(QIB_I_RCVURG_MASK | QIB_I_RCVAVAIL_MASK | \
	QIB_I_SPIOSENT | \
	QIB_I_C_ERROR | QIB_I_SPIOBUFAVAIL | QIB_I_GPIO)

#define QIB_I_BITSEXTANT (QIB_I_C_BITSEXTANT | \
	QIB_I_P_BITSEXTANT(0) | QIB_I_P_BITSEXTANT(1))

/*
 * Error bits that are "per port".
 */
#define QIB_E_P_IBSTATUSCHANGED ERR_MASK_N(IBStatusChanged)
#define QIB_E_P_SHDR ERR_MASK_N(SHeadersErr)
#define QIB_E_P_VL15_BUF_MISUSE ERR_MASK_N(VL15BufMisuseErr)
#define QIB_E_P_SND_BUF_MISUSE ERR_MASK_N(SendBufMisuseErr)
#define QIB_E_P_SUNSUPVL ERR_MASK_N(SendUnsupportedVLErr)
#define QIB_E_P_SUNEXP_PKTNUM ERR_MASK_N(SendUnexpectedPktNumErr)
#define QIB_E_P_SDROP_DATA ERR_MASK_N(SendDroppedDataPktErr)
#define QIB_E_P_SDROP_SMP ERR_MASK_N(SendDroppedSmpPktErr)
#define QIB_E_P_SPKTLEN ERR_MASK_N(SendPktLenErr)
#define QIB_E_P_SUNDERRUN ERR_MASK_N(SendUnderRunErr)
#define QIB_E_P_SMAXPKTLEN ERR_MASK_N(SendMaxPktLenErr)
#define QIB_E_P_SMINPKTLEN ERR_MASK_N(SendMinPktLenErr)
#define QIB_E_P_RIBLOSTLINK ERR_MASK_N(RcvIBLostLinkErr)
#define QIB_E_P_RHDR ERR_MASK_N(RcvHdrErr)
#define QIB_E_P_RHDRLEN ERR_MASK_N(RcvHdrLenErr)
#define QIB_E_P_RBADTID ERR_MASK_N(RcvBadTidErr)
#define QIB_E_P_RBADVERSION ERR_MASK_N(RcvBadVersionErr)
#define QIB_E_P_RIBFLOW ERR_MASK_N(RcvIBFlowErr)
#define QIB_E_P_REBP ERR_MASK_N(RcvEBPErr)
#define QIB_E_P_RUNSUPVL ERR_MASK_N(RcvUnsupportedVLErr)
#define QIB_E_P_RUNEXPCHAR ERR_MASK_N(RcvUnexpectedCharErr)
#define QIB_E_P_RSHORTPKTLEN ERR_MASK_N(RcvShortPktLenErr)
#define QIB_E_P_RLONGPKTLEN ERR_MASK_N(RcvLongPktLenErr)
#define QIB_E_P_RMAXPKTLEN ERR_MASK_N(RcvMaxPktLenErr)
#define QIB_E_P_RMINPKTLEN ERR_MASK_N(RcvMinPktLenErr)
#define QIB_E_P_RICRC ERR_MASK_N(RcvICRCErr)
#define QIB_E_P_RVCRC ERR_MASK_N(RcvVCRCErr)
#define QIB_E_P_RFORMATERR ERR_MASK_N(RcvFormatErr)

#define QIB_E_P_SDMA1STDESC ERR_MASK_N(SDma1stDescErr)
#define QIB_E_P_SDMABASE ERR_MASK_N(SDmaBaseErr)
#define QIB_E_P_SDMADESCADDRMISALIGN ERR_MASK_N(SDmaDescAddrMisalignErr)
#define QIB_E_P_SDMADWEN ERR_MASK_N(SDmaDwEnErr)
#define QIB_E_P_SDMAGENMISMATCH ERR_MASK_N(SDmaGenMismatchErr)
#define QIB_E_P_SDMAHALT ERR_MASK_N(SDmaHaltErr)
#define QIB_E_P_SDMAMISSINGDW ERR_MASK_N(SDmaMissingDwErr)
#define QIB_E_P_SDMAOUTOFBOUND ERR_MASK_N(SDmaOutOfBoundErr)
#define QIB_E_P_SDMARPYTAG ERR_MASK_N(SDmaRpyTagErr)
#define QIB_E_P_SDMATAILOUTOFBOUND ERR_MASK_N(SDmaTailOutOfBoundErr)
#define QIB_E_P_SDMAUNEXPDATA ERR_MASK_N(SDmaUnexpDataErr)

/* Error bits that are common to a device */
#define QIB_E_RESET ERR_MASK(ResetNegated)
#define QIB_E_HARDWARE ERR_MASK(HardwareErr)
#define QIB_E_INVALIDADDR ERR_MASK(InvalidAddrErr)


/*
 * Per chip (rather than per-port) errors.  Most either do
 * nothing but trigger a print (because they self-recover, or
 * always occur in tandem with other errors that handle the
 * issue), or because they indicate errors with no recovery,
 * but we want to know that they happened.
 */
#define QIB_E_SBUF_VL15_MISUSE ERR_MASK(SBufVL15MisUseErr)
#define QIB_E_BADEEP ERR_MASK(InvalidEEPCmd)
#define QIB_E_VLMISMATCH ERR_MASK(SendVLMismatchErr)
#define QIB_E_ARMLAUNCH ERR_MASK(SendArmLaunchErr)
#define QIB_E_SPCLTRIG ERR_MASK(SendSpecialTriggerErr)
#define QIB_E_RRCVHDRFULL ERR_MASK(RcvHdrFullErr)
#define QIB_E_RRCVEGRFULL ERR_MASK(RcvEgrFullErr)
#define QIB_E_RCVCTXTSHARE ERR_MASK(RcvContextShareErr)

/* SDMA chip errors (not per port)
 * QIB_E_SDMA_BUF_DUP needs no special handling, because we will also get
 * the SDMAHALT error immediately, so we just print the dup error via the
 * E_AUTO mechanism.  This is true of most of the per-port fatal errors
 * as well, but since this is port-independent, by definition, it's
 * handled a bit differently.  SDMA_VL15 and SDMA_WRONG_PORT are per
 * packet send errors, and so are handled in the same manner as other
 * per-packet errors.
 */
#define QIB_E_SDMA_VL15 ERR_MASK(SDmaVL15Err)
#define QIB_E_SDMA_WRONG_PORT ERR_MASK(SDmaWrongPortErr)
#define QIB_E_SDMA_BUF_DUP ERR_MASK(SDmaBufMaskDuplicateErr)

/*
 * Below functionally equivalent to legacy QLOGIC_IB_E_PKTERRS
 * it is used to print "common" packet errors.
 */
#define QIB_E_P_PKTERRS (QIB_E_P_SPKTLEN |\
	QIB_E_P_SDROP_DATA | QIB_E_P_RVCRC |\
	QIB_E_P_RICRC | QIB_E_P_RSHORTPKTLEN |\
	QIB_E_P_VL15_BUF_MISUSE | QIB_E_P_SHDR | \
	QIB_E_P_REBP)

/* Error Bits that Packet-related (Receive, per-port) */
#define QIB_E_P_RPKTERRS (\
	QIB_E_P_RHDRLEN | QIB_E_P_RBADTID | \
	QIB_E_P_RBADVERSION | QIB_E_P_RHDR | \
	QIB_E_P_RLONGPKTLEN | QIB_E_P_RSHORTPKTLEN |\
	QIB_E_P_RMAXPKTLEN | QIB_E_P_RMINPKTLEN | \
	QIB_E_P_RFORMATERR | QIB_E_P_RUNSUPVL | \
	QIB_E_P_RUNEXPCHAR | QIB_E_P_RIBFLOW | QIB_E_P_REBP)

/*
 * Error bits that are Send-related (per port)
 * (ARMLAUNCH excluded from E_SPKTERRS because it gets special handling).
 * All of these potentially need to have a buffer disarmed
 */
#define QIB_E_P_SPKTERRS (\
	QIB_E_P_SUNEXP_PKTNUM |\
	QIB_E_P_SDROP_DATA | QIB_E_P_SDROP_SMP |\
	QIB_E_P_SMAXPKTLEN |\
	QIB_E_P_VL15_BUF_MISUSE | QIB_E_P_SHDR | \
	QIB_E_P_SMINPKTLEN | QIB_E_P_SPKTLEN | \
	QIB_E_P_SND_BUF_MISUSE | QIB_E_P_SUNSUPVL)

#define QIB_E_SPKTERRS ( \
		QIB_E_SBUF_VL15_MISUSE | QIB_E_VLMISMATCH | \
		ERR_MASK_N(SendUnsupportedVLErr) |			\
		QIB_E_SPCLTRIG | QIB_E_SDMA_VL15 | QIB_E_SDMA_WRONG_PORT)

#define QIB_E_P_SDMAERRS ( \
	QIB_E_P_SDMAHALT | \
	QIB_E_P_SDMADESCADDRMISALIGN | \
	QIB_E_P_SDMAUNEXPDATA | \
	QIB_E_P_SDMAMISSINGDW | \
	QIB_E_P_SDMADWEN | \
	QIB_E_P_SDMARPYTAG | \
	QIB_E_P_SDMA1STDESC | \
	QIB_E_P_SDMABASE | \
	QIB_E_P_SDMATAILOUTOFBOUND | \
	QIB_E_P_SDMAOUTOFBOUND | \
	QIB_E_P_SDMAGENMISMATCH)

/*
 * This sets some bits more than once, but makes it more obvious which
 * bits are not handled under other categories, and the repeat definition
 * is not a problem.
 */
#define QIB_E_P_BITSEXTANT ( \
	QIB_E_P_SPKTERRS | QIB_E_P_PKTERRS | QIB_E_P_RPKTERRS | \
	QIB_E_P_RIBLOSTLINK | QIB_E_P_IBSTATUSCHANGED | \
	QIB_E_P_SND_BUF_MISUSE | QIB_E_P_SUNDERRUN | \
	QIB_E_P_SHDR | QIB_E_P_VL15_BUF_MISUSE | QIB_E_P_SDMAERRS \
	)

/*
 * These are errors that can occur when the link
 * changes state while a packet is being sent or received.  This doesn't
 * cover things like EBP or VCRC that can be the result of a sending
 * having the link change state, so we receive a "known bad" packet.
 * All of these are "per port", so renamed:
 */
#define QIB_E_P_LINK_PKTERRS (\
	QIB_E_P_SDROP_DATA | QIB_E_P_SDROP_SMP |\
	QIB_E_P_SMINPKTLEN | QIB_E_P_SPKTLEN |\
	QIB_E_P_RSHORTPKTLEN | QIB_E_P_RMINPKTLEN |\
	QIB_E_P_RUNEXPCHAR)

/*
 * This sets some bits more than once, but makes it more obvious which
 * bits are not handled under other categories (such as QIB_E_SPKTERRS),
 * and the repeat definition is not a problem.
 */
#define QIB_E_C_BITSEXTANT (\
	QIB_E_HARDWARE | QIB_E_INVALIDADDR | QIB_E_BADEEP |\
	QIB_E_ARMLAUNCH | QIB_E_VLMISMATCH | QIB_E_RRCVHDRFULL |\
	QIB_E_RRCVEGRFULL | QIB_E_RESET | QIB_E_SBUF_VL15_MISUSE)

/* Likewise Neuter E_SPKT_ERRS_IGNORE */
#define E_SPKT_ERRS_IGNORE 0

#define QIB_EXTS_MEMBIST_DISABLED \
	SYM_MASK(EXTStatus, MemBISTDisabled)
#define QIB_EXTS_MEMBIST_ENDTEST \
	SYM_MASK(EXTStatus, MemBISTEndTest)

#define QIB_E_SPIOARMLAUNCH \
	ERR_MASK(SendArmLaunchErr)

#define IBA7322_IBCC_LINKINITCMD_MASK SYM_RMASK(IBCCtrlA_0, LinkInitCmd)
#define IBA7322_IBCC_LINKCMD_SHIFT SYM_LSB(IBCCtrlA_0, LinkCmd)

/*
 * IBTA_1_2 is set when multiple speeds are enabled (normal),
 * and also if forced QDR (only QDR enabled).  It's enabled for the
 * forced QDR case so that scrambling will be enabled by the TS3
 * exchange, when supported by both sides of the link.
 */
#define IBA7322_IBC_IBTA_1_2_MASK SYM_MASK(IBCCtrlB_0, IB_ENHANCED_MODE)
#define IBA7322_IBC_MAX_SPEED_MASK SYM_MASK(IBCCtrlB_0, SD_SPEED)
#define IBA7322_IBC_SPEED_QDR SYM_MASK(IBCCtrlB_0, SD_SPEED_QDR)
#define IBA7322_IBC_SPEED_DDR SYM_MASK(IBCCtrlB_0, SD_SPEED_DDR)
#define IBA7322_IBC_SPEED_SDR SYM_MASK(IBCCtrlB_0, SD_SPEED_SDR)
#define IBA7322_IBC_SPEED_MASK (SYM_MASK(IBCCtrlB_0, SD_SPEED_SDR) | \
	SYM_MASK(IBCCtrlB_0, SD_SPEED_DDR) | SYM_MASK(IBCCtrlB_0, SD_SPEED_QDR))
#define IBA7322_IBC_SPEED_LSB SYM_LSB(IBCCtrlB_0, SD_SPEED_SDR)

#define IBA7322_LEDBLINK_OFF_SHIFT SYM_LSB(RcvPktLEDCnt_0, OFFperiod)
#define IBA7322_LEDBLINK_ON_SHIFT SYM_LSB(RcvPktLEDCnt_0, ONperiod)

#define IBA7322_IBC_WIDTH_AUTONEG SYM_MASK(IBCCtrlB_0, IB_NUM_CHANNELS)
#define IBA7322_IBC_WIDTH_4X_ONLY (1<<SYM_LSB(IBCCtrlB_0, IB_NUM_CHANNELS))
#define IBA7322_IBC_WIDTH_1X_ONLY (0<<SYM_LSB(IBCCtrlB_0, IB_NUM_CHANNELS))

#define IBA7322_IBC_RXPOL_MASK SYM_MASK(IBCCtrlB_0, IB_POLARITY_REV_SUPP)
#define IBA7322_IBC_RXPOL_LSB SYM_LSB(IBCCtrlB_0, IB_POLARITY_REV_SUPP)
#define IBA7322_IBC_HRTBT_MASK (SYM_MASK(IBCCtrlB_0, HRTBT_AUTO) | \
	SYM_MASK(IBCCtrlB_0, HRTBT_ENB))
#define IBA7322_IBC_HRTBT_RMASK (IBA7322_IBC_HRTBT_MASK >> \
	SYM_LSB(IBCCtrlB_0, HRTBT_ENB))
#define IBA7322_IBC_HRTBT_LSB SYM_LSB(IBCCtrlB_0, HRTBT_ENB)

#define IBA7322_REDIRECT_VEC_PER_REG 12

#define IBA7322_SENDCHK_PKEY SYM_MASK(SendCheckControl_0, PKey_En)
#define IBA7322_SENDCHK_BTHQP SYM_MASK(SendCheckControl_0, BTHQP_En)
#define IBA7322_SENDCHK_SLID SYM_MASK(SendCheckControl_0, SLID_En)
#define IBA7322_SENDCHK_RAW_IPV6 SYM_MASK(SendCheckControl_0, RawIPV6_En)
#define IBA7322_SENDCHK_MINSZ SYM_MASK(SendCheckControl_0, PacketTooSmall_En)

#define AUTONEG_TRIES 3 /* sequential retries to negotiate DDR */

#define HWE_AUTO(fldname) { .mask = SYM_MASK(HwErrMask, fldname##Mask), \
	.msg = #fldname , .sz = sizeof(#fldname) }
#define HWE_AUTO_P(fldname, port) { .mask = SYM_MASK(HwErrMask, \
	fldname##Mask##_##port), .msg = #fldname , .sz = sizeof(#fldname) }
static const struct qib_hwerror_msgs qib_7322_hwerror_msgs[] = {
	HWE_AUTO_P(IBSerdesPClkNotDetect, 1),
	HWE_AUTO_P(IBSerdesPClkNotDetect, 0),
	HWE_AUTO(PCIESerdesPClkNotDetect),
	HWE_AUTO(PowerOnBISTFailed),
	HWE_AUTO(TempsenseTholdReached),
	HWE_AUTO(MemoryErr),
	HWE_AUTO(PCIeBusParityErr),
	HWE_AUTO(PcieCplTimeout),
	HWE_AUTO(PciePoisonedTLP),
	HWE_AUTO_P(SDmaMemReadErr, 1),
	HWE_AUTO_P(SDmaMemReadErr, 0),
	HWE_AUTO_P(IBCBusFromSPCParityErr, 1),
	HWE_AUTO_P(IBCBusToSPCParityErr, 1),
	HWE_AUTO_P(IBCBusFromSPCParityErr, 0),
	HWE_AUTO(statusValidNoEop),
	HWE_AUTO(LATriggered),
	{ .mask = 0, .sz = 0 }
};

#define E_AUTO(fldname) { .mask = SYM_MASK(ErrMask, fldname##Mask), \
	.msg = #fldname, .sz = sizeof(#fldname) }
#define E_P_AUTO(fldname) { .mask = SYM_MASK(ErrMask_0, fldname##Mask), \
	.msg = #fldname, .sz = sizeof(#fldname) }
static const struct qib_hwerror_msgs qib_7322error_msgs[] = {
	E_AUTO(RcvEgrFullErr),
	E_AUTO(RcvHdrFullErr),
	E_AUTO(ResetNegated),
	E_AUTO(HardwareErr),
	E_AUTO(InvalidAddrErr),
	E_AUTO(SDmaVL15Err),
	E_AUTO(SBufVL15MisUseErr),
	E_AUTO(InvalidEEPCmd),
	E_AUTO(RcvContextShareErr),
	E_AUTO(SendVLMismatchErr),
	E_AUTO(SendArmLaunchErr),
	E_AUTO(SendSpecialTriggerErr),
	E_AUTO(SDmaWrongPortErr),
	E_AUTO(SDmaBufMaskDuplicateErr),
	{ .mask = 0, .sz = 0 }
};

static const struct  qib_hwerror_msgs qib_7322p_error_msgs[] = {
	E_P_AUTO(IBStatusChanged),
	E_P_AUTO(SHeadersErr),
	E_P_AUTO(VL15BufMisuseErr),
	/*
	 * SDmaHaltErr is not really an error, make it clearer;
	 */
	{.mask = SYM_MASK(ErrMask_0, SDmaHaltErrMask), .msg = "SDmaHalted",
		.sz = 11},
	E_P_AUTO(SDmaDescAddrMisalignErr),
	E_P_AUTO(SDmaUnexpDataErr),
	E_P_AUTO(SDmaMissingDwErr),
	E_P_AUTO(SDmaDwEnErr),
	E_P_AUTO(SDmaRpyTagErr),
	E_P_AUTO(SDma1stDescErr),
	E_P_AUTO(SDmaBaseErr),
	E_P_AUTO(SDmaTailOutOfBoundErr),
	E_P_AUTO(SDmaOutOfBoundErr),
	E_P_AUTO(SDmaGenMismatchErr),
	E_P_AUTO(SendBufMisuseErr),
	E_P_AUTO(SendUnsupportedVLErr),
	E_P_AUTO(SendUnexpectedPktNumErr),
	E_P_AUTO(SendDroppedDataPktErr),
	E_P_AUTO(SendDroppedSmpPktErr),
	E_P_AUTO(SendPktLenErr),
	E_P_AUTO(SendUnderRunErr),
	E_P_AUTO(SendMaxPktLenErr),
	E_P_AUTO(SendMinPktLenErr),
	E_P_AUTO(RcvIBLostLinkErr),
	E_P_AUTO(RcvHdrErr),
	E_P_AUTO(RcvHdrLenErr),
	E_P_AUTO(RcvBadTidErr),
	E_P_AUTO(RcvBadVersionErr),
	E_P_AUTO(RcvIBFlowErr),
	E_P_AUTO(RcvEBPErr),
	E_P_AUTO(RcvUnsupportedVLErr),
	E_P_AUTO(RcvUnexpectedCharErr),
	E_P_AUTO(RcvShortPktLenErr),
	E_P_AUTO(RcvLongPktLenErr),
	E_P_AUTO(RcvMaxPktLenErr),
	E_P_AUTO(RcvMinPktLenErr),
	E_P_AUTO(RcvICRCErr),
	E_P_AUTO(RcvVCRCErr),
	E_P_AUTO(RcvFormatErr),
	{ .mask = 0, .sz = 0 }
};

/*
 * Below generates "auto-message" for interrupts not specific to any port or
 * context
 */
#define INTR_AUTO(fldname) { .mask = SYM_MASK(IntMask, fldname##Mask), \
	.msg = #fldname, .sz = sizeof(#fldname) }
/* Below generates "auto-message" for interrupts specific to a port */
#define INTR_AUTO_P(fldname) { .mask = MASK_ACROSS(\
	SYM_LSB(IntMask, fldname##Mask##_0), \
	SYM_LSB(IntMask, fldname##Mask##_1)), \
	.msg = #fldname "_P", .sz = sizeof(#fldname "_P") }
/* For some reason, the SerDesTrimDone bits are reversed */
#define INTR_AUTO_PI(fldname) { .mask = MASK_ACROSS(\
	SYM_LSB(IntMask, fldname##Mask##_1), \
	SYM_LSB(IntMask, fldname##Mask##_0)), \
	.msg = #fldname "_P", .sz = sizeof(#fldname "_P") }
/*
 * Below generates "auto-message" for interrupts specific to a context,
 * with ctxt-number appended
 */
#define INTR_AUTO_C(fldname) { .mask = MASK_ACROSS(\
	SYM_LSB(IntMask, fldname##0IntMask), \
	SYM_LSB(IntMask, fldname##17IntMask)), \
	.msg = #fldname "_C", .sz = sizeof(#fldname "_C") }

static const struct  qib_hwerror_msgs qib_7322_intr_msgs[] = {
	INTR_AUTO_P(SDmaInt),
	INTR_AUTO_P(SDmaProgressInt),
	INTR_AUTO_P(SDmaIdleInt),
	INTR_AUTO_P(SDmaCleanupDone),
	INTR_AUTO_C(RcvUrg),
	INTR_AUTO_P(ErrInt),
	INTR_AUTO(ErrInt),      /* non-port-specific errs */
	INTR_AUTO(AssertGPIOInt),
	INTR_AUTO_P(SendDoneInt),
	INTR_AUTO(SendBufAvailInt),
	INTR_AUTO_C(RcvAvail),
	{ .mask = 0, .sz = 0 }
};

#define TXSYMPTOM_AUTO_P(fldname) \
	{ .mask = SYM_MASK(SendHdrErrSymptom_0, fldname), \
	.msg = #fldname, .sz = sizeof(#fldname) }
static const struct  qib_hwerror_msgs hdrchk_msgs[] = {
	TXSYMPTOM_AUTO_P(NonKeyPacket),
	TXSYMPTOM_AUTO_P(GRHFail),
	TXSYMPTOM_AUTO_P(PkeyFail),
	TXSYMPTOM_AUTO_P(QPFail),
	TXSYMPTOM_AUTO_P(SLIDFail),
	TXSYMPTOM_AUTO_P(RawIPV6),
	TXSYMPTOM_AUTO_P(PacketTooSmall),
	{ .mask = 0, .sz = 0 }
};

#define IBA7322_HDRHEAD_PKTINT_SHIFT 32 /* interrupt cnt in upper 32 bits */

/*
 * Called when we might have an error that is specific to a particular
 * PIO buffer, and may need to cancel that buffer, so it can be re-used,
 * because we don't need to force the update of pioavail
 */
static void qib_disarm_7322_senderrbufs(struct qib_pportdata *ppd)
{
	struct qib_devdata *dd = ppd->dd;
	u32 i;
	int any;
	u32 piobcnt = dd->piobcnt2k + dd->piobcnt4k + NUM_VL15_BUFS;
	u32 regcnt = (piobcnt + BITS_PER_LONG - 1) / BITS_PER_LONG;
	unsigned long sbuf[4];

	/*
	 * It's possible that sendbuffererror could have bits set; might
	 * have already done this as a result of hardware error handling.
	 */
	any = 0;
	for (i = 0; i < regcnt; ++i) {
		sbuf[i] = qib_read_kreg64(dd, kr_sendbuffererror + i);
		if (sbuf[i]) {
			any = 1;
			qib_write_kreg(dd, kr_sendbuffererror + i, sbuf[i]);
		}
	}

	if (any)
		qib_disarm_piobufs_set(dd, sbuf, piobcnt);
}

/* No txe_recover yet, if ever */

/* No decode__errors yet */
static void err_decode(char *msg, size_t len, u64 errs,
		       const struct qib_hwerror_msgs *msp)
{
	u64 these, lmask;
	int took, multi, n = 0;

	while (errs && msp && msp->mask) {
		multi = (msp->mask & (msp->mask - 1));
		while (errs & msp->mask) {
			these = (errs & msp->mask);
			lmask = (these & (these - 1)) ^ these;
			if (len) {
				if (n++) {
					/* separate the strings */
					*msg++ = ',';
					len--;
				}
				BUG_ON(!msp->sz);
				/* msp->sz counts the nul */
				took = min_t(size_t, msp->sz - (size_t)1, len);
				memcpy(msg,  msp->msg, took);
				len -= took;
				msg += took;
				if (len)
					*msg = '\0';
			}
			errs &= ~lmask;
			if (len && multi) {
				/* More than one bit this mask */
				int idx = -1;

				while (lmask & msp->mask) {
					++idx;
					lmask >>= 1;
				}
				took = scnprintf(msg, len, "_%d", idx);
				len -= took;
				msg += took;
			}
		}
		++msp;
	}
	/* If some bits are left, show in hex. */
	if (len && errs)
		snprintf(msg, len, "%sMORE:%llX", n ? "," : "",
			(unsigned long long) errs);
}

/* only called if r1 set */
static void flush_fifo(struct qib_pportdata *ppd)
{
	struct qib_devdata *dd = ppd->dd;
	u32 __iomem *piobuf;
	u32 bufn;
	u32 *hdr;
	u64 pbc;
	const unsigned hdrwords = 7;
	static struct qib_ib_header ibhdr = {
		.lrh[0] = cpu_to_be16(0xF000 | QIB_LRH_BTH),
		.lrh[1] = IB_LID_PERMISSIVE,
		.lrh[2] = cpu_to_be16(hdrwords + SIZE_OF_CRC),
		.lrh[3] = IB_LID_PERMISSIVE,
		.u.oth.bth[0] = cpu_to_be32(
			(IB_OPCODE_UD_SEND_ONLY << 24) | QIB_DEFAULT_P_KEY),
		.u.oth.bth[1] = cpu_to_be32(0),
		.u.oth.bth[2] = cpu_to_be32(0),
		.u.oth.u.ud.deth[0] = cpu_to_be32(0),
		.u.oth.u.ud.deth[1] = cpu_to_be32(0),
	};

	/*
	 * Send a dummy VL15 packet to flush the launch FIFO.
	 * This will not actually be sent since the TxeBypassIbc bit is set.
	 */
	pbc = PBC_7322_VL15_SEND |
		(((u64)ppd->hw_pidx) << (PBC_PORT_SEL_LSB + 32)) |
		(hdrwords + SIZE_OF_CRC);
	piobuf = qib_7322_getsendbuf(ppd, pbc, &bufn);
	if (!piobuf)
		return;
	writeq(pbc, piobuf);
	hdr = (u32 *) &ibhdr;
	if (dd->flags & QIB_PIO_FLUSH_WC) {
		qib_flush_wc();
		qib_pio_copy(piobuf + 2, hdr, hdrwords - 1);
		qib_flush_wc();
		__raw_writel(hdr[hdrwords - 1], piobuf + hdrwords + 1);
		qib_flush_wc();
	} else
		qib_pio_copy(piobuf + 2, hdr, hdrwords);
	qib_sendbuf_done(dd, bufn);
}

/*
 * This is called with interrupts disabled and sdma_lock held.
 */
static void qib_7322_sdma_sendctrl(struct qib_pportdata *ppd, unsigned op)
{
	struct qib_devdata *dd = ppd->dd;
	u64 set_sendctrl = 0;
	u64 clr_sendctrl = 0;

	if (op & QIB_SDMA_SENDCTRL_OP_ENABLE)
		set_sendctrl |= SYM_MASK(SendCtrl_0, SDmaEnable);
	else
		clr_sendctrl |= SYM_MASK(SendCtrl_0, SDmaEnable);

	if (op & QIB_SDMA_SENDCTRL_OP_INTENABLE)
		set_sendctrl |= SYM_MASK(SendCtrl_0, SDmaIntEnable);
	else
		clr_sendctrl |= SYM_MASK(SendCtrl_0, SDmaIntEnable);

	if (op & QIB_SDMA_SENDCTRL_OP_HALT)
		set_sendctrl |= SYM_MASK(SendCtrl_0, SDmaHalt);
	else
		clr_sendctrl |= SYM_MASK(SendCtrl_0, SDmaHalt);

	if (op & QIB_SDMA_SENDCTRL_OP_DRAIN)
		set_sendctrl |= SYM_MASK(SendCtrl_0, TxeBypassIbc) |
				SYM_MASK(SendCtrl_0, TxeAbortIbc) |
				SYM_MASK(SendCtrl_0, TxeDrainRmFifo);
	else
		clr_sendctrl |= SYM_MASK(SendCtrl_0, TxeBypassIbc) |
				SYM_MASK(SendCtrl_0, TxeAbortIbc) |
				SYM_MASK(SendCtrl_0, TxeDrainRmFifo);

	spin_lock(&dd->sendctrl_lock);

	/* If we are draining everything, block sends first */
	if (op & QIB_SDMA_SENDCTRL_OP_DRAIN) {
		ppd->p_sendctrl &= ~SYM_MASK(SendCtrl_0, SendEnable);
		qib_write_kreg_port(ppd, krp_sendctrl, ppd->p_sendctrl);
		qib_write_kreg(dd, kr_scratch, 0);
	}

	ppd->p_sendctrl |= set_sendctrl;
	ppd->p_sendctrl &= ~clr_sendctrl;

	if (op & QIB_SDMA_SENDCTRL_OP_CLEANUP)
		qib_write_kreg_port(ppd, krp_sendctrl,
				    ppd->p_sendctrl |
				    SYM_MASK(SendCtrl_0, SDmaCleanup));
	else
		qib_write_kreg_port(ppd, krp_sendctrl, ppd->p_sendctrl);
	qib_write_kreg(dd, kr_scratch, 0);

	if (op & QIB_SDMA_SENDCTRL_OP_DRAIN) {
		ppd->p_sendctrl |= SYM_MASK(SendCtrl_0, SendEnable);
		qib_write_kreg_port(ppd, krp_sendctrl, ppd->p_sendctrl);
		qib_write_kreg(dd, kr_scratch, 0);
	}

	spin_unlock(&dd->sendctrl_lock);

	if ((op & QIB_SDMA_SENDCTRL_OP_DRAIN) && ppd->dd->cspec->r1)
		flush_fifo(ppd);
}

static void qib_7322_sdma_hw_clean_up(struct qib_pportdata *ppd)
{
	__qib_sdma_process_event(ppd, qib_sdma_event_e50_hw_cleaned);
}

static void qib_sdma_7322_setlengen(struct qib_pportdata *ppd)
{
	/*
	 * Set SendDmaLenGen and clear and set
	 * the MSB of the generation count to enable generation checking
	 * and load the internal generation counter.
	 */
	qib_write_kreg_port(ppd, krp_senddmalengen, ppd->sdma_descq_cnt);
	qib_write_kreg_port(ppd, krp_senddmalengen,
			    ppd->sdma_descq_cnt |
			    (1ULL << QIB_7322_SendDmaLenGen_0_Generation_MSB));
}

/*
 * Must be called with sdma_lock held, or before init finished.
 */
static void qib_sdma_update_7322_tail(struct qib_pportdata *ppd, u16 tail)
{
	/* Commit writes to memory and advance the tail on the chip */
	wmb();
	ppd->sdma_descq_tail = tail;
	qib_write_kreg_port(ppd, krp_senddmatail, tail);
}

/*
 * This is called with interrupts disabled and sdma_lock held.
 */
static void qib_7322_sdma_hw_start_up(struct qib_pportdata *ppd)
{
	/*
	 * Drain all FIFOs.
	 * The hardware doesn't require this but we do it so that verbs
	 * and user applications don't wait for link active to send stale
	 * data.
	 */
	sendctrl_7322_mod(ppd, QIB_SENDCTRL_FLUSH);

	qib_sdma_7322_setlengen(ppd);
	qib_sdma_update_7322_tail(ppd, 0); /* Set SendDmaTail */
	ppd->sdma_head_dma[0] = 0;
	qib_7322_sdma_sendctrl(ppd,
		ppd->sdma_state.current_op | QIB_SDMA_SENDCTRL_OP_CLEANUP);
}

#define DISABLES_SDMA ( \
	QIB_E_P_SDMAHALT | \
	QIB_E_P_SDMADESCADDRMISALIGN | \
	QIB_E_P_SDMAMISSINGDW | \
	QIB_E_P_SDMADWEN | \
	QIB_E_P_SDMARPYTAG | \
	QIB_E_P_SDMA1STDESC | \
	QIB_E_P_SDMABASE | \
	QIB_E_P_SDMATAILOUTOFBOUND | \
	QIB_E_P_SDMAOUTOFBOUND | \
	QIB_E_P_SDMAGENMISMATCH)

static void sdma_7322_p_errors(struct qib_pportdata *ppd, u64 errs)
{
	unsigned long flags;
	struct qib_devdata *dd = ppd->dd;

	errs &= QIB_E_P_SDMAERRS;

	if (errs & QIB_E_P_SDMAUNEXPDATA)
		qib_dev_err(dd, "IB%u:%u SDmaUnexpData\n", dd->unit,
			    ppd->port);

	spin_lock_irqsave(&ppd->sdma_lock, flags);

	switch (ppd->sdma_state.current_state) {
	case qib_sdma_state_s00_hw_down:
		break;

	case qib_sdma_state_s10_hw_start_up_wait:
		if (errs & QIB_E_P_SDMAHALT)
			__qib_sdma_process_event(ppd,
				qib_sdma_event_e20_hw_started);
		break;

	case qib_sdma_state_s20_idle:
		break;

	case qib_sdma_state_s30_sw_clean_up_wait:
		break;

	case qib_sdma_state_s40_hw_clean_up_wait:
		if (errs & QIB_E_P_SDMAHALT)
			__qib_sdma_process_event(ppd,
				qib_sdma_event_e50_hw_cleaned);
		break;

	case qib_sdma_state_s50_hw_halt_wait:
		if (errs & QIB_E_P_SDMAHALT)
			__qib_sdma_process_event(ppd,
				qib_sdma_event_e60_hw_halted);
		break;

	case qib_sdma_state_s99_running:
		__qib_sdma_process_event(ppd, qib_sdma_event_e7322_err_halted);
		__qib_sdma_process_event(ppd, qib_sdma_event_e60_hw_halted);
		break;
	}

	spin_unlock_irqrestore(&ppd->sdma_lock, flags);
}

/*
 * handle per-device errors (not per-port errors)
 */
static noinline void handle_7322_errors(struct qib_devdata *dd)
{
	char *msg;
	u64 iserr = 0;
	u64 errs;
	u64 mask;
	int log_idx;

	qib_stats.sps_errints++;
	errs = qib_read_kreg64(dd, kr_errstatus);
	if (!errs) {
		qib_devinfo(dd->pcidev,
			"device error interrupt, but no error bits set!\n");
		goto done;
	}

	/* don't report errors that are masked */
	errs &= dd->cspec->errormask;
	msg = dd->cspec->emsgbuf;

	/* do these first, they are most important */
	if (errs & QIB_E_HARDWARE) {
		*msg = '\0';
		qib_7322_handle_hwerrors(dd, msg, sizeof dd->cspec->emsgbuf);
	} else
		for (log_idx = 0; log_idx < QIB_EEP_LOG_CNT; ++log_idx)
			if (errs & dd->eep_st_masks[log_idx].errs_to_log)
				qib_inc_eeprom_err(dd, log_idx, 1);

	if (errs & QIB_E_SPKTERRS) {
		qib_disarm_7322_senderrbufs(dd->pport);
		qib_stats.sps_txerrs++;
	} else if (errs & QIB_E_INVALIDADDR)
		qib_stats.sps_txerrs++;
	else if (errs & QIB_E_ARMLAUNCH) {
		qib_stats.sps_txerrs++;
		qib_disarm_7322_senderrbufs(dd->pport);
	}
	qib_write_kreg(dd, kr_errclear, errs);

	/*
	 * The ones we mask off are handled specially below
	 * or above.  Also mask SDMADISABLED by default as it
	 * is too chatty.
	 */
	mask = QIB_E_HARDWARE;
	*msg = '\0';

	err_decode(msg, sizeof dd->cspec->emsgbuf, errs & ~mask,
		   qib_7322error_msgs);

	/*
	 * Getting reset is a tragedy for all ports. Mark the device
	 * _and_ the ports as "offline" in way meaningful to each.
	 */
	if (errs & QIB_E_RESET) {
		int pidx;

		qib_dev_err(dd,
			"Got reset, requires re-init (unload and reload driver)\n");
		dd->flags &= ~QIB_INITTED;  /* needs re-init */
		/* mark as having had error */
		*dd->devstatusp |= QIB_STATUS_HWERROR;
		for (pidx = 0; pidx < dd->num_pports; ++pidx)
			if (dd->pport[pidx].link_speed_supported)
				*dd->pport[pidx].statusp &= ~QIB_STATUS_IB_CONF;
	}

	if (*msg && iserr)
		qib_dev_err(dd, "%s error\n", msg);

	/*
	 * If there were hdrq or egrfull errors, wake up any processes
	 * waiting in poll.  We used to try to check which contexts had
	 * the overflow, but given the cost of that and the chip reads
	 * to support it, it's better to just wake everybody up if we
	 * get an overflow; waiters can poll again if it's not them.
	 */
	if (errs & (ERR_MASK(RcvEgrFullErr) | ERR_MASK(RcvHdrFullErr))) {
		qib_handle_urcv(dd, ~0U);
		if (errs & ERR_MASK(RcvEgrFullErr))
			qib_stats.sps_buffull++;
		else
			qib_stats.sps_hdrfull++;
	}

done:
	return;
}

static void qib_error_tasklet(unsigned long data)
{
	struct qib_devdata *dd = (struct qib_devdata *)data;

	handle_7322_errors(dd);
	qib_write_kreg(dd, kr_errmask, dd->cspec->errormask);
}

static void reenable_chase(unsigned long opaque)
{
	struct qib_pportdata *ppd = (struct qib_pportdata *)opaque;

	ppd->cpspec->chase_timer.expires = 0;
	qib_set_ib_7322_lstate(ppd, QLOGIC_IB_IBCC_LINKCMD_DOWN,
		QLOGIC_IB_IBCC_LINKINITCMD_POLL);
}

static void disable_chase(struct qib_pportdata *ppd, unsigned long tnow,
		u8 ibclt)
{
	ppd->cpspec->chase_end = 0;

	if (!qib_chase)
		return;

	qib_set_ib_7322_lstate(ppd, QLOGIC_IB_IBCC_LINKCMD_DOWN,
		QLOGIC_IB_IBCC_LINKINITCMD_DISABLE);
	ppd->cpspec->chase_timer.expires = jiffies + QIB_CHASE_DIS_TIME;
	add_timer(&ppd->cpspec->chase_timer);
}

static void handle_serdes_issues(struct qib_pportdata *ppd, u64 ibcst)
{
	u8 ibclt;
	unsigned long tnow;

	ibclt = (u8)SYM_FIELD(ibcst, IBCStatusA_0, LinkTrainingState);

	/*
	 * Detect and handle the state chase issue, where we can
	 * get stuck if we are unlucky on timing on both sides of
	 * the link.   If we are, we disable, set a timer, and
	 * then re-enable.
	 */
	switch (ibclt) {
	case IB_7322_LT_STATE_CFGRCVFCFG:
	case IB_7322_LT_STATE_CFGWAITRMT:
	case IB_7322_LT_STATE_TXREVLANES:
	case IB_7322_LT_STATE_CFGENH:
		tnow = jiffies;
		if (ppd->cpspec->chase_end &&
		     time_after(tnow, ppd->cpspec->chase_end))
			disable_chase(ppd, tnow, ibclt);
		else if (!ppd->cpspec->chase_end)
			ppd->cpspec->chase_end = tnow + QIB_CHASE_TIME;
		break;
	default:
		ppd->cpspec->chase_end = 0;
		break;
	}

	if (((ibclt >= IB_7322_LT_STATE_CFGTEST &&
	      ibclt <= IB_7322_LT_STATE_CFGWAITENH) ||
	     ibclt == IB_7322_LT_STATE_LINKUP) &&
	    (ibcst & SYM_MASK(IBCStatusA_0, LinkSpeedQDR))) {
		force_h1(ppd);
		ppd->cpspec->qdr_reforce = 1;
		if (!ppd->dd->cspec->r1)
			serdes_7322_los_enable(ppd, 0);
	} else if (ppd->cpspec->qdr_reforce &&
		(ibcst & SYM_MASK(IBCStatusA_0, LinkSpeedQDR)) &&
		 (ibclt == IB_7322_LT_STATE_CFGENH ||
		ibclt == IB_7322_LT_STATE_CFGIDLE ||
		ibclt == IB_7322_LT_STATE_LINKUP))
		force_h1(ppd);

	if ((IS_QMH(ppd->dd) || IS_QME(ppd->dd)) &&
	    ppd->link_speed_enabled == QIB_IB_QDR &&
	    (ibclt == IB_7322_LT_STATE_CFGTEST ||
	     ibclt == IB_7322_LT_STATE_CFGENH ||
	     (ibclt >= IB_7322_LT_STATE_POLLACTIVE &&
	      ibclt <= IB_7322_LT_STATE_SLEEPQUIET)))
		adj_tx_serdes(ppd);

	if (ibclt != IB_7322_LT_STATE_LINKUP) {
		u8 ltstate = qib_7322_phys_portstate(ibcst);
		u8 pibclt = (u8)SYM_FIELD(ppd->lastibcstat, IBCStatusA_0,
					  LinkTrainingState);
		if (!ppd->dd->cspec->r1 &&
		    pibclt == IB_7322_LT_STATE_LINKUP &&
		    ltstate != IB_PHYSPORTSTATE_LINK_ERR_RECOVER &&
		    ltstate != IB_PHYSPORTSTATE_RECOVERY_RETRAIN &&
		    ltstate != IB_PHYSPORTSTATE_RECOVERY_WAITRMT &&
		    ltstate != IB_PHYSPORTSTATE_RECOVERY_IDLE)
			/* If the link went down (but no into recovery,
			 * turn LOS back on */
			serdes_7322_los_enable(ppd, 1);
		if (!ppd->cpspec->qdr_dfe_on &&
		    ibclt <= IB_7322_LT_STATE_SLEEPQUIET) {
			ppd->cpspec->qdr_dfe_on = 1;
			ppd->cpspec->qdr_dfe_time = 0;
			/* On link down, reenable QDR adaptation */
			qib_write_kreg_port(ppd, krp_static_adapt_dis(2),
					    ppd->dd->cspec->r1 ?
					    QDR_STATIC_ADAPT_DOWN_R1 :
					    QDR_STATIC_ADAPT_DOWN);
			pr_info(
				"IB%u:%u re-enabled QDR adaptation ibclt %x\n",
				ppd->dd->unit, ppd->port, ibclt);
		}
	}
}

static int qib_7322_set_ib_cfg(struct qib_pportdata *, int, u32);

/*
 * This is per-pport error handling.
 * will likely get it's own MSIx interrupt (one for each port,
 * although just a single handler).
 */
static noinline void handle_7322_p_errors(struct qib_pportdata *ppd)
{
	char *msg;
	u64 ignore_this_time = 0, iserr = 0, errs, fmask;
	struct qib_devdata *dd = ppd->dd;

	/* do this as soon as possible */
	fmask = qib_read_kreg64(dd, kr_act_fmask);
	if (!fmask)
		check_7322_rxe_status(ppd);

	errs = qib_read_kreg_port(ppd, krp_errstatus);
	if (!errs)
		qib_devinfo(dd->pcidev,
			 "Port%d error interrupt, but no error bits set!\n",
			 ppd->port);
	if (!fmask)
		errs &= ~QIB_E_P_IBSTATUSCHANGED;
	if (!errs)
		goto done;

	msg = ppd->cpspec->epmsgbuf;
	*msg = '\0';

	if (errs & ~QIB_E_P_BITSEXTANT) {
		err_decode(msg, sizeof ppd->cpspec->epmsgbuf,
			   errs & ~QIB_E_P_BITSEXTANT, qib_7322p_error_msgs);
		if (!*msg)
			snprintf(msg, sizeof ppd->cpspec->epmsgbuf,
				 "no others");
		qib_dev_porterr(dd, ppd->port,
			"error interrupt with unknown errors 0x%016Lx set (and %s)\n",
			(errs & ~QIB_E_P_BITSEXTANT), msg);
		*msg = '\0';
	}

	if (errs & QIB_E_P_SHDR) {
		u64 symptom;

		/* determine cause, then write to clear */
		symptom = qib_read_kreg_port(ppd, krp_sendhdrsymptom);
		qib_write_kreg_port(ppd, krp_sendhdrsymptom, 0);
		err_decode(msg, sizeof ppd->cpspec->epmsgbuf, symptom,
			   hdrchk_msgs);
		*msg = '\0';
		/* senderrbuf cleared in SPKTERRS below */
	}

	if (errs & QIB_E_P_SPKTERRS) {
		if ((errs & QIB_E_P_LINK_PKTERRS) &&
		    !(ppd->lflags & QIBL_LINKACTIVE)) {
			/*
			 * This can happen when trying to bring the link
			 * up, but the IB link changes state at the "wrong"
			 * time. The IB logic then complains that the packet
			 * isn't valid.  We don't want to confuse people, so
			 * we just don't print them, except at debug
			 */
			err_decode(msg, sizeof ppd->cpspec->epmsgbuf,
				   (errs & QIB_E_P_LINK_PKTERRS),
				   qib_7322p_error_msgs);
			*msg = '\0';
			ignore_this_time = errs & QIB_E_P_LINK_PKTERRS;
		}
		qib_disarm_7322_senderrbufs(ppd);
	} else if ((errs & QIB_E_P_LINK_PKTERRS) &&
		   !(ppd->lflags & QIBL_LINKACTIVE)) {
		/*
		 * This can happen when SMA is trying to bring the link
		 * up, but the IB link changes state at the "wrong" time.
		 * The IB logic then complains that the packet isn't
		 * valid.  We don't want to confuse people, so we just
		 * don't print them, except at debug
		 */
		err_decode(msg, sizeof ppd->cpspec->epmsgbuf, errs,
			   qib_7322p_error_msgs);
		ignore_this_time = errs & QIB_E_P_LINK_PKTERRS;
		*msg = '\0';
	}

	qib_write_kreg_port(ppd, krp_errclear, errs);

	errs &= ~ignore_this_time;
	if (!errs)
		goto done;

	if (errs & QIB_E_P_RPKTERRS)
		qib_stats.sps_rcverrs++;
	if (errs & QIB_E_P_SPKTERRS)
		qib_stats.sps_txerrs++;

	iserr = errs & ~(QIB_E_P_RPKTERRS | QIB_E_P_PKTERRS);

	if (errs & QIB_E_P_SDMAERRS)
		sdma_7322_p_errors(ppd, errs);

	if (errs & QIB_E_P_IBSTATUSCHANGED) {
		u64 ibcs;
		u8 ltstate;

		ibcs = qib_read_kreg_port(ppd, krp_ibcstatus_a);
		ltstate = qib_7322_phys_portstate(ibcs);

		if (!(ppd->lflags & QIBL_IB_AUTONEG_INPROG))
			handle_serdes_issues(ppd, ibcs);
		if (!(ppd->cpspec->ibcctrl_a &
		      SYM_MASK(IBCCtrlA_0, IBStatIntReductionEn))) {
			/*
			 * We got our interrupt, so init code should be
			 * happy and not try alternatives. Now squelch
			 * other "chatter" from link-negotiation (pre Init)
			 */
			ppd->cpspec->ibcctrl_a |=
				SYM_MASK(IBCCtrlA_0, IBStatIntReductionEn);
			qib_write_kreg_port(ppd, krp_ibcctrl_a,
					    ppd->cpspec->ibcctrl_a);
		}

		/* Update our picture of width and speed from chip */
		ppd->link_width_active =
			(ibcs & SYM_MASK(IBCStatusA_0, LinkWidthActive)) ?
			    IB_WIDTH_4X : IB_WIDTH_1X;
		ppd->link_speed_active = (ibcs & SYM_MASK(IBCStatusA_0,
			LinkSpeedQDR)) ? QIB_IB_QDR : (ibcs &
			  SYM_MASK(IBCStatusA_0, LinkSpeedActive)) ?
				   QIB_IB_DDR : QIB_IB_SDR;

		if ((ppd->lflags & QIBL_IB_LINK_DISABLED) && ltstate !=
		    IB_PHYSPORTSTATE_DISABLED)
			qib_set_ib_7322_lstate(ppd, 0,
			       QLOGIC_IB_IBCC_LINKINITCMD_DISABLE);
		else
			/*
			 * Since going into a recovery state causes the link
			 * state to go down and since recovery is transitory,
			 * it is better if we "miss" ever seeing the link
			 * training state go into recovery (i.e., ignore this
			 * transition for link state special handling purposes)
			 * without updating lastibcstat.
			 */
			if (ltstate != IB_PHYSPORTSTATE_LINK_ERR_RECOVER &&
			    ltstate != IB_PHYSPORTSTATE_RECOVERY_RETRAIN &&
			    ltstate != IB_PHYSPORTSTATE_RECOVERY_WAITRMT &&
			    ltstate != IB_PHYSPORTSTATE_RECOVERY_IDLE)
				qib_handle_e_ibstatuschanged(ppd, ibcs);
	}
	if (*msg && iserr)
		qib_dev_porterr(dd, ppd->port, "%s error\n", msg);

	if (ppd->state_wanted & ppd->lflags)
		wake_up_interruptible(&ppd->state_wait);
done:
	return;
}

/* enable/disable chip from delivering interrupts */
static void qib_7322_set_intr_state(struct qib_devdata *dd, u32 enable)
{
	if (enable) {
		if (dd->flags & QIB_BADINTR)
			return;
		qib_write_kreg(dd, kr_intmask, dd->cspec->int_enable_mask);
		/* cause any pending enabled interrupts to be re-delivered */
		qib_write_kreg(dd, kr_intclear, 0ULL);
		if (dd->cspec->num_msix_entries) {
			/* and same for MSIx */
			u64 val = qib_read_kreg64(dd, kr_intgranted);
			if (val)
				qib_write_kreg(dd, kr_intgranted, val);
		}
	} else
		qib_write_kreg(dd, kr_intmask, 0ULL);
}

/*
 * Try to cleanup as much as possible for anything that might have gone
 * wrong while in freeze mode, such as pio buffers being written by user
 * processes (causing armlaunch), send errors due to going into freeze mode,
 * etc., and try to avoid causing extra interrupts while doing so.
 * Forcibly update the in-memory pioavail register copies after cleanup
 * because the chip won't do it while in freeze mode (the register values
 * themselves are kept correct).
 * Make sure that we don't lose any important interrupts by using the chip
 * feature that says that writing 0 to a bit in *clear that is set in
 * *status will cause an interrupt to be generated again (if allowed by
 * the *mask value).
 * This is in chip-specific code because of all of the register accesses,
 * even though the details are similar on most chips.
 */
static void qib_7322_clear_freeze(struct qib_devdata *dd)
{
	int pidx;

	/* disable error interrupts, to avoid confusion */
	qib_write_kreg(dd, kr_errmask, 0ULL);

	for (pidx = 0; pidx < dd->num_pports; ++pidx)
		if (dd->pport[pidx].link_speed_supported)
			qib_write_kreg_port(dd->pport + pidx, krp_errmask,
					    0ULL);

	/* also disable interrupts; errormask is sometimes overwriten */
	qib_7322_set_intr_state(dd, 0);

	/* clear the freeze, and be sure chip saw it */
	qib_write_kreg(dd, kr_control, dd->control);
	qib_read_kreg32(dd, kr_scratch);

	/*
	 * Force new interrupt if any hwerr, error or interrupt bits are
	 * still set, and clear "safe" send packet errors related to freeze
	 * and cancelling sends.  Re-enable error interrupts before possible
	 * force of re-interrupt on pending interrupts.
	 */
	qib_write_kreg(dd, kr_hwerrclear, 0ULL);
	qib_write_kreg(dd, kr_errclear, E_SPKT_ERRS_IGNORE);
	qib_write_kreg(dd, kr_errmask, dd->cspec->errormask);
	/* We need to purge per-port errs and reset mask, too */
	for (pidx = 0; pidx < dd->num_pports; ++pidx) {
		if (!dd->pport[pidx].link_speed_supported)
			continue;
		qib_write_kreg_port(dd->pport + pidx, krp_errclear, ~0Ull);
		qib_write_kreg_port(dd->pport + pidx, krp_errmask, ~0Ull);
	}
	qib_7322_set_intr_state(dd, 1);
}

/* no error handling to speak of */
/**
 * qib_7322_handle_hwerrors - display hardware errors.
 * @dd: the qlogic_ib device
 * @msg: the output buffer
 * @msgl: the size of the output buffer
 *
 * Use same msg buffer as regular errors to avoid excessive stack
 * use.  Most hardware errors are catastrophic, but for right now,
 * we'll print them and continue.  We reuse the same message buffer as
 * qib_handle_errors() to avoid excessive stack usage.
 */
static void qib_7322_handle_hwerrors(struct qib_devdata *dd, char *msg,
				     size_t msgl)
{
	u64 hwerrs;
	u32 ctrl;
	int isfatal = 0;

	hwerrs = qib_read_kreg64(dd, kr_hwerrstatus);
	if (!hwerrs)
		goto bail;
	if (hwerrs == ~0ULL) {
		qib_dev_err(dd,
			"Read of hardware error status failed (all bits set); ignoring\n");
		goto bail;
	}
	qib_stats.sps_hwerrs++;

	/* Always clear the error status register, except BIST fail */
	qib_write_kreg(dd, kr_hwerrclear, hwerrs &
		       ~HWE_MASK(PowerOnBISTFailed));

	hwerrs &= dd->cspec->hwerrmask;

	/* no EEPROM logging, yet */

	if (hwerrs)
		qib_devinfo(dd->pcidev,
			"Hardware error: hwerr=0x%llx (cleared)\n",
			(unsigned long long) hwerrs);

	ctrl = qib_read_kreg32(dd, kr_control);
	if ((ctrl & SYM_MASK(Control, FreezeMode)) && !dd->diag_client) {
		/*
		 * No recovery yet...
		 */
		if ((hwerrs & ~HWE_MASK(LATriggered)) ||
		    dd->cspec->stay_in_freeze) {
			/*
			 * If any set that we aren't ignoring only make the
			 * complaint once, in case it's stuck or recurring,
			 * and we get here multiple times
			 * Force link down, so switch knows, and
			 * LEDs are turned off.
			 */
			if (dd->flags & QIB_INITTED)
				isfatal = 1;
		} else
			qib_7322_clear_freeze(dd);
	}

	if (hwerrs & HWE_MASK(PowerOnBISTFailed)) {
		isfatal = 1;
		strlcpy(msg,
			"[Memory BIST test failed, InfiniPath hardware unusable]",
			msgl);
		/* ignore from now on, so disable until driver reloaded */
		dd->cspec->hwerrmask &= ~HWE_MASK(PowerOnBISTFailed);
		qib_write_kreg(dd, kr_hwerrmask, dd->cspec->hwerrmask);
	}

	err_decode(msg, msgl, hwerrs, qib_7322_hwerror_msgs);

	/* Ignore esoteric PLL failures et al. */

	qib_dev_err(dd, "%s hardware error\n", msg);

	if (isfatal && !dd->diag_client) {
		qib_dev_err(dd,
			"Fatal Hardware Error, no longer usable, SN %.16s\n",
			dd->serial);
		/*
		 * for /sys status file and user programs to print; if no
		 * trailing brace is copied, we'll know it was truncated.
		 */
		if (dd->freezemsg)
			snprintf(dd->freezemsg, dd->freezelen,
				 "{%s}", msg);
		qib_disable_after_error(dd);
	}
bail:;
}

/**
 * qib_7322_init_hwerrors - enable hardware errors
 * @dd: the qlogic_ib device
 *
 * now that we have finished initializing everything that might reasonably
 * cause a hardware error, and cleared those errors bits as they occur,
 * we can enable hardware errors in the mask (potentially enabling
 * freeze mode), and enable hardware errors as errors (along with
 * everything else) in errormask
 */
static void qib_7322_init_hwerrors(struct qib_devdata *dd)
{
	int pidx;
	u64 extsval;

	extsval = qib_read_kreg64(dd, kr_extstatus);
	if (!(extsval & (QIB_EXTS_MEMBIST_DISABLED |
			 QIB_EXTS_MEMBIST_ENDTEST)))
		qib_dev_err(dd, "MemBIST did not complete!\n");

	/* never clear BIST failure, so reported on each driver load */
	qib_write_kreg(dd, kr_hwerrclear, ~HWE_MASK(PowerOnBISTFailed));
	qib_write_kreg(dd, kr_hwerrmask, dd->cspec->hwerrmask);

	/* clear all */
	qib_write_kreg(dd, kr_errclear, ~0ULL);
	/* enable errors that are masked, at least this first time. */
	qib_write_kreg(dd, kr_errmask, ~0ULL);
	dd->cspec->errormask = qib_read_kreg64(dd, kr_errmask);
	for (pidx = 0; pidx < dd->num_pports; ++pidx)
		if (dd->pport[pidx].link_speed_supported)
			qib_write_kreg_port(dd->pport + pidx, krp_errmask,
					    ~0ULL);
}

/*
 * Disable and enable the armlaunch error.  Used for PIO bandwidth testing
 * on chips that are count-based, rather than trigger-based.  There is no
 * reference counting, but that's also fine, given the intended use.
 * Only chip-specific because it's all register accesses
 */
static void qib_set_7322_armlaunch(struct qib_devdata *dd, u32 enable)
{
	if (enable) {
		qib_write_kreg(dd, kr_errclear, QIB_E_SPIOARMLAUNCH);
		dd->cspec->errormask |= QIB_E_SPIOARMLAUNCH;
	} else
		dd->cspec->errormask &= ~QIB_E_SPIOARMLAUNCH;
	qib_write_kreg(dd, kr_errmask, dd->cspec->errormask);
}

/*
 * Formerly took parameter <which> in pre-shifted,
 * pre-merged form with LinkCmd and LinkInitCmd
 * together, and assuming the zero was NOP.
 */
static void qib_set_ib_7322_lstate(struct qib_pportdata *ppd, u16 linkcmd,
				   u16 linitcmd)
{
	u64 mod_wd;
	struct qib_devdata *dd = ppd->dd;
	unsigned long flags;

	if (linitcmd == QLOGIC_IB_IBCC_LINKINITCMD_DISABLE) {
		/*
		 * If we are told to disable, note that so link-recovery
		 * code does not attempt to bring us back up.
		 * Also reset everything that we can, so we start
		 * completely clean when re-enabled (before we
		 * actually issue the disable to the IBC)
		 */
		qib_7322_mini_pcs_reset(ppd);
		spin_lock_irqsave(&ppd->lflags_lock, flags);
		ppd->lflags |= QIBL_IB_LINK_DISABLED;
		spin_unlock_irqrestore(&ppd->lflags_lock, flags);
	} else if (linitcmd || linkcmd == QLOGIC_IB_IBCC_LINKCMD_DOWN) {
		/*
		 * Any other linkinitcmd will lead to LINKDOWN and then
		 * to INIT (if all is well), so clear flag to let
		 * link-recovery code attempt to bring us back up.
		 */
		spin_lock_irqsave(&ppd->lflags_lock, flags);
		ppd->lflags &= ~QIBL_IB_LINK_DISABLED;
		spin_unlock_irqrestore(&ppd->lflags_lock, flags);
		/*
		 * Clear status change interrupt reduction so the
		 * new state is seen.
		 */
		ppd->cpspec->ibcctrl_a &=
			~SYM_MASK(IBCCtrlA_0, IBStatIntReductionEn);
	}

	mod_wd = (linkcmd << IBA7322_IBCC_LINKCMD_SHIFT) |
		(linitcmd << QLOGIC_IB_IBCC_LINKINITCMD_SHIFT);

	qib_write_kreg_port(ppd, krp_ibcctrl_a, ppd->cpspec->ibcctrl_a |
			    mod_wd);
	/* write to chip to prevent back-to-back writes of ibc reg */
	qib_write_kreg(dd, kr_scratch, 0);

}

/*
 * The total RCV buffer memory is 64KB, used for both ports, and is
 * in units of 64 bytes (same as IB flow control credit unit).
 * The consumedVL unit in the same registers are in 32 byte units!
 * So, a VL15 packet needs 4.50 IB credits, and 9 rx buffer chunks,
 * and we can therefore allocate just 9 IB credits for 2 VL15 packets
 * in krp_rxcreditvl15, rather than 10.
 */
#define RCV_BUF_UNITSZ 64
#define NUM_RCV_BUF_UNITS(dd) ((64 * 1024) / (RCV_BUF_UNITSZ * dd->num_pports))

static void set_vls(struct qib_pportdata *ppd)
{
	int i, numvls, totcred, cred_vl, vl0extra;
	struct qib_devdata *dd = ppd->dd;
	u64 val;

	numvls = qib_num_vls(ppd->vls_operational);

	/*
	 * Set up per-VL credits. Below is kluge based on these assumptions:
	 * 1) port is disabled at the time early_init is called.
	 * 2) give VL15 17 credits, for two max-plausible packets.
	 * 3) Give VL0-N the rest, with any rounding excess used for VL0
	 */
	/* 2 VL15 packets @ 288 bytes each (including IB headers) */
	totcred = NUM_RCV_BUF_UNITS(dd);
	cred_vl = (2 * 288 + RCV_BUF_UNITSZ - 1) / RCV_BUF_UNITSZ;
	totcred -= cred_vl;
	qib_write_kreg_port(ppd, krp_rxcreditvl15, (u64) cred_vl);
	cred_vl = totcred / numvls;
	vl0extra = totcred - cred_vl * numvls;
	qib_write_kreg_port(ppd, krp_rxcreditvl0, cred_vl + vl0extra);
	for (i = 1; i < numvls; i++)
		qib_write_kreg_port(ppd, krp_rxcreditvl0 + i, cred_vl);
	for (; i < 8; i++) /* no buffer space for other VLs */
		qib_write_kreg_port(ppd, krp_rxcreditvl0 + i, 0);

	/* Notify IBC that credits need to be recalculated */
	val = qib_read_kreg_port(ppd, krp_ibsdtestiftx);
	val |= SYM_MASK(IB_SDTEST_IF_TX_0, CREDIT_CHANGE);
	qib_write_kreg_port(ppd, krp_ibsdtestiftx, val);
	qib_write_kreg(dd, kr_scratch, 0ULL);
	val &= ~SYM_MASK(IB_SDTEST_IF_TX_0, CREDIT_CHANGE);
	qib_write_kreg_port(ppd, krp_ibsdtestiftx, val);

	for (i = 0; i < numvls; i++)
		val = qib_read_kreg_port(ppd, krp_rxcreditvl0 + i);
	val = qib_read_kreg_port(ppd, krp_rxcreditvl15);

	/* Change the number of operational VLs */
	ppd->cpspec->ibcctrl_a = (ppd->cpspec->ibcctrl_a &
				~SYM_MASK(IBCCtrlA_0, NumVLane)) |
		((u64)(numvls - 1) << SYM_LSB(IBCCtrlA_0, NumVLane));
	qib_write_kreg_port(ppd, krp_ibcctrl_a, ppd->cpspec->ibcctrl_a);
	qib_write_kreg(dd, kr_scratch, 0ULL);
}

/*
 * The code that deals with actual SerDes is in serdes_7322_init().
 * Compared to the code for iba7220, it is minimal.
 */
static int serdes_7322_init(struct qib_pportdata *ppd);

/**
 * qib_7322_bringup_serdes - bring up the serdes
 * @ppd: physical port on the qlogic_ib device
 */
static int qib_7322_bringup_serdes(struct qib_pportdata *ppd)
{
	struct qib_devdata *dd = ppd->dd;
	u64 val, guid, ibc;
	unsigned long flags;
	int ret = 0;

	/*
	 * SerDes model not in Pd, but still need to
	 * set up much of IBCCtrl and IBCDDRCtrl; move elsewhere
	 * eventually.
	 */
	/* Put IBC in reset, sends disabled (should be in reset already) */
	ppd->cpspec->ibcctrl_a &= ~SYM_MASK(IBCCtrlA_0, IBLinkEn);
	qib_write_kreg_port(ppd, krp_ibcctrl_a, ppd->cpspec->ibcctrl_a);
	qib_write_kreg(dd, kr_scratch, 0ULL);

	if (qib_compat_ddr_negotiate) {
		ppd->cpspec->ibdeltainprog = 1;
		ppd->cpspec->ibsymsnap = read_7322_creg32_port(ppd,
						crp_ibsymbolerr);
		ppd->cpspec->iblnkerrsnap = read_7322_creg32_port(ppd,
						crp_iblinkerrrecov);
	}

	/* flowcontrolwatermark is in units of KBytes */
	ibc = 0x5ULL << SYM_LSB(IBCCtrlA_0, FlowCtrlWaterMark);
	/*
	 * Flow control is sent this often, even if no changes in
	 * buffer space occur.  Units are 128ns for this chip.
	 * Set to 3usec.
	 */
	ibc |= 24ULL << SYM_LSB(IBCCtrlA_0, FlowCtrlPeriod);
	/* max error tolerance */
	ibc |= 0xfULL << SYM_LSB(IBCCtrlA_0, PhyerrThreshold);
	/* IB credit flow control. */
	ibc |= 0xfULL << SYM_LSB(IBCCtrlA_0, OverrunThreshold);
	/*
	 * set initial max size pkt IBC will send, including ICRC; it's the
	 * PIO buffer size in dwords, less 1; also see qib_set_mtu()
	 */
	ibc |= ((u64)(ppd->ibmaxlen >> 2) + 1) <<
		SYM_LSB(IBCCtrlA_0, MaxPktLen);
	ppd->cpspec->ibcctrl_a = ibc; /* without linkcmd or linkinitcmd! */

	/*
	 * Reset the PCS interface to the serdes (and also ibc, which is still
	 * in reset from above).  Writes new value of ibcctrl_a as last step.
	 */
	qib_7322_mini_pcs_reset(ppd);

	if (!ppd->cpspec->ibcctrl_b) {
		unsigned lse = ppd->link_speed_enabled;

		/*
		 * Not on re-init after reset, establish shadow
		 * and force initial config.
		 */
		ppd->cpspec->ibcctrl_b = qib_read_kreg_port(ppd,
							     krp_ibcctrl_b);
		ppd->cpspec->ibcctrl_b &= ~(IBA7322_IBC_SPEED_QDR |
				IBA7322_IBC_SPEED_DDR |
				IBA7322_IBC_SPEED_SDR |
				IBA7322_IBC_WIDTH_AUTONEG |
				SYM_MASK(IBCCtrlB_0, IB_LANE_REV_SUPPORTED));
		if (lse & (lse - 1)) /* Muliple speeds enabled */
			ppd->cpspec->ibcctrl_b |=
				(lse << IBA7322_IBC_SPEED_LSB) |
				IBA7322_IBC_IBTA_1_2_MASK |
				IBA7322_IBC_MAX_SPEED_MASK;
		else
			ppd->cpspec->ibcctrl_b |= (lse == QIB_IB_QDR) ?
				IBA7322_IBC_SPEED_QDR |
				 IBA7322_IBC_IBTA_1_2_MASK :
				(lse == QIB_IB_DDR) ?
					IBA7322_IBC_SPEED_DDR :
					IBA7322_IBC_SPEED_SDR;
		if ((ppd->link_width_enabled & (IB_WIDTH_1X | IB_WIDTH_4X)) ==
		    (IB_WIDTH_1X | IB_WIDTH_4X))
			ppd->cpspec->ibcctrl_b |= IBA7322_IBC_WIDTH_AUTONEG;
		else
			ppd->cpspec->ibcctrl_b |=
				ppd->link_width_enabled == IB_WIDTH_4X ?
				IBA7322_IBC_WIDTH_4X_ONLY :
				IBA7322_IBC_WIDTH_1X_ONLY;

		/* always enable these on driver reload, not sticky */
		ppd->cpspec->ibcctrl_b |= (IBA7322_IBC_RXPOL_MASK |
			IBA7322_IBC_HRTBT_MASK);
	}
	qib_write_kreg_port(ppd, krp_ibcctrl_b, ppd->cpspec->ibcctrl_b);

	/* setup so we have more time at CFGTEST to change H1 */
	val = qib_read_kreg_port(ppd, krp_ibcctrl_c);
	val &= ~SYM_MASK(IBCCtrlC_0, IB_FRONT_PORCH);
	val |= 0xfULL << SYM_LSB(IBCCtrlC_0, IB_FRONT_PORCH);
	qib_write_kreg_port(ppd, krp_ibcctrl_c, val);

	serdes_7322_init(ppd);

	guid = be64_to_cpu(ppd->guid);
	if (!guid) {
		if (dd->base_guid)
			guid = be64_to_cpu(dd->base_guid) + ppd->port - 1;
		ppd->guid = cpu_to_be64(guid);
	}

	qib_write_kreg_port(ppd, krp_hrtbt_guid, guid);
	/* write to chip to prevent back-to-back writes of ibc reg */
	qib_write_kreg(dd, kr_scratch, 0);

	/* Enable port */
	ppd->cpspec->ibcctrl_a |= SYM_MASK(IBCCtrlA_0, IBLinkEn);
	set_vls(ppd);

	/* initially come up DISABLED, without sending anything. */
	val = ppd->cpspec->ibcctrl_a | (QLOGIC_IB_IBCC_LINKINITCMD_DISABLE <<
					QLOGIC_IB_IBCC_LINKINITCMD_SHIFT);
	qib_write_kreg_port(ppd, krp_ibcctrl_a, val);
	qib_write_kreg(dd, kr_scratch, 0ULL);
	/* clear the linkinit cmds */
	ppd->cpspec->ibcctrl_a = val & ~SYM_MASK(IBCCtrlA_0, LinkInitCmd);

	/* be paranoid against later code motion, etc. */
	spin_lock_irqsave(&dd->cspec->rcvmod_lock, flags);
	ppd->p_rcvctrl |= SYM_MASK(RcvCtrl_0, RcvIBPortEnable);
	qib_write_kreg_port(ppd, krp_rcvctrl, ppd->p_rcvctrl);
	spin_unlock_irqrestore(&dd->cspec->rcvmod_lock, flags);

	/* Also enable IBSTATUSCHG interrupt.  */
	val = qib_read_kreg_port(ppd, krp_errmask);
	qib_write_kreg_port(ppd, krp_errmask,
		val | ERR_MASK_N(IBStatusChanged));

	/* Always zero until we start messing with SerDes for real */
	return ret;
}

/**
 * qib_7322_quiet_serdes - set serdes to txidle
 * @dd: the qlogic_ib device
 * Called when driver is being unloaded
 */
static void qib_7322_mini_quiet_serdes(struct qib_pportdata *ppd)
{
	u64 val;
	unsigned long flags;

	qib_set_ib_7322_lstate(ppd, 0, QLOGIC_IB_IBCC_LINKINITCMD_DISABLE);

	spin_lock_irqsave(&ppd->lflags_lock, flags);
	ppd->lflags &= ~QIBL_IB_AUTONEG_INPROG;
	spin_unlock_irqrestore(&ppd->lflags_lock, flags);
	wake_up(&ppd->cpspec->autoneg_wait);
	cancel_delayed_work_sync(&ppd->cpspec->autoneg_work);
	if (ppd->dd->cspec->r1)
		cancel_delayed_work_sync(&ppd->cpspec->ipg_work);

	ppd->cpspec->chase_end = 0;
	if (ppd->cpspec->chase_timer.data) /* if initted */
		del_timer_sync(&ppd->cpspec->chase_timer);

	/*
	 * Despite the name, actually disables IBC as well. Do it when
	 * we are as sure as possible that no more packets can be
	 * received, following the down and the PCS reset.
	 * The actual disabling happens in qib_7322_mini_pci_reset(),
	 * along with the PCS being reset.
	 */
	ppd->cpspec->ibcctrl_a &= ~SYM_MASK(IBCCtrlA_0, IBLinkEn);
	qib_7322_mini_pcs_reset(ppd);

	/*
	 * Update the adjusted counters so the adjustment persists
	 * across driver reload.
	 */
	if (ppd->cpspec->ibsymdelta || ppd->cpspec->iblnkerrdelta ||
	    ppd->cpspec->ibdeltainprog || ppd->cpspec->iblnkdowndelta) {
		struct qib_devdata *dd = ppd->dd;
		u64 diagc;

		/* enable counter writes */
		diagc = qib_read_kreg64(dd, kr_hwdiagctrl);
		qib_write_kreg(dd, kr_hwdiagctrl,
			       diagc | SYM_MASK(HwDiagCtrl, CounterWrEnable));

		if (ppd->cpspec->ibsymdelta || ppd->cpspec->ibdeltainprog) {
			val = read_7322_creg32_port(ppd, crp_ibsymbolerr);
			if (ppd->cpspec->ibdeltainprog)
				val -= val - ppd->cpspec->ibsymsnap;
			val -= ppd->cpspec->ibsymdelta;
			write_7322_creg_port(ppd, crp_ibsymbolerr, val);
		}
		if (ppd->cpspec->iblnkerrdelta || ppd->cpspec->ibdeltainprog) {
			val = read_7322_creg32_port(ppd, crp_iblinkerrrecov);
			if (ppd->cpspec->ibdeltainprog)
				val -= val - ppd->cpspec->iblnkerrsnap;
			val -= ppd->cpspec->iblnkerrdelta;
			write_7322_creg_port(ppd, crp_iblinkerrrecov, val);
		}
		if (ppd->cpspec->iblnkdowndelta) {
			val = read_7322_creg32_port(ppd, crp_iblinkdown);
			val += ppd->cpspec->iblnkdowndelta;
			write_7322_creg_port(ppd, crp_iblinkdown, val);
		}
		/*
		 * No need to save ibmalfdelta since IB perfcounters
		 * are cleared on driver reload.
		 */

		/* and disable counter writes */
		qib_write_kreg(dd, kr_hwdiagctrl, diagc);
	}
}

/**
 * qib_setup_7322_setextled - set the state of the two external LEDs
 * @ppd: physical port on the qlogic_ib device
 * @on: whether the link is up or not
 *
 * The exact combo of LEDs if on is true is determined by looking
 * at the ibcstatus.
 *
 * These LEDs indicate the physical and logical state of IB link.
 * For this chip (at least with recommended board pinouts), LED1
 * is Yellow (logical state) and LED2 is Green (physical state),
 *
 * Note:  We try to match the Mellanox HCA LED behavior as best
 * we can.  Green indicates physical link state is OK (something is
 * plugged in, and we can train).
 * Amber indicates the link is logically up (ACTIVE).
 * Mellanox further blinks the amber LED to indicate data packet
 * activity, but we have no hardware support for that, so it would
 * require waking up every 10-20 msecs and checking the counters
 * on the chip, and then turning the LED off if appropriate.  That's
 * visible overhead, so not something we will do.
 */
static void qib_setup_7322_setextled(struct qib_pportdata *ppd, u32 on)
{
	struct qib_devdata *dd = ppd->dd;
	u64 extctl, ledblink = 0, val;
	unsigned long flags;
	int yel, grn;

	/*
	 * The diags use the LED to indicate diag info, so we leave
	 * the external LED alone when the diags are running.
	 */
	if (dd->diag_client)
		return;

	/* Allow override of LED display for, e.g. Locating system in rack */
	if (ppd->led_override) {
		grn = (ppd->led_override & QIB_LED_PHYS);
		yel = (ppd->led_override & QIB_LED_LOG);
	} else if (on) {
		val = qib_read_kreg_port(ppd, krp_ibcstatus_a);
		grn = qib_7322_phys_portstate(val) ==
			IB_PHYSPORTSTATE_LINKUP;
		yel = qib_7322_iblink_state(val) == IB_PORT_ACTIVE;
	} else {
		grn = 0;
		yel = 0;
	}

	spin_lock_irqsave(&dd->cspec->gpio_lock, flags);
	extctl = dd->cspec->extctrl & (ppd->port == 1 ?
		~ExtLED_IB1_MASK : ~ExtLED_IB2_MASK);
	if (grn) {
		extctl |= ppd->port == 1 ? ExtLED_IB1_GRN : ExtLED_IB2_GRN;
		/*
		 * Counts are in chip clock (4ns) periods.
		 * This is 1/16 sec (66.6ms) on,
		 * 3/16 sec (187.5 ms) off, with packets rcvd.
		 */
		ledblink = ((66600 * 1000UL / 4) << IBA7322_LEDBLINK_ON_SHIFT) |
			((187500 * 1000UL / 4) << IBA7322_LEDBLINK_OFF_SHIFT);
	}
	if (yel)
		extctl |= ppd->port == 1 ? ExtLED_IB1_YEL : ExtLED_IB2_YEL;
	dd->cspec->extctrl = extctl;
	qib_write_kreg(dd, kr_extctrl, dd->cspec->extctrl);
	spin_unlock_irqrestore(&dd->cspec->gpio_lock, flags);

	if (ledblink) /* blink the LED on packet receive */
		qib_write_kreg_port(ppd, krp_rcvpktledcnt, ledblink);
}

#ifdef CONFIG_INFINIBAND_QIB_DCA

static int qib_7322_notify_dca(struct qib_devdata *dd, unsigned long event)
{
	switch (event) {
	case DCA_PROVIDER_ADD:
		if (dd->flags & QIB_DCA_ENABLED)
			break;
		if (!dca_add_requester(&dd->pcidev->dev)) {
			qib_devinfo(dd->pcidev, "DCA enabled\n");
			dd->flags |= QIB_DCA_ENABLED;
			qib_setup_dca(dd);
		}
		break;
	case DCA_PROVIDER_REMOVE:
		if (dd->flags & QIB_DCA_ENABLED) {
			dca_remove_requester(&dd->pcidev->dev);
			dd->flags &= ~QIB_DCA_ENABLED;
			dd->cspec->dca_ctrl = 0;
			qib_write_kreg(dd, KREG_IDX(DCACtrlA),
				dd->cspec->dca_ctrl);
		}
		break;
	}
	return 0;
}

static void qib_update_rhdrq_dca(struct qib_ctxtdata *rcd, int cpu)
{
	struct qib_devdata *dd = rcd->dd;
	struct qib_chip_specific *cspec = dd->cspec;

	if (!(dd->flags & QIB_DCA_ENABLED))
		return;
	if (cspec->rhdr_cpu[rcd->ctxt] != cpu) {
		const struct dca_reg_map *rmp;

		cspec->rhdr_cpu[rcd->ctxt] = cpu;
		rmp = &dca_rcvhdr_reg_map[rcd->ctxt];
		cspec->dca_rcvhdr_ctrl[rmp->shadow_inx] &= rmp->mask;
		cspec->dca_rcvhdr_ctrl[rmp->shadow_inx] |=
			(u64) dca3_get_tag(&dd->pcidev->dev, cpu) << rmp->lsb;
		qib_devinfo(dd->pcidev,
			"Ctxt %d cpu %d dca %llx\n", rcd->ctxt, cpu,
			(long long) cspec->dca_rcvhdr_ctrl[rmp->shadow_inx]);
		qib_write_kreg(dd, rmp->regno,
			       cspec->dca_rcvhdr_ctrl[rmp->shadow_inx]);
		cspec->dca_ctrl |= SYM_MASK(DCACtrlA, RcvHdrqDCAEnable);
		qib_write_kreg(dd, KREG_IDX(DCACtrlA), cspec->dca_ctrl);
	}
}

static void qib_update_sdma_dca(struct qib_pportdata *ppd, int cpu)
{
	struct qib_devdata *dd = ppd->dd;
	struct qib_chip_specific *cspec = dd->cspec;
	unsigned pidx = ppd->port - 1;

	if (!(dd->flags & QIB_DCA_ENABLED))
		return;
	if (cspec->sdma_cpu[pidx] != cpu) {
		cspec->sdma_cpu[pidx] = cpu;
		cspec->dca_rcvhdr_ctrl[4] &= ~(ppd->hw_pidx ?
			SYM_MASK(DCACtrlF, SendDma1DCAOPH) :
			SYM_MASK(DCACtrlF, SendDma0DCAOPH));
		cspec->dca_rcvhdr_ctrl[4] |=
			(u64) dca3_get_tag(&dd->pcidev->dev, cpu) <<
				(ppd->hw_pidx ?
					SYM_LSB(DCACtrlF, SendDma1DCAOPH) :
					SYM_LSB(DCACtrlF, SendDma0DCAOPH));
		qib_devinfo(dd->pcidev,
			"sdma %d cpu %d dca %llx\n", ppd->hw_pidx, cpu,
			(long long) cspec->dca_rcvhdr_ctrl[4]);
		qib_write_kreg(dd, KREG_IDX(DCACtrlF),
			       cspec->dca_rcvhdr_ctrl[4]);
		cspec->dca_ctrl |= ppd->hw_pidx ?
			SYM_MASK(DCACtrlA, SendDMAHead1DCAEnable) :
			SYM_MASK(DCACtrlA, SendDMAHead0DCAEnable);
		qib_write_kreg(dd, KREG_IDX(DCACtrlA), cspec->dca_ctrl);
	}
}

static void qib_setup_dca(struct qib_devdata *dd)
{
	struct qib_chip_specific *cspec = dd->cspec;
	int i;

	for (i = 0; i < ARRAY_SIZE(cspec->rhdr_cpu); i++)
		cspec->rhdr_cpu[i] = -1;
	for (i = 0; i < ARRAY_SIZE(cspec->sdma_cpu); i++)
		cspec->sdma_cpu[i] = -1;
	cspec->dca_rcvhdr_ctrl[0] =
		(1ULL << SYM_LSB(DCACtrlB, RcvHdrq0DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlB, RcvHdrq1DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlB, RcvHdrq2DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlB, RcvHdrq3DCAXfrCnt));
	cspec->dca_rcvhdr_ctrl[1] =
		(1ULL << SYM_LSB(DCACtrlC, RcvHdrq4DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlC, RcvHdrq5DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlC, RcvHdrq6DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlC, RcvHdrq7DCAXfrCnt));
	cspec->dca_rcvhdr_ctrl[2] =
		(1ULL << SYM_LSB(DCACtrlD, RcvHdrq8DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlD, RcvHdrq9DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlD, RcvHdrq10DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlD, RcvHdrq11DCAXfrCnt));
	cspec->dca_rcvhdr_ctrl[3] =
		(1ULL << SYM_LSB(DCACtrlE, RcvHdrq12DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlE, RcvHdrq13DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlE, RcvHdrq14DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlE, RcvHdrq15DCAXfrCnt));
	cspec->dca_rcvhdr_ctrl[4] =
		(1ULL << SYM_LSB(DCACtrlF, RcvHdrq16DCAXfrCnt)) |
		(1ULL << SYM_LSB(DCACtrlF, RcvHdrq17DCAXfrCnt));
	for (i = 0; i < ARRAY_SIZE(cspec->sdma_cpu); i++)
		qib_write_kreg(dd, KREG_IDX(DCACtrlB) + i,
			       cspec->dca_rcvhdr_ctrl[i]);
	for (i = 0; i < cspec->num_msix_entries; i++)
		setup_dca_notifier(dd, &cspec->msix_entries[i]);
}

static void qib_irq_notifier_notify(struct irq_affinity_notify *notify,
			     const cpumask_t *mask)
{
	struct qib_irq_notify *n =
		container_of(notify, struct qib_irq_notify, notify);
	int cpu = cpumask_first(mask);

	if (n->rcv) {
		struct qib_ctxtdata *rcd = (struct qib_ctxtdata *)n->arg;
		qib_update_rhdrq_dca(rcd, cpu);
	} else {
		struct qib_pportdata *ppd = (struct qib_pportdata *)n->arg;
		qib_update_sdma_dca(ppd, cpu);
	}
}

static void qib_irq_notifier_release(struct kref *ref)
{
	struct qib_irq_notify *n =
		container_of(ref, struct qib_irq_notify, notify.kref);
	struct qib_devdata *dd;

	if (n->rcv) {
		struct qib_ctxtdata *rcd = (struct qib_ctxtdata *)n->arg;
		dd = rcd->dd;
	} else {
		struct qib_pportdata *ppd = (struct qib_pportdata *)n->arg;
		dd = ppd->dd;
	}
	qib_devinfo(dd->pcidev,
		"release on HCA notify 0x%p n 0x%p\n", ref, n);
	kfree(n);
}
#endif

/*
 * Disable MSIx interrupt if enabled, call generic MSIx code
 * to cleanup, and clear pending MSIx interrupts.
 * Used for fallback to INTx, after reset, and when MSIx setup fails.
 */
static void qib_7322_nomsix(struct qib_devdata *dd)
{
	u64 intgranted;
	int n;

	dd->cspec->main_int_mask = ~0ULL;
	n = dd->cspec->num_msix_entries;
	if (n) {
		int i;

		dd->cspec->num_msix_entries = 0;
		for (i = 0; i < n; i++) {
#ifdef CONFIG_INFINIBAND_QIB_DCA
			reset_dca_notifier(dd, &dd->cspec->msix_entries[i]);
#endif
			irq_set_affinity_hint(
			  dd->cspec->msix_entries[i].msix.vector, NULL);
			free_cpumask_var(dd->cspec->msix_entries[i].mask);
			free_irq(dd->cspec->msix_entries[i].msix.vector,
			   dd->cspec->msix_entries[i].arg);
		}
		qib_nomsix(dd);
	}
	/* make sure no MSIx interrupts are left pending */
	intgranted = qib_read_kreg64(dd, kr_intgranted);
	if (intgranted)
		qib_write_kreg(dd, kr_intgranted, intgranted);
}

static void qib_7322_free_irq(struct qib_devdata *dd)
{
	if (dd->cspec->irq) {
		free_irq(dd->cspec->irq, dd);
		dd->cspec->irq = 0;
	}
	qib_7322_nomsix(dd);
}

static void qib_setup_7322_cleanup(struct qib_devdata *dd)
{
	int i;

#ifdef CONFIG_INFINIBAND_QIB_DCA
	if (dd->flags & QIB_DCA_ENABLED) {
		dca_remove_requester(&dd->pcidev->dev);
		dd->flags &= ~QIB_DCA_ENABLED;
		dd->cspec->dca_ctrl = 0;
		qib_write_kreg(dd, KREG_IDX(DCACtrlA), dd->cspec->dca_ctrl);
	}
#endif

	qib_7322_free_irq(dd);
	kfree(dd->cspec->cntrs);
	kfree(dd->cspec->sendchkenable);
	kfree(dd->cspec->sendgrhchk);
	kfree(dd->cspec->sendibchk);
	kfree(dd->cspec->msix_entries);
	for (i = 0; i < dd->num_pports; i++) {
		unsigned long flags;
		u32 mask = QSFP_GPIO_MOD_PRS_N |
			(QSFP_GPIO_MOD_PRS_N << QSFP_GPIO_PORT2_SHIFT);

		kfree(dd->pport[i].cpspec->portcntrs);
		if (dd->flags & QIB_HAS_QSFP) {
			spin_lock_irqsave(&dd->cspec->gpio_lock, flags);
			dd->cspec->gpio_mask &= ~mask;
			qib_write_kreg(dd, kr_gpio_mask, dd->cspec->gpio_mask);
			spin_unlock_irqrestore(&dd->cspec->gpio_lock, flags);
			qib_qsfp_deinit(&dd->pport[i].cpspec->qsfp_data);
		}
		if (dd->pport[i].ibport_data.smi_ah)
			ib_destroy_ah(&dd->pport[i].ibport_data.smi_ah->ibah);
	}
}

/* handle SDMA interrupts */
static void sdma_7322_intr(struct qib_devdata *dd, u64 istat)
{
	struct qib_pportdata *ppd0 = &dd->pport[0];
	struct qib_pportdata *ppd1 = &dd->pport[1];
	u64 intr0 = istat & (INT_MASK_P(SDma, 0) |
		INT_MASK_P(SDmaIdle, 0) | INT_MASK_P(SDmaProgress, 0));
	u64 intr1 = istat & (INT_MASK_P(SDma, 1) |
		INT_MASK_P(SDmaIdle, 1) | INT_MASK_P(SDmaProgress, 1));

	if (intr0)
		qib_sdma_intr(ppd0);
	if (intr1)
		qib_sdma_intr(ppd1);

	if (istat & INT_MASK_PM(SDmaCleanupDone, 0))
		qib_sdma_process_event(ppd0, qib_sdma_event_e20_hw_started);
	if (istat & INT_MASK_PM(SDmaCleanupDone, 1))
		qib_sdma_process_event(ppd1, qib_sdma_event_e20_hw_started);
}

/*
 * Set or clear the Send buffer available interrupt enable bit.
 */
static void qib_wantpiobuf_7322_intr(struct qib_devdata *dd, u32 needint)
{
	unsigned long flags;

	spin_lock_irqsave(&dd->sendctrl_lock, flags);
	if (needint)
		dd->sendctrl |= SYM_MASK(SendCtrl, SendIntBufAvail);
	else
		dd->sendctrl &= ~SYM_MASK(SendCtrl, SendIntBufAvail);
	qib_write_kreg(dd, kr_sendctrl, dd->sendctrl);
	qib_write_kreg(dd, kr_scratch, 0ULL);
	spin_unlock_irqrestore(&dd->sendctrl_lock, flags);
}

/*
 * Somehow got an interrupt with reserved bits set in interrupt status.
 * Print a message so we know it happened, then clear them.
 * keep mainline interrupt handler cache-friendly
 */
static noinline void unknown_7322_ibits(struct qib_devdata *dd, u64 istat)
{
	u64 kills;
	char msg[128];

	kills = istat & ~QIB_I_BITSEXTANT;
	qib_dev_err(dd,
		"Clearing reserved interrupt(s) 0x%016llx: %s\n",
		(unsigned long long) kills, msg);
	qib_write_kreg(dd, kr_intmask, (dd->cspec->int_enable_mask & ~kills));
}

/* keep mainline interrupt handler cache-friendly */
static noinline void unknown_7322_gpio_intr(struct qib_devdata *dd)
{
	u32 gpiostatus;
	int handled = 0;
	int pidx;

	/*
	 * Boards for this chip currently don't use GPIO interrupts,
	 * so clear by writing GPIOstatus to GPIOclear, and complain
	 * to developer.  To avoid endless repeats, clear
	 * the bits in the mask, since there is some kind of
	 * programming error or chip problem.
	 */
	gpiostatus = qib_read_kreg32(dd, kr_gpio_status);
	/*
	 * In theory, writing GPIOstatus to GPIOclear could
	 * have a bad side-effect on some diagnostic that wanted
	 * to poll for a status-change, but the various shadows
	 * make that problematic at best. Diags will just suppress
	 * all GPIO interrupts during such tests.
	 */
	qib_write_kreg(dd, kr_gpio_clear, gpiostatus);
	/*
	 * Check for QSFP MOD_PRS changes
	 * only works for single port if IB1 != pidx1
	 */
	for (pidx = 0; pidx < dd->num_pports && (dd->flags & QIB_HAS_QSFP);
	     ++pidx) {
		struct qib_pportdata *ppd;
		struct qib_qsfp_data *qd;
		u32 mask;
		if (!dd->pport[pidx].link_speed_supported)
			continue;
		mask = QSFP_GPIO_MOD_PRS_N;
		ppd = dd->pport + pidx;
		mask <<= (QSFP_GPIO_PORT2_SHIFT * ppd->hw_pidx);
		if (gpiostatus & dd->cspec->gpio_mask & mask) {
			u64 pins;
			qd = &ppd->cpspec->qsfp_data;
			gpiostatus &= ~mask;
			pins = qib_read_kreg64(dd, kr_extstatus);
			pins >>= SYM_LSB(EXTStatus, GPIOIn);
			if (!(pins & mask)) {
				++handled;
				qd->t_insert = jiffies;
				queue_work(ib_wq, &qd->work);
			}
		}
	}

	if (gpiostatus && !handled) {
		const u32 mask = qib_read_kreg32(dd, kr_gpio_mask);
		u32 gpio_irq = mask & gpiostatus;

		/*
		 * Clear any troublemakers, and update chip from shadow
		 */
		dd->cspec->gpio_mask &= ~gpio_irq;
		qib_write_kreg(dd, kr_gpio_mask, dd->cspec->gpio_mask);
	}
}

/*
 * Handle errors and unusual events first, separate function
 * to improve cache hits for fast path interrupt handling.
 */
static noinline void unlikely_7322_intr(struct qib_devdata *dd, u64 istat)
{
	if (istat & ~QIB_I_BITSEXTANT)
		unknown_7322_ibits(dd, istat);
	if (istat & QIB_I_GPIO)
		unknown_7322_gpio_intr(dd);
	if (istat & QIB_I_C_ERROR) {
		qib_write_kreg(dd, kr_errmask, 0ULL);
		tasklet_schedule(&dd->error_tasklet);
	}
	if (istat & INT_MASK_P(Err, 0) && dd->rcd[0])
		handle_7322_p_errors(dd->rcd[0]->ppd);
	if (istat & INT_MASK_P(Err, 1) && dd->rcd[1])
		handle_7322_p_errors(dd->rcd[1]->ppd);
}

/*
 * Dynamically adjust the rcv int timeout for a context based on incoming
 * packet rate.
 */
static void adjust_rcv_timeout(struct qib_ctxtdata *rcd, int npkts)
{
	struct qib_devdata *dd = rcd->dd;
	u32 timeout = dd->cspec->rcvavail_timeout[rcd->ctxt];

	/*
	 * Dynamically adjust idle timeout on chip
	 * based on number of packets processed.
	 */
	if (npkts < rcv_int_count && timeout > 2)
		timeout >>= 1;
	else if (npkts >= rcv_int_count && timeout < rcv_int_timeout)
		timeout = min(timeout << 1, rcv_int_timeout);
	else
		return;

	dd->cspec->rcvavail_timeout[rcd->ctxt] = timeout;
	qib_write_kreg(dd, kr_rcvavailtimeout + rcd->ctxt, timeout);
}

/*
 * This is the main interrupt handler.
 * It will normally only be used for low frequency interrupts but may
 * have to handle all interrupts if INTx is enabled or fewer than normal
 * MSIx interrupts were allocated.
 * This routine should ignore the interrupt bits for any of the
 * dedicated MSIx handlers.
 */
static irqreturn_t qib_7322intr(int irq, void *data)
{
	struct qib_devdata *dd = data;
	irqreturn_t ret;
	u64 istat;
	u64 ctxtrbits;
	u64 rmask;
	unsigned i;
	u32 npkts;

	if ((dd->flags & (QIB_PRESENT | QIB_BADINTR)) != QIB_PRESENT) {
		/*
		 * This return value is not great, but we do not want the
		 * interrupt core code to remove our interrupt handler
		 * because we don't appear to be handling an interrupt
		 * during a chip reset.
		 */
		ret = IRQ_HANDLED;
		goto bail;
	}

	istat = qib_read_kreg64(dd, kr_intstatus);

	if (unlikely(istat == ~0ULL)) {
		qib_bad_intrstatus(dd);
		qib_dev_err(dd, "Interrupt status all f's, skipping\n");
		/* don't know if it was our interrupt or not */
		ret = IRQ_NONE;
		goto bail;
	}

	istat &= dd->cspec->main_int_mask;
	if (unlikely(!istat)) {
		/* already handled, or shared and not us */
		ret = IRQ_NONE;
		goto bail;
	}

	qib_stats.sps_ints++;
	if (dd->int_counter != (u32) -1)
		dd->int_counter++;

	/* handle "errors" of various kinds first, device ahead of port */
	if (unlikely(istat & (~QIB_I_BITSEXTANT | QIB_I_GPIO |
			      QIB_I_C_ERROR | INT_MASK_P(Err, 0) |
			      INT_MASK_P(Err, 1))))
		unlikely_7322_intr(dd, istat);

	/*
	 * Clear the interrupt bits we found set, relatively early, so we
	 * "know" know the chip will have seen this by the time we process
	 * the queue, and will re-interrupt if necessary.  The processor
	 * itself won't take the interrupt again until we return.
	 */
	qib_write_kreg(dd, kr_intclear, istat);

	/*
	 * Handle kernel receive queues before checking for pio buffers
	 * available since receives can overflow; piobuf waiters can afford
	 * a few extra cycles, since they were waiting anyway.
	 */
	ctxtrbits = istat & (QIB_I_RCVAVAIL_MASK | QIB_I_RCVURG_MASK);
	if (ctxtrbits) {
		rmask = (1ULL << QIB_I_RCVAVAIL_LSB) |
			(1ULL << QIB_I_RCVURG_LSB);
		for (i = 0; i < dd->first_user_ctxt; i++) {
			if (ctxtrbits & rmask) {
				ctxtrbits &= ~rmask;
				if (dd->rcd[i])
					qib_kreceive(dd->rcd[i], NULL, &npkts);
			}
			rmask <<= 1;
		}
		if (ctxtrbits) {
			ctxtrbits = (ctxtrbits >> QIB_I_RCVAVAIL_LSB) |
				(ctxtrbits >> QIB_I_RCVURG_LSB);
			qib_handle_urcv(dd, ctxtrbits);
		}
	}

	if (istat & (QIB_I_P_SDMAINT(0) | QIB_I_P_SDMAINT(1)))
		sdma_7322_intr(dd, istat);

	if ((istat & QIB_I_SPIOBUFAVAIL) && (dd->flags & QIB_INITTED))
		qib_ib_piobufavail(dd);

	ret = IRQ_HANDLED;
bail:
	return ret;
}

/*
 * Dedicated receive packet available interrupt handler.
 */
static irqreturn_t qib_7322pintr(int irq, void *data)
{
	struct qib_ctxtdata *rcd = data;
	struct qib_devdata *dd = rcd->dd;
	u32 npkts;

	if ((dd->flags & (QIB_PRESENT | QIB_BADINTR)) != QIB_PRESENT)
		/*
		 * This return value is not great, but we do not want the
		 * interrupt core code to remove our interrupt handler
		 * because we don't appear to be handling an interrupt
		 * during a chip reset.
		 */
		return IRQ_HANDLED;

	qib_stats.sps_ints++;
	if (dd->int_counter != (u32) -1)
		dd->int_counter++;

	/* Clear the interrupt bit we expect to be set. */
	qib_write_kreg(dd, kr_intclear, ((1ULL << QIB_I_RCVAVAIL_LSB) |
		       (1ULL << QIB_I_RCVURG_LSB)) << rcd->ctxt);

	qib_kreceive(rcd, NULL, &npkts);

	return IRQ_HANDLED;
}

/*
 * Dedicated Send buffer available interrupt handler.
 */
static irqreturn_t qib_7322bufavail(int irq, void *data)
{
	struct qib_devdata *dd = data;

	if ((dd->flags & (QIB_PRESENT | QIB_BADINTR)) != QIB_PRESENT)
		/*
		 * This return value is not great, but we do not want the
		 * interrupt core code to remove our interrupt handler
		 * because we don't appear to be handling an interrupt
		 * during a chip reset.
		 */
		return IRQ_HANDLED;

	qib_stats.sps_ints++;
	if (dd->int_counter != (u32) -1)
		dd->int_counter++;

	/* Clear the interrupt bit we expect to be set. */
	qib_write_kreg(dd, kr_intclear, QIB_I_SPIOBUFAVAIL);

	/* qib_ib_piobufavail() will clear the want PIO interrupt if needed */
	if (dd->flags & QIB_INITTED)
		qib_ib_piobufavail(dd);
	else
		qib_wantpiobuf_7322_intr(dd, 0);

	return IRQ_HANDLED;
}

/*
 * Dedicated Send DMA interrupt handler.
 */
static irqreturn_t sdma_intr(int irq, void *data)
{
	struct qib_pportdata *ppd = data;
	struct qib_devdata *dd = ppd->dd;

	if ((dd->flags & (QIB_PRESENT | QIB_BADINTR)) != QIB_PRESENT)
		/*
		 * This return value is not great, but we do not want the
		 * interrupt core code to remove our interrupt handler
		 * because we don't appear to be handling an interrupt
		 * during a chip reset.
		 */
		return IRQ_HANDLED;

	qib_stats.sps_ints++;
	if (dd->int_counter != (u32) -1)
		dd->int_counter++;

	/* Clear the interrupt bit we expect to be set. */
	qib_write_kreg(dd, kr_intclear, ppd->hw_pidx ?
		       INT_MASK_P(SDma, 1) : INT_MASK_P(SDma, 0));
	qib_sdma_intr(ppd);

	return IRQ_HANDLED;
}

/*
 * Dedicated Send DMA idle interrupt handler.
 */
static irqreturn_t sdma_idle_intr(int irq, void *data)
{
	struct qib_pportdata *ppd = data;
	struct qib_devdata *dd = ppd->dd;

	if ((dd->flags & (QIB_PRESENT | QIB_BADINTR)) != QIB_PRESENT)
		/*
		 * This return value is not great, but we do not want the
		 * interrupt core code to remove our interrupt handler
		 * because we don't appear to be handling an interrupt
		 * during a chip reset.
		 */
		return IRQ_HANDLED;

	qib_stats.sps_ints++;
	if (dd->int_counter != (u32) -1)
		dd->int_counter++;

	/* Clear the interrupt bit we expect to be set. */
	qib_write_kreg(dd, kr_intclear, ppd->hw_pidx ?
		       INT_MASK_P(SDmaIdle, 1) : INT_MASK_P(SDmaIdle, 0));
	qib_sdma_intr(ppd);

	return IRQ_HANDLED;
}

/*
 * Dedicated Send DMA progress interrupt handler.
 */
static irqreturn_t sdma_progress_intr(int irq, void *data)
{
	struct qib_pportdata *ppd = data;
	struct qib_devdata *dd = ppd->dd;

	if ((dd->flags & (QIB_PRESENT | QIB_BADINTR)) != QIB_PRESENT)
		/*
		 * This return value is not great, but we do not want the
		 * interrupt core code to remove our interrupt handler
		 * because we don't appear to be handling an interrupt
		 * during a chip reset.
		 */
		return IRQ_HANDLED;

	qib_stats.sps_ints++;
	if (dd->int_counter != (u32) -1)
		dd->int_counter++;

	/* Clear the interrupt bit we expect to be set. */
	qib_write_kreg(dd, kr_intclear, ppd->hw_pidx ?
		       INT_MASK_P(SDmaProgress, 1) :
		       INT_MASK_P(SDmaProgress, 0));
	qib_sdma_intr(ppd);

	return IRQ_HANDLED;
}

/*
 * Dedicated Send DMA cleanup interrupt handler.
 */
static irqreturn_t sdma_cleanup_intr(int irq, void *data)
{
	struct qib_pportdata *ppd = data;
	struct qib_devdata *dd = ppd->dd;

	if ((dd->flags & (QIB_PRESENT | QIB_BADINTR)) != QIB_PRESENT)
		/*
		 * This return value is not great, but we do not want the
		 * interrupt core code to remove our interrupt handler
		 * because we don't appear to be handling an interrupt
		 * during a chip reset.
		 */
		return IRQ_HANDLED;

	qib_stats.sps_ints++;
	if (dd->int_counter != (u32) -1)
		dd->int_counter++;

	/* Clear the interrupt bit we expect to be set. */
	qib_write_kreg(dd, kr_intclear, ppd->hw_pidx ?
		       INT_MASK_PM(SDmaCleanupDone, 1) :
		       INT_MASK_PM(SDmaCleanupDone, 0));
	qib_sdma_process_event(ppd, qib_sdma_event_e20_hw_started);

	return IRQ_HANDLED;
}

#ifdef CONFIG_INFINIBAND_QIB_DCA

static void reset_dca_notifier(struct qib_devdata *dd, struct qib_msix_entry *m)
{
	if (!m->dca)
		return;
	qib_devinfo(dd->pcidev,
		"Disabling notifier on HCA %d irq %d\n",
		dd->unit,
		m->msix.vector);
	irq_set_affinity_notifier(
		m->msix.vector,
		NULL);
	m->notifier = NULL;
}

static void setup_dca_notifier(struct qib_devdata *dd, struct qib_msix_entry *m)
{
	struct qib_irq_notify *n;

	if (!m->dca)
		return;
	n = kzalloc(sizeof(*n), GFP_KERNEL);
	if (n) {
		int ret;

		m->notifier = n;
		n->notify.irq = m->msix.vector;
		n->notify.notify = qib_irq_notifier_notify;
		n->notify.release = qib_irq_notifier_release;
		n->arg = m->arg;
		n->rcv = m->rcv;
		qib_devinfo(dd->pcidev,
			"set notifier irq %d rcv %d notify %p\n",
			n->notify.irq, n->rcv, &n->notify);
		ret = irq_set_affinity_notifier(
				n->notify.irq,
				&n->notify);
		if (ret) {
			m->notifier = NULL;
			kfree(n);
		}
	}
}

#endif

/*
 * Set up our chip-specific interrupt handler.
 * The interrupt type has already been setup, so
 * we just need to do the registration and error checking.
 * If we are using MSIx interrupts, we may fall back to
 * INTx later, if the interrupt handler doesn't get called
 * within 1/2 second (see verify_interrupt()).
 */
static void qib_setup_7322_interrupt(struct qib_devdata *dd, int clearpend)
{
	int ret, i, msixnum;
	u64 redirect[6];
	u64 mask;
	const struct cpumask *local_mask;
	int firstcpu, secondcpu = 0, currrcvcpu = 0;

	if (!dd->num_pports)
		return;

	if (clearpend) {
		/*
		 * if not switching interrupt types, be sure interrupts are
		 * disabled, and then clear anything pending at this point,
		 * because we are starting clean.
		 */
		qib_7322_set_intr_state(dd, 0);

		/* clear the reset error, init error/hwerror mask */
		qib_7322_init_hwerrors(dd);

		/* clear any interrupt bits that might be set */
		qib_write_kreg(dd, kr_intclear, ~0ULL);

		/* make sure no pending MSIx intr, and clear diag reg */
		qib_write_kreg(dd, kr_intgranted, ~0ULL);
		qib_write_kreg(dd, kr_vecclr_wo_int, ~0ULL);
	}

	if (!dd->cspec->num_msix_entries) {
		/* Try to get INTx interrupt */
try_intx:
		if (!dd->pcidev->irq) {
			qib_dev_err(dd,
				"irq is 0, BIOS error?  Interrupts won't work\n");
			goto bail;
		}
		ret = request_irq(dd->pcidev->irq, qib_7322intr,
				  IRQF_SHARED, QIB_DRV_NAME, dd);
		if (ret) {
			qib_dev_err(dd,
				"Couldn't setup INTx interrupt (irq=%d): %d\n",
				dd->pcidev->irq, ret);
			goto bail;
		}
		dd->cspec->irq = dd->pcidev->irq;
		dd->cspec->main_int_mask = ~0ULL;
		goto bail;
	}

	/* Try to get MSIx interrupts */
	memset(redirect, 0, sizeof redirect);
	mask = ~0ULL;
	msixnum = 0;
	local_mask = cpumask_of_pcibus(dd->pcidev->bus);
	firstcpu = cpumask_first(local_mask);
	if (firstcpu >= nr_cpu_ids ||
			cpumask_weight(local_mask) == num_online_cpus()) {
		local_mask = topology_core_cpumask(0);
		firstcpu = cpumask_first(local_mask);
	}
	if (firstcpu < nr_cpu_ids) {
		secondcpu = cpumask_next(firstcpu, local_mask);
		if (secondcpu >= nr_cpu_ids)
			secondcpu = firstcpu;
		currrcvcpu = secondcpu;
	}
	for (i = 0; msixnum < dd->cspec->num_msix_entries; i++) {
		irq_handler_t handler;
		void *arg;
		u64 val;
		int lsb, reg, sh;
#ifdef CONFIG_INFINIBAND_QIB_DCA
		int dca = 0;
#endif

		dd->cspec->msix_entries[msixnum].
			name[sizeof(dd->cspec->msix_entries[msixnum].name) - 1]
			= '\0';
		if (i < ARRAY_SIZE(irq_table)) {
			if (irq_table[i].port) {
				/* skip if for a non-configured port */
				if (irq_table[i].port > dd->num_pports)
					continue;
				arg = dd->pport + irq_table[i].port - 1;
			} else
				arg = dd;
#ifdef CONFIG_INFINIBAND_QIB_DCA
			dca = irq_table[i].dca;
#endif
			lsb = irq_table[i].lsb;
			handler = irq_table[i].handler;
			snprintf(dd->cspec->msix_entries[msixnum].name,
				sizeof(dd->cspec->msix_entries[msixnum].name)
				 - 1,
				QIB_DRV_NAME "%d%s", dd->unit,
				irq_table[i].name);
		} else {
			unsigned ctxt;

			ctxt = i - ARRAY_SIZE(irq_table);
			/* per krcvq context receive interrupt */
			arg = dd->rcd[ctxt];
			if (!arg)
				continue;
			if (qib_krcvq01_no_msi && ctxt < 2)
				continue;
#ifdef CONFIG_INFINIBAND_QIB_DCA
			dca = 1;
#endif
			lsb = QIB_I_RCVAVAIL_LSB + ctxt;
			handler = qib_7322pintr;
			snprintf(dd->cspec->msix_entries[msixnum].name,
				sizeof(dd->cspec->msix_entries[msixnum].name)
				 - 1,
				QIB_DRV_NAME "%d (kctx)", dd->unit);
		}
		ret = request_irq(
			dd->cspec->msix_entries[msixnum].msix.vector,
			handler, 0, dd->cspec->msix_entries[msixnum].name,
			arg);
		if (ret) {
			/*
			 * Shouldn't happen since the enable said we could
			 * have as many as we are trying to setup here.
			 */
			qib_dev_err(dd,
				"Couldn't setup MSIx interrupt (vec=%d, irq=%d): %d\n",
				msixnum,
				dd->cspec->msix_entries[msixnum].msix.vector,
				ret);
			qib_7322_nomsix(dd);
			goto try_intx;
		}
		dd->cspec->msix_entries[msixnum].arg = arg;
#ifdef CONFIG_INFINIBAND_QIB_DCA
		dd->cspec->msix_entries[msixnum].dca = dca;
		dd->cspec->msix_entries[msixnum].rcv =
			handler == qib_7322pintr;
#endif
		if (lsb >= 0) {
			reg = lsb / IBA7322_REDIRECT_VEC_PER_REG;
			sh = (lsb % IBA7322_REDIRECT_VEC_PER_REG) *
				SYM_LSB(IntRedirect0, vec1);
			mask &= ~(1ULL << lsb);
			redirect[reg] |= ((u64) msixnum) << sh;
		}
		val = qib_read_kreg64(dd, 2 * msixnum + 1 +
			(QIB_7322_MsixTable_OFFS / sizeof(u64)));
		if (firstcpu < nr_cpu_ids &&
			zalloc_cpumask_var(
				&dd->cspec->msix_entries[msixnum].mask,
				GFP_KERNEL)) {
			if (handler == qib_7322pintr) {
				cpumask_set_cpu(currrcvcpu,
					dd->cspec->msix_entries[msixnum].mask);
				currrcvcpu = cpumask_next(currrcvcpu,
					local_mask);
				if (currrcvcpu >= nr_cpu_ids)
					currrcvcpu = secondcpu;
			} else {
				cpumask_set_cpu(firstcpu,
					dd->cspec->msix_entries[msixnum].mask);
			}
			irq_set_affinity_hint(
				dd->cspec->msix_entries[msixnum].msix.vector,
				dd->cspec->msix_entries[msixnum].mask);
		}
		msixnum++;
	}
	/* Initialize the vector mapping */
	for (i = 0; i < ARRAY_SIZE(redirect); i++)
		qib_write_kreg(dd, kr_intredirect + i, redirect[i]);
	dd->cspec->main_int_mask = mask;
	tasklet_init(&dd->error_tasklet, qib_error_tasklet,
		(unsigned long)dd);
bail:;
}

/**
 * qib_7322_boardname - fill in the board name and note features
 * @dd: the qlogic_ib device
 *
 * info will be based on the board revision register
 */
static unsigned qib_7322_boardname(struct qib_devdata *dd)
{
	/* Will need enumeration of board-types here */
	char *n;
	u32 boardid, namelen;
	unsigned features = DUAL_PORT_CAP;

	boardid = SYM_FIELD(dd->revision, Revision, BoardID);

	switch (boardid) {
	case 0:
		n = "InfiniPath_QLE7342_Emulation";
		break;
	case 1:
		n = "InfiniPath_QLE7340";
		dd->flags |= QIB_HAS_QSFP;
		features = PORT_SPD_CAP;
		break;
	case 2:
		n = "InfiniPath_QLE7342";
		dd->flags |= QIB_HAS_QSFP;
		break;
	case 3:
		n = "InfiniPath_QMI7342";
		break;
	case 4:
		n = "InfiniPath_Unsupported7342";
		qib_dev_err(dd, "Unsupported version of QMH7342\n");
		features = 0;
		break;
	case BOARD_QMH7342:
		n = "InfiniPath_QMH7342";
		features = 0x24;
		break;
	case BOARD_QME7342:
		n = "InfiniPath_QME7342";
		break;
	case 8:
		n = "InfiniPath_QME7362";
		dd->flags |= QIB_HAS_QSFP;
		break;
	case 15:
		n = "InfiniPath_QLE7342_TEST";
		dd->flags |= QIB_HAS_QSFP;
		break;
	default:
		n = "InfiniPath_QLE73xy_UNKNOWN";
		qib_dev_err(dd, "Unknown 7322 board type %u\n", boardid);
		break;
	}
	dd->board_atten = 1; /* index into txdds_Xdr */

	namelen = strlen(n) + 1;
	dd->boardname = kmalloc(namelen, GFP_KERNEL);
	if (!dd->boardname)
		qib_dev_err(dd, "Failed allocation for board name: %s\n", n);
	else
		snprintf(dd->boardname, namelen, "%s", n);

	snprintf(dd->boardversion, sizeof(dd->boardversion),
		 "ChipABI %u.%u, %s, InfiniPath%u %u.%u, SW Compat %u\n",
		 QIB_CHIP_VERS_MAJ, QIB_CHIP_VERS_MIN, dd->boardname,
		 (unsigned)SYM_FIELD(dd->revision, Revision_R, Arch),
		 dd->majrev, dd->minrev,
		 (unsigned)SYM_FIELD(dd->revision, Revision_R, SW));

	if (qib_singleport && (features >> PORT_SPD_CAP_SHIFT) & PORT_SPD_CAP) {
		qib_devinfo(dd->pcidev,
			"IB%u: Forced to single port mode by module parameter\n",
			dd->unit);
		features &= PORT_SPD_CAP;
	}

	return features;
}

/*
 * This routine sleeps, so it can only be called from user context, not
 * from interrupt context.
 */
static int qib_do_7322_reset(struct qib_devdata *dd)
{
	u64 val;
	u64 *msix_vecsave;
	int i, msix_entries, ret = 1;
	u16 cmdval;
	u8 int_line, clinesz;
	unsigned long flags;

	/* Use dev_err so it shows up in logs, etc. */
	qib_dev_err(dd, "Resetting InfiniPath unit %u\n", dd->unit);

	qib_pcie_getcmd(dd, &cmdval, &int_line, &clinesz);

	msix_entries = dd->cspec->num_msix_entries;

	/* no interrupts till re-initted */
	qib_7322_set_intr_state(dd, 0);

	if (msix_entries) {
		qib_7322_nomsix(dd);
		/* can be up to 512 bytes, too big for stack */
		msix_vecsave = kmalloc(2 * dd->cspec->num_msix_entries *
			sizeof(u64), GFP_KERNEL);
		if (!msix_vecsave)
			qib_dev_err(dd, "No mem to save MSIx data\n");
	} else
		msix_vecsave = NULL;

	/*
	 * Core PCI (as of 2.6.18) doesn't save or rewrite the full vector
	 * info that is set up by the BIOS, so we have to save and restore
	 * it ourselves.   There is some risk something could change it,
	 * after we save it, but since we have disabled the MSIx, it
	 * shouldn't be touched...
	 */
	for (i = 0; i < msix_entries; i++) {
		u64 vecaddr, vecdata;
		vecaddr = qib_read_kreg64(dd, 2 * i +
				  (QIB_7322_MsixTable_OFFS / sizeof(u64)));
		vecdata = qib_read_kreg64(dd, 1 + 2 * i +
				  (QIB_7322_MsixTable_OFFS / sizeof(u64)));
		if (msix_vecsave) {
			msix_vecsave[2 * i] = vecaddr;
			/* save it without the masked bit set */
			msix_vecsave[1 + 2 * i] = vecdata & ~0x100000000ULL;
		}
	}

	dd->pport->cpspec->ibdeltainprog = 0;
	dd->pport->cpspec->ibsymdelta = 0;
	dd->pport->cpspec->iblnkerrdelta = 0;
	dd->pport->cpspec->ibmalfdelta = 0;
	dd->int_counter = 0; /* so we check interrupts work again */

	/*
	 * Keep chip from being accessed until we are ready.  Use
	 * writeq() directly, to allow the write even though QIB_PRESENT
	 * isn't set.
	 */
	dd->flags &= ~(QIB_INITTED | QIB_PRESENT | QIB_BADINTR);
	dd->flags |= QIB_DOING_RESET;
	val = dd->control | QLOGIC_IB_C_RESET;
	writeq(val, &dd->kregbase[kr_control]);

	for (i = 1; i <= 5; i++) {
		/*
		 * Allow MBIST, etc. to complete; longer on each retry.
		 * We sometimes get machine checks from bus timeout if no
		 * response, so for now, make it *really* long.
		 */
		msleep(1000 + (1 + i) * 3000);

		qib_pcie_reenable(dd, cmdval, int_line, clinesz);

		/*
		 * Use readq directly, so we don't need to mark it as PRESENT
		 * until we get a successful indication that all is well.
		 */
		val = readq(&dd->kregbase[kr_revision]);
		if (val == dd->revision)
			break;
		if (i == 5) {
			qib_dev_err(dd,
				"Failed to initialize after reset, unusable\n");
			ret = 0;
			goto  bail;
		}
	}

	dd->flags |= QIB_PRESENT; /* it's back */

	if (msix_entries) {
		/* restore the MSIx vector address and data if saved above */
		for (i = 0; i < msix_entries; i++) {
			dd->cspec->msix_entries[i].msix.entry = i;
			if (!msix_vecsave || !msix_vecsave[2 * i])
				continue;
			qib_write_kreg(dd, 2 * i +
				(QIB_7322_MsixTable_OFFS / sizeof(u64)),
				msix_vecsave[2 * i]);
			qib_write_kreg(dd, 1 + 2 * i +
				(QIB_7322_MsixTable_OFFS / sizeof(u64)),
				msix_vecsave[1 + 2 * i]);
		}
	}

	/* initialize the remaining registers.  */
	for (i = 0; i < dd->num_pports; ++i)
		write_7322_init_portregs(&dd->pport[i]);
	write_7322_initregs(dd);

	if (qib_pcie_params(dd, dd->lbus_width,
			    &dd->cspec->num_msix_entries,
			    dd->cspec->msix_entries))
		qib_dev_err(dd,
			"Reset failed to setup PCIe or interrupts; continuing anyway\n");

	qib_setup_7322_interrupt(dd, 1);

	for (i = 0; i < dd->num_pports; ++i) {
		struct qib_pportdata *ppd = &dd->pport[i];

		spin_lock_irqsave(&ppd->lflags_lock, flags);
		ppd->lflags |= QIBL_IB_FORCE_NOTIFY;
		ppd->lflags &= ~QIBL_IB_AUTONEG_FAILED;
		spin_unlock_irqrestore(&ppd->lflags_lock, flags);
	}

bail:
	dd->flags &= ~QIB_DOING_RESET; /* OK or not, no longer resetting */
	kfree(msix_vecsave);
	return ret;
}

/**
 * qib_7322_put_tid - write a TID to the chip
 * @dd: the qlogic_ib device
 * @tidptr: pointer to the expected TID (in chip) to update
 * @tidtype: 0 for eager, 1 for expected
 * @pa: physical address of in memory buffer; tidinvalid if freeing
 */
static void qib_7322_put_tid(struct qib_devdata *dd, u64 __iomem *tidptr,
			     u32 type, unsigned long pa)
{
	if (!(dd->flags & QIB_PRESENT))
		return;
	if (pa != dd->tidinvalid) {
		u64 chippa = pa >> IBA7322_TID_PA_SHIFT;

		/* paranoia checks */
		if (pa != (chippa << IBA7322_TID_PA_SHIFT)) {
			qib_dev_err(dd, "Physaddr %lx not 2KB aligned!\n",
				    pa);
			return;
		}
		if (chippa >= (1UL << IBA7322_TID_SZ_SHIFT)) {
			qib_dev_err(dd,
				"Physical page address 0x%lx larger than supported\n",
				pa);
			return;
		}

		if (type == RCVHQ_RCV_TYPE_EAGER)
			chippa |= dd->tidtemplate;
		else /* for now, always full 4KB page */
			chippa |= IBA7322_TID_SZ_4K;
		pa = chippa;
	}
	writeq(pa, tidptr);
	mmiowb();
}

/**
 * qib_7322_clear_tids - clear all TID entries for a ctxt, expected and eager
 * @dd: the qlogic_ib device
 * @ctxt: the ctxt
 *
 * clear all TID entries for a ctxt, expected and eager.
 * Used from qib_close().
 */
static void qib_7322_clear_tids(struct qib_devdata *dd,
				struct qib_ctxtdata *rcd)
{
	u64 __iomem *tidbase;
	unsigned long tidinv;
	u32 ctxt;
	int i;

	if (!dd->kregbase || !rcd)
		return;

	ctxt = rcd->ctxt;

	tidinv = dd->tidinvalid;
	tidbase = (u64 __iomem *)
		((char __iomem *) dd->kregbase +
		 dd->rcvtidbase +
		 ctxt * dd->rcvtidcnt * sizeof(*tidbase));

	for (i = 0; i < dd->rcvtidcnt; i++)
		qib_7322_put_tid(dd, &tidbase[i], RCVHQ_RCV_TYPE_EXPECTED,
				 tidinv);

	tidbase = (u64 __iomem *)
		((char __iomem *) dd->kregbase +
		 dd->rcvegrbase +
		 rcd->rcvegr_tid_base * sizeof(*tidbase));

	for (i = 0; i < rcd->rcvegrcnt; i++)
		qib_7322_put_tid(dd, &tidbase[i], RCVHQ_RCV_TYPE_EAGER,
				 tidinv);
}

/**
 * qib_7322_tidtemplate - setup constants for TID updates
 * @dd: the qlogic_ib device
 *
 * We setup stuff that we use a lot, to avoid calculating each time
 */
static void qib_7322_tidtemplate(struct qib_devdata *dd)
{
	/*
	 * For now, we always allocate 4KB buffers (at init) so we can
	 * receive max size packets.  We may want a module parameter to
	 * specify 2KB or 4KB and/or make it per port instead of per device
	 * for those who want to reduce memory footprint.  Note that the
	 * rcvhdrentsize size must be large enough to hold the largest
	 * IB header (currently 96 bytes) that we expect to handle (plus of
	 * course the 2 dwords of RHF).
	 */
	if (dd->rcvegrbufsize == 2048)
		dd->tidtemplate = IBA7322_TID_SZ_2K;
	else if (dd->rcvegrbufsize == 4096)
		dd->tidtemplate = IBA7322_TID_SZ_4K;
	dd->tidinvalid = 0;
}

/**
 * qib_init_7322_get_base_info - set chip-specific flags for user code
 * @rcd: the qlogic_ib ctxt
 * @kbase: qib_base_info pointer
 *
 * We set the PCIE flag because the lower bandwidth on PCIe vs
 * HyperTransport can affect some user packet algorithims.
 */

static int qib_7322_get_base_info(struct qib_ctxtdata *rcd,
				  struct qib_base_info *kinfo)
{
	kinfo->spi_runtime_flags |= QIB_RUNTIME_CTXT_MSB_IN_QP |
		QIB_RUNTIME_PCIE | QIB_RUNTIME_NODMA_RTAIL |
		QIB_RUNTIME_HDRSUPP | QIB_RUNTIME_SDMA;
	if (rcd->dd->cspec->r1)
		kinfo->spi_runtime_flags |= QIB_RUNTIME_RCHK;
	if (rcd->dd->flags & QIB_USE_SPCL_TRIG)
		kinfo->spi_runtime_flags |= QIB_RUNTIME_SPECIAL_TRIGGER;

	return 0;
}

static struct qib_message_header *
qib_7322_get_msgheader(struct qib_devdata *dd, __le32 *rhf_addr)
{
	u32 offset = qib_hdrget_offset(rhf_addr);

	return (struct qib_message_header *)
		(rhf_addr - dd->rhf_offset + offset);
}

/*
 * Configure number of contexts.
 */
static void qib_7322_config_ctxts(struct qib_devdata *dd)
{
	unsigned long flags;
	u32 nchipctxts;

	nchipctxts = qib_read_kreg32(dd, kr_contextcnt);
	dd->cspec->numctxts = nchipctxts;
	if (qib_n_krcv_queues > 1 && dd->num_pports) {
		dd->first_user_ctxt = NUM_IB_PORTS +
			(qib_n_krcv_queues - 1) * dd->num_pports;
		if (dd->first_user_ctxt > nchipctxts)
			dd->first_user_ctxt = nchipctxts;
		dd->n_krcv_queues = dd->first_user_ctxt / dd->num_pports;
	} else {
		dd->first_user_ctxt = NUM_IB_PORTS;
		dd->n_krcv_queues = 1;
	}

	if (!qib_cfgctxts) {
		int nctxts = dd->first_user_ctxt + num_online_cpus();

		if (nctxts <= 6)
			dd->ctxtcnt = 6;
		else if (nctxts <= 10)
			dd->ctxtcnt = 10;
		else if (nctxts <= nchipctxts)
			dd->ctxtcnt = nchipctxts;
	} else if (qib_cfgctxts < dd->num_pports)
		dd->ctxtcnt = dd->num_pports;
	else if (qib_cfgctxts <= nchipctxts)
		dd->ctxtcnt = qib_cfgctxts;
	if (!dd->ctxtcnt) /* none of the above, set to max */
		dd->ctxtcnt = nchipctxts;

	/*
	 * Chip can be configured for 6, 10, or 18 ctxts, and choice
	 * affects number of eager TIDs per ctxt (1K, 2K, 4K).
	 * Lock to be paranoid about later motion, etc.
	 */
	spin_lock_irqsave(&dd->cspec->rcvmod_lock, flags);
	if (dd->ctxtcnt > 10)
		dd->rcvctrl |= 2ULL << SYM_LSB(RcvCtrl, ContextCfg);
	else if (dd->ctxtcnt > 6)
		dd->rcvctrl |= 1ULL << SYM_LSB(RcvCtrl, ContextCfg);
	/* else configure for default 6 receive ctxts */

	/* The XRC opcode is 5. */
	dd->rcvctrl |= 5ULL << SYM_LSB(RcvCtrl, XrcTypeCode);

	/*
	 * RcvCtrl *must* be written here so that the
	 * chip understands how to change rcvegrcnt below.
	 */
	qib_write_kreg(dd, kr_rcvctrl, dd->rcvctrl);
	spin_unlock_irqrestore(&dd->cspec->rcvmod_lock, flags);

	/* kr_rcvegrcnt changes based on the number of contexts enabled */
	dd->cspec->rcvegrcnt = qib_read_kreg32(dd, kr_rcvegrcnt);
	if (qib_rcvhdrcnt)
		dd->rcvhdrcnt = max(dd->cspec->rcvegrcnt, qib_rcvhdrcnt);
	else
		dd->rcvhdrcnt = 2 * max(dd->cspec->rcvegrcnt,
				    dd->num_pports > 1 ? 1024U : 2048U);
}

static int qib_7322_get_ib_cfg(struct qib_pportdata *ppd, int which)
{

	int lsb, ret = 0;
	u64 maskr; /* right-justified mask */

	switch (which) {

	case QIB_IB_CFG_LWID_ENB: /* Get allowed Link-width */
		ret = ppd->link_width_enabled;
		goto done;

	case QIB_IB_CFG_LWID: /* Get currently active Link-width */
		ret = ppd->link_width_active;
		goto done;

	case QIB_IB_CFG_SPD_ENB: /* Get allowed Link speeds */
		ret = ppd->link_speed_enabled;
		goto done;

	case QIB_IB_CFG_SPD: /* Get current Link spd */
		ret = ppd->link_speed_active;
		goto done;

	case QIB_IB_CFG_RXPOL_ENB: /* Get Auto-RX-polarity enable */
		lsb = SYM_LSB(IBCCtrlB_0, IB_POLARITY_REV_SUPP);
		maskr = SYM_RMASK(IBCCtrlB_0, IB_POLARITY_REV_SUPP);
		break;

	case QIB_IB_CFG_LREV_ENB: /* Get Auto-Lane-reversal enable */
		lsb = SYM_LSB(IBCCtrlB_0, IB_LANE_REV_SUPPORTED);
		maskr = SYM_RMASK(IBCCtrlB_0, IB_LANE_REV_SUPPORTED);
		break;

	case QIB_IB_CFG_LINKLATENCY:
		ret = qib_read_kreg_port(ppd, krp_ibcstatus_b) &
			SYM_MASK(IBCStatusB_0, LinkRoundTripLatency);
		goto done;

	case QIB_IB_CFG_OP_VLS:
		ret = ppd->vls_operational;
		goto done;

	case QIB_IB_CFG_VL_HIGH_CAP:
		ret = 16;
		goto done;

	case QIB_IB_CFG_VL_LOW_CAP:
		ret = 16;
		goto done;

	case QIB_IB_CFG_OVERRUN_THRESH: /* IB overrun threshold */
		ret = SYM_FIELD(ppd->cpspec->ibcctrl_a, IBCCtrlA_0,
				OverrunThreshold);
		goto done;

	case QIB_IB_CFG_PHYERR_THRESH: /* IB PHY error threshold */
		ret = SYM_FIELD(ppd->cpspec->ibcctrl_a, IBCCtrlA_0,
				PhyerrThreshold);
		goto done;

	case QIB_IB_CFG_LINKDEFAULT: /* IB link default (sleep/poll) */
		/* will only take effect when the link state changes */
		ret = (ppd->cpspec->ibcctrl_a &
		       SYM_MASK(IBCCtrlA_0, LinkDownDefaultState)) ?
			IB_LINKINITCMD_SLEEP : IB_LINKINITCMD_POLL;
		goto done;

	case QIB_IB_CFG_HRTBT: /* Get Heartbeat off/enable/auto */
		lsb = IBA7322_IBC_HRTBT_LSB;
		maskr = IBA7322_IBC_HRTBT_RMASK; /* OR of AUTO and ENB */
		break;

	case QIB_IB_CFG_PMA_TICKS:
		/*
		 * 0x00 = 10x link transfer rate or 4 nsec. for 2.5Gbs
		 * Since the clock is always 250MHz, the value is 3, 1 or 0.
		 */
		if (ppd->link_speed_active == QIB_IB_QDR)
			ret = 3;
		else if (ppd->link_speed_active == QIB_IB_DDR)
			ret = 1;
		else
			ret = 0;
		goto done;

	default:
		ret = -EINVAL;
		goto done;
	}
	ret = (int)((ppd->cpspec->ibcctrl_b >> lsb) & maskr);
done:
	return ret;
}

/*
 * Below again cribbed liberally from older version. Do not lean
 * heavily on it.
 */
#define IBA7322_IBC_DLIDLMC_SHIFT QIB_7322_IBCCtrlB_0_IB_DLID_LSB
#define IBA7322_IBC_DLIDLMC_MASK (QIB_7322_IBCCtrlB_0_IB_DLID_RMASK \
	| (QIB_7322_IBCCtrlB_0_IB_DLID_MASK_RMASK << 16))

static int qib_7322_set_ib_cfg(struct qib_pportdata *ppd, int which, u32 val)
{
	struct qib_devdata *dd = ppd->dd;
	u64 maskr; /* right-justified mask */
	int lsb, ret = 0;
	u16 lcmd, licmd;
	unsigned long flags;

	switch (which) {
	case QIB_IB_CFG_LIDLMC:
		/*
		 * Set LID and LMC. Combined to avoid possible hazard
		 * caller puts LMC in 16MSbits, DLID in 16LSbits of val
		 */
		lsb = IBA7322_IBC_DLIDLMC_SHIFT;
		maskr = IBA7322_IBC_DLIDLMC_MASK;
		/*
		 * For header-checking, the SLID in the packet will
		 * be masked with SendIBSLMCMask, and compared
		 * with SendIBSLIDAssignMask. Make sure we do not
		 * set any bits not covered by the mask, or we get
		 * false-positives.
		 */
		qib_write_kreg_port(ppd, krp_sendslid,
				    val & (val >> 16) & SendIBSLIDAssignMask);
		qib_write_kreg_port(ppd, krp_sendslidmask,
				    (val >> 16) & SendIBSLMCMask);
		break;

	case QIB_IB_CFG_LWID_ENB: /* set allowed Link-width */
		ppd->link_width_enabled = val;
		/* convert IB value to chip register value */
		if (val == IB_WIDTH_1X)
			val = 0;
		else if (val == IB_WIDTH_4X)
			val = 1;
		else
			val = 3;
		maskr = SYM_RMASK(IBCCtrlB_0, IB_NUM_CHANNELS);
		lsb = SYM_LSB(IBCCtrlB_0, IB_NUM_CHANNELS);
		break;

	case QIB_IB_CFG_SPD_ENB: /* set allowed Link speeds */
		/*
		 * As with width, only write the actual register if the
		 * link is currently down, otherwise takes effect on next
		 * link change.  Since setting is being explicitly requested
		 * (via MAD or sysfs), clear autoneg failure status if speed
		 * autoneg is enabled.
		 */
		ppd->link_speed_enabled = val;
		val <<= IBA7322_IBC_SPEED_LSB;
		maskr = IBA7322_IBC_SPEED_MASK | IBA7322_IBC_IBTA_1_2_MASK |
			IBA7322_IBC_MAX_SPEED_MASK;
		if (val & (val - 1)) {
			/* Muliple speeds enabled */
			val |= IBA7322_IBC_IBTA_1_2_MASK |
				IBA7322_IBC_MAX_SPEED_MASK;
			spin_lock_irqsave(&ppd->lflags_lock, flags);
			ppd->lflags &= ~QIBL_IB_AUTONEG_FAILED;
			spin_unlock_irqrestore(&ppd->lflags_lock, flags);
		} else if (val & IBA7322_IBC_SPEED_QDR)
			val |= IBA7322_IBC_IBTA_1_2_MASK;
		/* IBTA 1.2 mode + min/max + speed bits are contiguous */
		lsb = SYM_LSB(IBCCtrlB_0, IB_ENHANCED_MODE);
		break;

	case QIB_IB_CFG_RXPOL_ENB: /* set Auto-RX-polarity enable */
		lsb = SYM_LSB(IBCCtrlB_0, IB_POLARITY_REV_SUPP);
		maskr = SYM_RMASK(IBCCtrlB_0, IB_POLARITY_REV_SUPP);
		break;

	case QIB_IB_CFG_LREV_ENB: /* set Auto-Lane-reversal enable */
		lsb = SYM_LSB(IBCCtrlB_0, IB_LANE_REV_SUPPORTED);
		maskr = SYM_RMASK(IBCCtrlB_0, IB_LANE_REV_SUPPORTED);
		break;

	case QIB_IB_CFG_OVERRUN_THRESH: /* IB overrun threshold */
		maskr = SYM_FIELD(ppd->cpspec->ibcctrl_a, IBCCtrlA_0,
				  OverrunThreshold);
		if (maskr != val) {
			ppd->cpspec->ibcctrl_a &=
				~SYM_MASK(IBCCtrlA_0, OverrunThreshold);
			ppd->cpspec->ibcctrl_a |= (u64) val <<
				SYM_LSB(IBCCtrlA_0, OverrunThreshold);
			qib_write_kreg_port(ppd, krp_ibcctrl_a,
					    ppd->cpspec->ibcctrl_a);
			qib_write_kreg(dd, kr_scratch, 0ULL);
		}
		goto bail;

	case QIB_IB_CFG_PHYERR_THRESH: /* IB PHY error threshold */
		maskr = SYM_FIELD(ppd->cpspec->ibcctrl_a, IBCCtrlA_0,
				  PhyerrThreshold);
		if (maskr != val) {
			ppd->cpspec->ibcctrl_a &=
				~SYM_MASK(IBCCtrlA_0, PhyerrThreshold);
			ppd->cpspec->ibcctrl_a |= (u64) val <<
				SYM_LSB(IBCCtrlA_0, PhyerrThreshold);
			qib_write_kreg_port(ppd, krp_ibcctrl_a,
					    ppd->cpspec->ibcctrl_a);
			qib_write_kreg(dd, kr_scratch, 0ULL);
		}
		goto bail;

	case QIB_IB_CFG_PKEYS: /* update pkeys */
		maskr = (u64) ppd->pkeys[0] | ((u64) ppd->pkeys[1] << 16) |
			((u64) ppd->pkeys[2] << 32) |
			((u64) ppd->pkeys[3] << 48);
		qib_write_kreg_port(ppd, krp_partitionkey, maskr);
		goto bail;

	case QIB_IB_CFG_LINKDEFAULT: /* IB link default (sleep/poll) */
		/* will only take effect when the link state changes */
		if (val == IB_LINKINITCMD_POLL)
			ppd->cpspec->ibcctrl_a &=
				~SYM_MASK(IBCCtrlA_0, LinkDownDefaultState);
		else /* SLEEP */
			ppd->cpspec->ibcctrl_a |=
				SYM_MASK(IBCCtrlA_0, LinkDownDefaultState);
		qib_write_kreg_port(ppd, krp_ibcctrl_a, ppd->cpspec->ibcctrl_a);
		qib_write_kreg(dd, kr_scratch, 0ULL);
		goto bail;

	case QIB_IB_CFG_MTU: /* update the MTU in IBC */
		/*
		 * Update our housekeeping variables, and set IBC max
		 * size, same as init code; max IBC is max we allow in
		 * buffer, less the qword pbc, plus 1 for ICRC, in dwords
		 * Set even if it's unchanged, print debug message only
		 * on changes.
		 */
		val = (ppd->ibmaxlen >> 2) + 1;
		ppd->cpspec->ibcctrl_a &= ~SYM_MASK(IBCCtrlA_0, MaxPktLen);
		ppd->cpspec->ibcctrl_a |= (u64)val <<
			SYM_LSB(IBCCtrlA_0, MaxPktLen);
		qib_write_kreg_port(ppd, krp_ibcctrl_a,
				    ppd->cpspec->ibcctrl_a);
		qib_write_kreg(dd, kr_scratch, 0ULL);
		goto bail;

	case QIB_IB_CFG_LSTATE: /* set the IB link state */
		switch (val & 0xffff0000) {
		case IB_LINKCMD_DOWN:
			lcmd = QLOGIC_IB_IBCC_LINKCMD_DOWN;
			ppd->cpspec->ibmalfusesnap = 1;
			ppd->cpspec->ibmalfsnap = read_7322_creg32_port(ppd,
				crp_errlink);
			if (!ppd->cpspec->ibdeltainprog &&
			    qib_compat_ddr_negotiate) {
				ppd->cpspec->ibdeltainprog = 1;
				ppd->cpspec->ibsymsnap =
					read_7322_creg32_port(ppd,
							      crp_ibsymbolerr);
				ppd->cpspec->iblnkerrsnap =
					read_7322_creg32_port(ppd,
						      crp_iblinkerrrecov);
			}
			break;

		case IB_LINKCMD_ARMED:
			lcmd = QLOGIC_IB_IBCC_LINKCMD_ARMED;
			if (ppd->cpspec->ibmalfusesnap) {
				ppd->cpspec->ibmalfusesnap = 0;
				ppd->cpspec->ibmalfdelta +=
					read_7322_creg32_port(ppd,
							      crp_errlink) -
					ppd->cpspec->ibmalfsnap;
			}
			break;

		case IB_LINKCMD_ACTIVE:
			lcmd = QLOGIC_IB_IBCC_LINKCMD_ACTIVE;
			break;

		default:
			ret = -EINVAL;
			qib_dev_err(dd, "bad linkcmd req 0x%x\n", val >> 16);
			goto bail;
		}
		switch (val & 0xffff) {
		case IB_LINKINITCMD_NOP:
			licmd = 0;
			break;

		case IB_LINKINITCMD_POLL:
			licmd = QLOGIC_IB_IBCC_LINKINITCMD_POLL;
			break;

		case IB_LINKINITCMD_SLEEP:
			licmd = QLOGIC_IB_IBCC_LINKINITCMD_SLEEP;
			break;

		case IB_LINKINITCMD_DISABLE:
			licmd = QLOGIC_IB_IBCC_LINKINITCMD_DISABLE;
			ppd->cpspec->chase_end = 0;
			/*
			 * stop state chase counter and timer, if running.
			 * wait forpending timer, but don't clear .data (ppd)!
			 */
			if (ppd->cpspec->chase_timer.expires) {
				del_timer_sync(&ppd->cpspec->chase_timer);
				ppd->cpspec->chase_timer.expires = 0;
			}
			break;

		default:
			ret = -EINVAL;
			qib_dev_err(dd, "bad linkinitcmd req 0x%x\n",
				    val & 0xffff);
			goto bail;
		}
		qib_set_ib_7322_lstate(ppd, lcmd, licmd);
		goto bail;

	case QIB_IB_CFG_OP_VLS:
		if (ppd->vls_operational != val) {
			ppd->vls_operational = val;
			set_vls(ppd);
		}
		goto bail;

	case QIB_IB_CFG_VL_HIGH_LIMIT:
		qib_write_kreg_port(ppd, krp_highprio_limit, val);
		goto bail;

	case QIB_IB_CFG_HRTBT: /* set Heartbeat off/enable/auto */
		if (val > 3) {
			ret = -EINVAL;
			goto bail;
		}
		lsb = IBA7322_IBC_HRTBT_LSB;
		maskr = IBA7322_IBC_HRTBT_RMASK; /* OR of AUTO and ENB */
		break;

	case QIB_IB_CFG_PORT:
		/* val is the port number of the switch we are connected to. */
		if (ppd->dd->cspec->r1) {
			cancel_delayed_work(&ppd->cpspec->ipg_work);
			ppd->cpspec->ipg_tries = 0;
		}
		goto bail;

	default:
		ret = -EINVAL;
		goto bail;
	}
	ppd->cpspec->ibcctrl_b &= ~(maskr << lsb);
	ppd->cpspec->ibcctrl_b |= (((u64) val & maskr) << lsb);
	qib_write_kreg_port(ppd, krp_ibcctrl_b, ppd->cpspec->ibcctrl_b);
	qib_write_kreg(dd, kr_scratch, 0);
bail:
	return ret;
}

static int qib_7322_set_loopback(struct qib_pportdata *ppd, const char *what)
{
	int ret = 0;
	u64 val, ctrlb;

	/* only IBC loopback, may add serdes and xgxs loopbacks later */
	if (!strncmp(what, "ibc", 3)) {
		ppd->cpspec->ibcctrl_a |= SYM_MASK(IBCCtrlA_0,
						       Loopback);
		val = 0; /* disable heart beat, so link will come up */
		qib_devinfo(ppd->dd->pcidev, "Enabling IB%u:%u IBC loopback\n",
			 ppd->dd->unit, ppd->port);
	} else if (!strncmp(what, "off", 3)) {
		ppd->cpspec->ibcctrl_a &= ~SYM_MASK(IBCCtrlA_0,
							Loopback);
		/* enable heart beat again */
		val = IBA7322_IBC_HRTBT_RMASK << IBA7322_IBC_HRTBT_LSB;
		qib_devinfo(ppd->dd->pcidev,
			"Disabling IB%u:%u IBC loopback (normal)\n",
			ppd->dd->unit, ppd->port);
	} else
		ret = -EINVAL;
	if (!ret) {
		qib_write_kreg_port(ppd, krp_ibcctrl_a,
				    ppd->cpspec->ibcctrl_a);
		ctrlb = ppd->cpspec->ibcctrl_b & ~(IBA7322_IBC_HRTBT_MASK
					     << IBA7322_IBC_HRTBT_LSB);
		ppd->cpspec->ibcctrl_b = ctrlb | val;
		qib_write_kreg_port(ppd, krp_ibcctrl_b,
				    ppd->cpspec->ibcctrl_b);
		qib_write_kreg(ppd->dd, kr_scratch, 0);
	}
	return ret;
}

static void get_vl_weights(struct qib_pportdata *ppd, unsigned regno,
			   struct ib_vl_weight_elem *vl)
{
	unsigned i;

	for (i = 0; i < 16; i++, regno++, vl++) {
		u32 val = qib_read_kreg_port(ppd, regno);

		vl->vl = (val >> SYM_LSB(LowPriority0_0, VirtualLane)) &
			SYM_RMASK(LowPriority0_0, VirtualLane);
		vl->weight = (val >> SYM_LSB(LowPriority0_0, Weight)) &
			SYM_RMASK(LowPriority0_0, Weight);
	}
}

static void set_vl_weights(struct qib_pportdata *ppd, unsigned regno,
			   struct ib_vl_weight_elem *vl)
{
	unsigned i;

	for (i = 0; i < 16; i++, regno++, vl++) {
		u64 val;

		val = ((vl->vl & SYM_RMASK(LowPriority0_0, VirtualLane)) <<
			SYM_LSB(LowPriority0_0, VirtualLane)) |
		      ((vl->weight & SYM_RMASK(LowPriority0_0, Weight)) <<
			SYM_LSB(LowPriority0_0, Weight));
		qib_write_kreg_port(ppd, regno, val);
	}
	if (!(ppd->p_sendctrl & SYM_MASK(SendCtrl_0, IBVLArbiterEn))) {
		struct qib_devdata *dd = ppd->dd;
		unsigned long flags;

		spin_lock_irqsave(&dd->sendctrl_lock, flags);
		ppd->p_sendctrl |= SYM_MASK(SendCtrl_0, IBVLArbiterEn);
		qib_write_kreg_port(ppd, krp_sendctrl, ppd->p_sendctrl);
		qib_write_kreg(dd, kr_scratch, 0);
		spin_unlock_irqrestore(&dd->sendctrl_lock, flags);
	}
}

static int qib_7322_get_ib_table(struct qib_pportdata *ppd, int which, void *t)
{
	switch (which) {
	case QIB_IB_TBL_VL_HIGH_ARB:
		get_vl_weights(ppd, krp_highprio_0, t);
		break;

	case QIB_IB_TBL_VL_LOW_ARB:
		get_vl_weights(ppd, krp_lowprio_0, t);
		break;

	default:
		return -EINVAL;
	}
	return 0;
}

static int qib_7322_set_ib_table(struct qib_pportdata *ppd, int which, void *t)
{
	switch (which) {
	case QIB_IB_TBL_VL_HIGH_ARB:
		set_vl_weights(ppd, krp_highprio_0, t);
		break;

	case QIB_IB_TBL_VL_LOW_ARB:
		set_vl_weights(ppd, krp_lowprio_0, t);
		break;

	default:
		return -EINVAL;
	}
	return 0;
}

static void qib_update_7322_usrhead(struct qib_ctxtdata *rcd, u64 hd,
				    u32 updegr, u32 egrhd, u32 npkts)
{
	/*
	 * Need to write timeout register before updating rcvhdrhead to ensure
	 * that the timer is enabled on reception of a packet.
	 */
	if (hd >> IBA7322_HDRHEAD_PKTINT_SHIFT)
		adjust_rcv_timeout(rcd, npkts);
	if (updegr)
		qib_write_ureg(rcd->dd, ur_rcvegrindexhead, egrhd, rcd->ctxt);
	mmiowb();
	qib_write_ureg(rcd->dd, ur_rcvhdrhead, hd, rcd->ctxt);
	qib_write_ureg(rcd->dd, ur_rcvhdrhead, hd, rcd->ctxt);
	mmiowb();
}

static u32 qib_7322_hdrqempty(struct qib_ctxtdata *rcd)
{
	u32 head, tail;

	head = qib_read_ureg32(rcd->dd, ur_rcvhdrhead, rcd->ctxt);
	if (rcd->rcvhdrtail_kvaddr)
		tail = qib_get_rcvhdrtail(rcd);
	else
		tail = qib_read_ureg32(rcd->dd, ur_rcvhdrtail, rcd->ctxt);
	return head == tail;
}

#define RCVCTRL_COMMON_MODS (QIB_RCVCTRL_CTXT_ENB | \
	QIB_RCVCTRL_CTXT_DIS | \
	QIB_RCVCTRL_TIDFLOW_ENB | \
	QIB_RCVCTRL_TIDFLOW_DIS | \
	QIB_RCVCTRL_TAILUPD_ENB | \
	QIB_RCVCTRL_TAILUPD_DIS | \
	QIB_RCVCTRL_INTRAVAIL_ENB | \
	QIB_RCVCTRL_INTRAVAIL_DIS | \
	QIB_RCVCTRL_BP_ENB | \
	QIB_RCVCTRL_BP_DIS)

#define RCVCTRL_PORT_MODS (QIB_RCVCTRL_CTXT_ENB | \
	QIB_RCVCTRL_CTXT_DIS | \
	QIB_RCVCTRL_PKEY_DIS | \
	QIB_RCVCTRL_PKEY_ENB)

/*
 * Modify the RCVCTRL register in chip-specific way. This
 * is a function because bit positions and (future) register
 * location is chip-specifc, but the needed operations are
 * generic. <op> is a bit-mask because we often want to
 * do multiple modifications.
 */
static void rcvctrl_7322_mod(struct qib_pportdata *ppd, unsigned int op,
			     int ctxt)
{
	struct qib_devdata *dd = ppd->dd;
	struct qib_ctxtdata *rcd;
	u64 mask, val;
	unsigned long flags;

	spin_lock_irqsave(&dd->cspec->rcvmod_lock, flags);

	if (op & QIB_RCVCTRL_TIDFLOW_ENB)
		dd->rcvctrl |= SYM_MASK(RcvCtrl, TidFlowEnable);
	if (op & QIB_RCVCTRL_TIDFLOW_DIS)
		dd->rcvctrl &= ~SYM_MASK(RcvCtrl, TidFlowEnable);
	if (op & QIB_RCVCTRL_TAILUPD_ENB)
		dd->rcvctrl |= SYM_MASK(RcvCtrl, TailUpd);
	if (op & QIB_RCVCTRL_TAILUPD_DIS)
		dd->rcvctrl &= ~SYM_MASK(RcvCtrl, TailUpd);
	if (op & QIB_RCVCTRL_PKEY_ENB)
		ppd->p_rcvctrl &= ~SYM_MASK(RcvCtrl_0, RcvPartitionKeyDisable);
	if (op & QIB_RCVCTRL_PKEY_DIS)
		ppd->p_rcvctrl |= SYM_MASK(RcvCtrl_0, RcvPartitionKeyDisable);
	if (ctxt < 0) {
		mask = (1ULL << dd->ctxtcnt) - 1;
		rcd = NULL;
	} else {
		mask = (1ULL << ctxt);
		rcd = dd->rcd[ctxt];
	}
	if ((op & QIB_RCVCTRL_CTXT_ENB) && rcd) {
		ppd->p_rcvctrl |=
			(mask << SYM_LSB(RcvCtrl_0, ContextEnableKernel));
		if (!(dd->flags & QIB_NODMA_RTAIL)) {
			op |= QIB_RCVCTRL_TAILUPD_ENB; /* need reg write */
			dd->rcvctrl |= SYM_MASK(RcvCtrl, TailUpd);
		}
		/* Write these registers before the context is enabled. */
		qib_write_kreg_ctxt(dd, krc_rcvhdrtailaddr, ctxt,
				    rcd->rcvhdrqtailaddr_phys);
		qib_write_kreg_ctxt(dd, krc_rcvhdraddr, ctxt,
				    rcd->rcvhdrq_phys);
		rcd->seq_cnt = 1;
	}
	if (op & QIB_RCVCTRL_CTXT_DIS)
		ppd->p_rcvctrl &=
			~(mask << SYM_LSB(RcvCtrl_0, ContextEnableKernel));
	if (op & QIB_RCVCTRL_BP_ENB)
		dd->rcvctrl |= mask << SYM_LSB(RcvCtrl, dontDropRHQFull);
	if (op & QIB_RCVCTRL_BP_DIS)
		dd->rcvctrl &= ~(mask << SYM_LSB(RcvCtrl, dontDropRHQFull));
	if (op & QIB_RCVCTRL_INTRAVAIL_ENB)
		dd->rcvctrl |= (mask << SYM_LSB(RcvCtrl, IntrAvail));
	if (op & QIB_RCVCTRL_INTRAVAIL_DIS)
		dd->rcvctrl &= ~(mask << SYM_LSB(RcvCtrl, IntrAvail));
	/*
	 * Decide which registers to write depending on the ops enabled.
	 * Special case is "flush" (no bits set at all)
	 * which needs to write both.
	 */
	if (op == 0 || (op & RCVCTRL_COMMON_MODS))
		qib_write_kreg(dd, kr_rcvctrl, dd->rcvctrl);
	if (op == 0 || (op & RCVCTRL_PORT_MODS))
		qib_write_kreg_port(ppd, krp_rcvctrl, ppd->p_rcvctrl);
	if ((op & QIB_RCVCTRL_CTXT_ENB) && dd->rcd[ctxt]) {
		/*
		 * Init the context registers also; if we were
		 * disabled, tail and head should both be zero
		 * already from the enable, but since we don't
		 * know, we have to do it explicitly.
		 */
		val = qib_read_ureg32(dd, ur_rcvegrindextail, ctxt);
		qib_write_ureg(dd, ur_rcvegrindexhead, val, ctxt);

		/* be sure enabling write seen; hd/tl should be 0 */
		(void) qib_read_kreg32(dd, kr_scratch);
		val = qib_read_ureg32(dd, ur_rcvhdrtail, ctxt);
		dd->rcd[ctxt]->head = val;
		/* If kctxt, interrupt on next receive. */
		if (ctxt < dd->first_user_ctxt)
			val |= dd->rhdrhead_intr_off;
		qib_write_ureg(dd, ur_rcvhdrhead, val, ctxt);
	} else if ((op & QIB_RCVCTRL_INTRAVAIL_ENB) &&
		dd->rcd[ctxt] && dd->rhdrhead_intr_off) {
		/* arm rcv interrupt */
		val = dd->rcd[ctxt]->head | dd->rhdrhead_intr_off;
		qib_write_ureg(dd, ur_rcvhdrhead, val, ctxt);
	}
	if (op & QIB_RCVCTRL_CTXT_DIS) {
		unsigned f;

		/* Now that the context is disabled, clear these registers. */
		if (ctxt >= 0) {
			qib_write_kreg_ctxt(dd, krc_rcvhdrtailaddr, ctxt, 0);
			qib_write_kreg_ctxt(dd, krc_rcvhdraddr, ctxt, 0);
			for (f = 0; f < NUM_TIDFLOWS_CTXT; f++)
				qib_write_ureg(dd, ur_rcvflowtable + f,
					       TIDFLOW_ERRBITS, ctxt);
		} else {
			unsigned i;

			for (i = 0; i < dd->cfgctxts; i++) {
				qib_write_kreg_ctxt(dd, krc_rcvhdrtailaddr,
						    i, 0);
				qib_write_kreg_ctxt(dd, krc_rcvhdraddr, i, 0);
				for (f = 0; f < NUM_TIDFLOWS_CTXT; f++)
					qib_write_ureg(dd, ur_rcvflowtable + f,
						       TIDFLOW_ERRBITS, i);
			}
		}
	}
	spin_unlock_irqrestore(&dd->cspec->rcvmod_lock, flags);
}

/*
 * Modify the SENDCTRL register in chip-specific way. This
 * is a function where there are multiple such registers with
 * slightly different layouts.
 * The chip doesn't allow back-to-back sendctrl writes, so write
 * the scratch register after writing sendctrl.
 *
 * Which register is written depends on the operation.
 * Most operate on the common register, while
 * SEND_ENB and SEND_DIS operate on the per-port ones.
 * SEND_ENB is included in common because it can change SPCL_TRIG
 */
#define SENDCTRL_COMMON_MODS (\
	QIB_SENDCTRL_CLEAR | \
	QIB_SENDCTRL_AVAIL_DIS | \
	QIB_SENDCTRL_AVAIL_ENB | \
	QIB_SENDCTRL_AVAIL_BLIP | \
	QIB_SENDCTRL_DISARM | \
	QIB_SENDCTRL_DISARM_ALL | \
	QIB_SENDCTRL_SEND_ENB)

#define SENDCTRL_PORT_MODS (\
	QIB_SENDCTRL_CLEAR | \
	QIB_SENDCTRL_SEND_ENB | \
	QIB_SENDCTRL_SEND_DIS | \
	QIB_SENDCTRL_FLUSH)

static void sendctrl_7322_mod(struct qib_pportdata *ppd, u32 op)
{
	struct qib_devdata *dd = ppd->dd;
	u64 tmp_dd_sendctrl;
	unsigned long flags;

	spin_lock_irqsave(&dd->sendctrl_lock, flags);

	/* First the dd ones that are "sticky", saved in shadow */
	if (op & QIB_SENDCTRL_CLEAR)
		dd->sendctrl = 0;
	if (op & QIB_SENDCTRL_AVAIL_DIS)
		dd->sendctrl &= ~SYM_MASK(SendCtrl, SendBufAvailUpd);
	else if (op & QIB_SENDCTRL_AVAIL_ENB) {
		dd->sendctrl |= SYM_MASK(SendCtrl, SendBufAvailUpd);
		if (dd->flags & QIB_USE_SPCL_TRIG)
			dd->sendctrl |= SYM_MASK(SendCtrl, SpecialTriggerEn);
	}

	/* Then the ppd ones that are "sticky", saved in shadow */
	if (op & QIB_SENDCTRL_SEND_DIS)
		ppd->p_sendctrl &= ~SYM_MASK(SendCtrl_0, SendEnable);
	else if (op & QIB_SENDCTRL_SEND_ENB)
		ppd->p_sendctrl |= SYM_MASK(SendCtrl_0, SendEnable);

	if (op & QIB_SENDCTRL_DISARM_ALL) {
		u32 i, last;

		tmp_dd_sendctrl = dd->sendctrl;
		last = dd->piobcnt2k + dd->piobcnt4k + NUM_VL15_BUFS;
		/*
		 * Disarm any buffers that are not yet launched,
		 * disabling updates until done.
		 */
		tmp_dd_sendctrl &= ~SYM_MASK(SendCtrl, SendBufAvailUpd);
		for (i = 0; i < last; i++) {
			qib_write_kreg(dd, kr_sendctrl,
				       tmp_dd_sendctrl |
				       SYM_MASK(SendCtrl, Disarm) | i);
			qib_write_kreg(dd, kr_scratch, 0);
		}
	}

	if (op & QIB_SENDCTRL_FLUSH) {
		u64 tmp_ppd_sendctrl = ppd->p_sendctrl;

		/*
		 * Now drain all the fifos.  The Abort bit should never be
		 * needed, so for now, at least, we don't use it.
		 */
		tmp_ppd_sendctrl |=
			SYM_MASK(SendCtrl_0, TxeDrainRmFifo) |
			SYM_MASK(SendCtrl_0, TxeDrainLaFifo) |
			SYM_MASK(SendCtrl_0, TxeBypassIbc);
		qib_write_kreg_port(ppd, krp_sendctrl, tmp_ppd_sendctrl);
		qib_write_kreg(dd, kr_scratch, 0);
	}

	tmp_dd_sendctrl = dd->sendctrl;

	if (op & QIB_SENDCTRL_DISARM)
		tmp_dd_sendctrl |= SYM_MASK(SendCtrl, Disarm) |
			((op & QIB_7322_SendCtrl_DisarmSendBuf_RMASK) <<
			 SYM_LSB(SendCtrl, DisarmSendBuf));
	if ((op & QIB_SENDCTRL_AVAIL_BLIP) &&
	    (dd->sendctrl & SYM_MASK(SendCtrl, SendBufAvailUpd)))
		tmp_dd_sendctrl &= ~SYM_MASK(SendCtrl, SendBufAvailUpd);

	if (op == 0 || (op & SENDCTRL_COMMON_MODS)) {
		qib_write_kreg(dd, kr_sendctrl, tmp_dd_sendctrl);
		qib_write_kreg(dd, kr_scratch, 0);
	}

	if (op == 0 || (op & SENDCTRL_PORT_MODS)) {
		qib_write_kreg_port(ppd, krp_sendctrl, ppd->p_sendctrl);
		qib_write_kreg(dd, kr_scratch, 0);
	}

	if (op & QIB_SENDCTRL_AVAIL_BLIP) {
		qib_write_kreg(dd, kr_sendctrl, dd->sendctrl);
		qib_write_kreg(dd, kr_scratch, 0);
	}

	spin_unlock_irqrestore(&dd->sendctrl_lock, flags);

	if (op & QIB_SENDCTRL_FLUSH) {
		u32 v;
		/*
		 * ensure writes have hit chip, then do a few
		 * more reads, to allow DMA of pioavail registers
		 * to occur, so in-memory copy is in sync with
		 * the chip.  Not always safe to sleep.
		 */
		v = qib_read_kreg32(dd, kr_scratch);
		qib_write_kreg(dd, kr_scratch, v);
		v = qib_read_kreg32(dd, kr_scratch);
		qib_write_kreg(dd, kr_scratch, v);
		qib_read_kreg32(dd, kr_scratch);
	}
}

#define _PORT_VIRT_FLAG 0x8000U /* "virtual", need adjustments */
#define _PORT_64BIT_FLAG 0x10000U /* not "virtual", but 64bit */
#define _PORT_CNTR_IDXMASK 0x7fffU /* mask off flags above */

/**
 * qib_portcntr_7322 - read a per-port chip counter
 * @ppd: the qlogic_ib pport
 * @creg: the counter to read (not a chip offset)
 */
static u64 qib_portcntr_7322(struct qib_pportdata *ppd, u32 reg)
{
	struct qib_devdata *dd = ppd->dd;
	u64 ret = 0ULL;
	u16 creg;
	/* 0xffff for unimplemented or synthesized counters */
	static const u32 xlator[] = {
		[QIBPORTCNTR_PKTSEND] = crp_pktsend | _PORT_64BIT_FLAG,
		[QIBPORTCNTR_WORDSEND] = crp_wordsend | _PORT_64BIT_FLAG,
		[QIBPORTCNTR_PSXMITDATA] = crp_psxmitdatacount,
		[QIBPORTCNTR_PSXMITPKTS] = crp_psxmitpktscount,
		[QIBPORTCNTR_PSXMITWAIT] = crp_psxmitwaitcount,
		[QIBPORTCNTR_SENDSTALL] = crp_sendstall,
		[QIBPORTCNTR_PKTRCV] = crp_pktrcv | _PORT_64BIT_FLAG,
		[QIBPORTCNTR_PSRCVDATA] = crp_psrcvdatacount,
		[QIBPORTCNTR_PSRCVPKTS] = crp_psrcvpktscount,
		[QIBPORTCNTR_RCVEBP] = crp_rcvebp,
		[QIBPORTCNTR_RCVOVFL] = crp_rcvovfl,
		[QIBPORTCNTR_WORDRCV] = crp_wordrcv | _PORT_64BIT_FLAG,
		[QIBPORTCNTR_RXDROPPKT] = 0xffff, /* not needed  for 7322 */
		[QIBPORTCNTR_RXLOCALPHYERR] = crp_rxotherlocalphyerr,
		[QIBPORTCNTR_RXVLERR] = crp_rxvlerr,
		[QIBPORTCNTR_ERRICRC] = crp_erricrc,
		[QIBPORTCNTR_ERRVCRC] = crp_errvcrc,
		[QIBPORTCNTR_ERRLPCRC] = crp_errlpcrc,
		[QIBPORTCNTR_BADFORMAT] = crp_badformat,
		[QIBPORTCNTR_ERR_RLEN] = crp_err_rlen,
		[QIBPORTCNTR_IBSYMBOLERR] = crp_ibsymbolerr,
		[QIBPORTCNTR_INVALIDRLEN] = crp_invalidrlen,
		[QIBPORTCNTR_UNSUPVL] = crp_txunsupvl,
		[QIBPORTCNTR_EXCESSBUFOVFL] = crp_excessbufferovfl,
		[QIBPORTCNTR_ERRLINK] = crp_errlink,
		[QIBPORTCNTR_IBLINKDOWN] = crp_iblinkdown,
		[QIBPORTCNTR_IBLINKERRRECOV] = crp_iblinkerrrecov,
		[QIBPORTCNTR_LLI] = crp_locallinkintegrityerr,
		[QIBPORTCNTR_VL15PKTDROP] = crp_vl15droppedpkt,
		[QIBPORTCNTR_ERRPKEY] = crp_errpkey,
		/*
		 * the next 3 aren't really counters, but were implemented
		 * as counters in older chips, so still get accessed as
		 * though they were counters from this code.
		 */
		[QIBPORTCNTR_PSINTERVAL] = krp_psinterval,
		[QIBPORTCNTR_PSSTART] = krp_psstart,
		[QIBPORTCNTR_PSSTAT] = krp_psstat,
		/* pseudo-counter, summed for all ports */
		[QIBPORTCNTR_KHDROVFL] = 0xffff,
	};

	if (reg >= ARRAY_SIZE(xlator)) {
		qib_devinfo(ppd->dd->pcidev,
			 "Unimplemented portcounter %u\n", reg);
		goto done;
	}
	creg = xlator[reg] & _PORT_CNTR_IDXMASK;

	/* handle non-counters and special cases first */
	if (reg == QIBPORTCNTR_KHDROVFL) {
		int i;

		/* sum over all kernel contexts (skip if mini_init) */
		for (i = 0; dd->rcd && i < dd->first_user_ctxt; i++) {
			struct qib_ctxtdata *rcd = dd->rcd[i];

			if (!rcd || rcd->ppd != ppd)
				continue;
			ret += read_7322_creg32(dd, cr_base_egrovfl + i);
		}
		goto done;
	} else if (reg == QIBPORTCNTR_RXDROPPKT) {
		/*
		 * Used as part of the synthesis of port_rcv_errors
		 * in the verbs code for IBTA counters.  Not needed for 7322,
		 * because all the errors are already counted by other cntrs.
		 */
		goto done;
	} else if (reg == QIBPORTCNTR_PSINTERVAL ||
		   reg == QIBPORTCNTR_PSSTART || reg == QIBPORTCNTR_PSSTAT) {
		/* were counters in older chips, now per-port kernel regs */
		ret = qib_read_kreg_port(ppd, creg);
		goto done;
	}

	/*
	 * Only fast increment counters are 64 bits; use 32 bit reads to
	 * avoid two independent reads when on Opteron.
	 */
	if (xlator[reg] & _PORT_64BIT_FLAG)
		ret = read_7322_creg_port(ppd, creg);
	else
		ret = read_7322_creg32_port(ppd, creg);
	if (creg == crp_ibsymbolerr) {
		if (ppd->cpspec->ibdeltainprog)
			ret -= ret - ppd->cpspec->ibsymsnap;
		ret -= ppd->cpspec->ibsymdelta;
	} else if (creg == crp_iblinkerrrecov) {
		if (ppd->cpspec->ibdeltainprog)
			ret -= ret - ppd->cpspec->iblnkerrsnap;
		ret -= ppd->cpspec->iblnkerrdelta;
	} else if (creg == crp_errlink)
		ret -= ppd->cpspec->ibmalfdelta;
	else if (creg == crp_iblinkdown)
		ret += ppd->cpspec->iblnkdowndelta;
done:
	return ret;
}

/*
 * Device counter names (not port-specific), one line per stat,
 * single string.  Used by utilities like ipathstats to print the stats
 * in a way which works for different versions of drivers, without changing
 * the utility.  Names need to be 12 chars or less (w/o newline), for proper
 * display by utility.
 * Non-error counters are first.
 * Start of "error" conters is indicated by a leading "E " on the first
 * "error" counter, and doesn't count in label length.
 * The EgrOvfl list needs to be last so we truncate them at the configured
 * context count for the device.
 * cntr7322indices contains the corresponding register indices.
 */
static const char cntr7322names[] =
	"Interrupts\n"
	"HostBusStall\n"
	"E RxTIDFull\n"
	"RxTIDInvalid\n"
	"RxTIDFloDrop\n" /* 7322 only */
	"Ctxt0EgrOvfl\n"
	"Ctxt1EgrOvfl\n"
	"Ctxt2EgrOvfl\n"
	"Ctxt3EgrOvfl\n"
	"Ctxt4EgrOvfl\n"
	"Ctxt5EgrOvfl\n"
	"Ctxt6EgrOvfl\n"
	"Ctxt7EgrOvfl\n"
	"Ctxt8EgrOvfl\n"
	"Ctxt9EgrOvfl\n"
	"Ctx10EgrOvfl\n"
	"Ctx11EgrOvfl\n"
	"Ctx12EgrOvfl\n"
	"Ctx13EgrOvfl\n"
	"Ctx14EgrOvfl\n"
	"Ctx15EgrOvfl\n"
	"Ctx16EgrOvfl\n"
	"Ctx17EgrOvfl\n"
	;

static const u32 cntr7322indices[] = {
	cr_lbint | _PORT_64BIT_FLAG,
	cr_lbstall | _PORT_64BIT_FLAG,
	cr_tidfull,
	cr_tidinvalid,
	cr_rxtidflowdrop,
	cr_base_egrovfl + 0,
	cr_base_egrovfl + 1,
	cr_base_egrovfl + 2,
	cr_base_egrovfl + 3,
	cr_base_egrovfl + 4,
	cr_base_egrovfl + 5,
	cr_base_egrovfl + 6,
	cr_base_egrovfl + 7,
	cr_base_egrovfl + 8,
	cr_base_egrovfl + 9,
	cr_base_egrovfl + 10,
	cr_base_egrovfl + 11,
	cr_base_egrovfl + 12,
	cr_base_egrovfl + 13,
	cr_base_egrovfl + 14,
	cr_base_egrovfl + 15,
	cr_base_egrovfl + 16,
	cr_base_egrovfl + 17,
};

/*
 * same as cntr7322names and cntr7322indices, but for port-specific counters.
 * portcntr7322indices is somewhat complicated by some registers needing
 * adjustments of various kinds, and those are ORed with _PORT_VIRT_FLAG
 */
static const char portcntr7322names[] =
	"TxPkt\n"
	"TxFlowPkt\n"
	"TxWords\n"
	"RxPkt\n"
	"RxFlowPkt\n"
	"RxWords\n"
	"TxFlowStall\n"
	"TxDmaDesc\n"  /* 7220 and 7322-only */
	"E RxDlidFltr\n"  /* 7220 and 7322-only */
	"IBStatusChng\n"
	"IBLinkDown\n"
	"IBLnkRecov\n"
	"IBRxLinkErr\n"
	"IBSymbolErr\n"
	"RxLLIErr\n"
	"RxBadFormat\n"
	"RxBadLen\n"
	"RxBufOvrfl\n"
	"RxEBP\n"
	"RxFlowCtlErr\n"
	"RxICRCerr\n"
	"RxLPCRCerr\n"
	"RxVCRCerr\n"
	"RxInvalLen\n"
	"RxInvalPKey\n"
	"RxPktDropped\n"
	"TxBadLength\n"
	"TxDropped\n"
	"TxInvalLen\n"
	"TxUnderrun\n"
	"TxUnsupVL\n"
	"RxLclPhyErr\n" /* 7220 and 7322-only from here down */
	"RxVL15Drop\n"
	"RxVlErr\n"
	"XcessBufOvfl\n"
	"RxQPBadCtxt\n" /* 7322-only from here down */
	"TXBadHeader\n"
	;

static const u32 portcntr7322indices[] = {
	QIBPORTCNTR_PKTSEND | _PORT_VIRT_FLAG,
	crp_pktsendflow,
	QIBPORTCNTR_WORDSEND | _PORT_VIRT_FLAG,
	QIBPORTCNTR_PKTRCV | _PORT_VIRT_FLAG,
	crp_pktrcvflowctrl,
	QIBPORTCNTR_WORDRCV | _PORT_VIRT_FLAG,
	QIBPORTCNTR_SENDSTALL | _PORT_VIRT_FLAG,
	crp_txsdmadesc | _PORT_64BIT_FLAG,
	crp_rxdlidfltr,
	crp_ibstatuschange,
	QIBPORTCNTR_IBLINKDOWN | _PORT_VIRT_FLAG,
	QIBPORTCNTR_IBLINKERRRECOV | _PORT_VIRT_FLAG,
	QIBPORTCNTR_ERRLINK | _PORT_VIRT_FLAG,
	QIBPORTCNTR_IBSYMBOLERR | _PORT_VIRT_FLAG,
	QIBPORTCNTR_LLI | _PORT_VIRT_FLAG,
	QIBPORTCNTR_BADFORMAT | _PORT_VIRT_FLAG,
	QIBPORTCNTR_ERR_RLEN | _PORT_VIRT_FLAG,
	QIBPORTCNTR_RCVOVFL | _PORT_VIRT_FLAG,
	QIBPORTCNTR_RCVEBP | _PORT_VIRT_FLAG,
	crp_rcvflowctrlviol,
	QIBPORTCNTR_ERRICRC | _PORT_VIRT_FLAG,
	QIBPORTCNTR_ERRLPCRC | _PORT_VIRT_FLAG,
	QIBPORTCNTR_ERRVCRC | _PORT_VIRT_FLAG,
	QIBPORTCNTR_INVALIDRLEN | _PORT_VIRT_FLAG,
	QIBPORTCNTR_ERRPKEY | _PORT_VIRT_FLAG,
	QIBPORTCNTR_RXDROPPKT | _PORT_VIRT_FLAG,
	crp_txminmaxlenerr,
	crp_txdroppedpkt,
	crp_txlenerr,
	crp_txunderrun,
	crp_txunsupvl,
	QIBPORTCNTR_RXLOCALPHYERR | _PORT_VIRT_FLAG,
	QIBPORTCNTR_VL15PKTDROP | _PORT_VIRT_FLAG,
	QIBPORTCNTR_RXVLERR | _PORT_VIRT_FLAG,
	QIBPORTCNTR_EXCESSBUFOVFL | _PORT_VIRT_FLAG,
	crp_rxqpinvalidctxt,
	crp_txhdrerr,
};

/* do all the setup to make the counter reads efficient later */
static void init_7322_cntrnames(struct qib_devdata *dd)
{
	int i, j = 0;
	char *s;

	for (i = 0, s = (char *)cntr7322names; s && j <= dd->cfgctxts;
	     i++) {
		/* we always have at least one counter before the egrovfl */
		if (!j && !strncmp("Ctxt0EgrOvfl", s + 1, 12))
			j = 1;
		s = strchr(s + 1, '\n');
		if (s && j)
			j++;
	}
	dd->cspec->ncntrs = i;
	if (!s)
		/* full list; size is without terminating null */
		dd->cspec->cntrnamelen = sizeof(cntr7322names) - 1;
	else
		dd->cspec->cntrnamelen = 1 + s - cntr7322names;
	dd->cspec->cntrs = kmalloc(dd->cspec->ncntrs
		* sizeof(u64), GFP_KERNEL);
	if (!dd->cspec->cntrs)
		qib_dev_err(dd, "Failed allocation for counters\n");

	for (i = 0, s = (char *)portcntr7322names; s; i++)
		s = strchr(s + 1, '\n');
	dd->cspec->nportcntrs = i - 1;
	dd->cspec->portcntrnamelen = sizeof(portcntr7322names) - 1;
	for (i = 0; i < dd->num_pports; ++i) {
		dd->pport[i].cpspec->portcntrs = kmalloc(dd->cspec->nportcntrs
			* sizeof(u64), GFP_KERNEL);
		if (!dd->pport[i].cpspec->portcntrs)
			qib_dev_err(dd,
				"Failed allocation for portcounters\n");
	}
}

static u32 qib_read_7322cntrs(struct qib_devdata *dd, loff_t pos, char **namep,
			      u64 **cntrp)
{
	u32 ret;

	if (namep) {
		ret = dd->cspec->cntrnamelen;
		if (pos >= ret)
			ret = 0; /* final read after getting everything */
		else
			*namep = (char *) cntr7322names;
	} else {
		u64 *cntr = dd->cspec->cntrs;
		int i;

		ret = dd->cspec->ncntrs * sizeof(u64);
		if (!cntr || pos >= ret) {
			/* everything read, or couldn't get memory */
			ret = 0;
			goto done;
		}
		*cntrp = cntr;
		for (i = 0; i < dd->cspec->ncntrs; i++)
			if (cntr7322indices[i] & _PORT_64BIT_FLAG)
				*cntr++ = read_7322_creg(dd,
							 cntr7322indices[i] &
							 _PORT_CNTR_IDXMASK);
			else
				*cntr++ = read_7322_creg32(dd,
							   cntr7322indices[i]);
	}
done:
	return ret;
}

static u32 qib_read_7322portcntrs(struct qib_devdata *dd, loff_t pos, u32 port,
				  char **namep, u64 **cntrp)
{
	u32 ret;

	if (namep) {
		ret = dd->cspec->portcntrnamelen;
		if (pos >= ret)
			ret = 0; /* final read after getting everything */
		else
			*namep = (char *)portcntr7322names;
	} else {
		struct qib_pportdata *ppd = &dd->pport[port];
		u64 *cntr = ppd->cpspec->portcntrs;
		int i;

		ret = dd->cspec->nportcntrs * sizeof(u64);
		if (!cntr || pos >= ret) {
			/* everything read, or couldn't get memory */
			ret = 0;
			goto done;
		}
		*cntrp = cntr;
		for (i = 0; i < dd->cspec->nportcntrs; i++) {
			if (portcntr7322indices[i] & _PORT_VIRT_FLAG)
				*cntr++ = qib_portcntr_7322(ppd,
					portcntr7322indices[i] &
					_PORT_CNTR_IDXMASK);
			else if (portcntr7322indices[i] & _PORT_64BIT_FLAG)
				*cntr++ = read_7322_creg_port(ppd,
					   portcntr7322indices[i] &
					    _PORT_CNTR_IDXMASK);
			else
				*cntr++ = read_7322_creg32_port(ppd,
					   portcntr7322indices[i]);
		}
	}
done:
	return ret;
}

/**
 * qib_get_7322_faststats - get word counters from chip before they overflow
 * @opaque - contains a pointer to the qlogic_ib device qib_devdata
 *
 * VESTIGIAL IBA7322 has no "small fast counters", so the only
 * real purpose of this function is to maintain the notion of
 * "active time", which in turn is only logged into the eeprom,
 * which we don;t have, yet, for 7322-based boards.
 *
 * called from add_timer
 */
static void qib_get_7322_faststats(unsigned long opaque)
{
	struct qib_devdata *dd = (struct qib_devdata *) opaque;
	struct qib_pportdata *ppd;
	unsigned long flags;
	u64 traffic_wds;
	int pidx;

	for (pidx = 0; pidx < dd->num_pports; ++pidx) {
		ppd = dd->pport + pidx;

		/*
		 * If port isn't enabled or not operational ports, or
		 * diags is running (can cause memory diags to fail)
		 * skip this port this time.
		 */
		if (!ppd->link_speed_supported || !(dd->flags & QIB_INITTED)
		    || dd->diag_client)
			continue;

		/*
		 * Maintain an activity timer, based on traffic
		 * exceeding a threshold, so we need to check the word-counts
		 * even if they are 64-bit.
		 */
		traffic_wds = qib_portcntr_7322(ppd, QIBPORTCNTR_WORDRCV) +
			qib_portcntr_7322(ppd, QIBPORTCNTR_WORDSEND);
		spin_lock_irqsave(&ppd->dd->eep_st_lock, flags);
		traffic_wds -= ppd->dd->traffic_wds;
		ppd->dd->traffic_wds += traffic_wds;
		if (traffic_wds >= QIB_TRAFFIC_ACTIVE_THRESHOLD)
			atomic_add(ACTIVITY_TIMER, &ppd->dd->active_time);
		spin_unlock_irqrestore(&ppd->dd->eep_st_lock, flags);
		if (ppd->cpspec->qdr_dfe_on && (ppd->link_speed_active &
						QIB_IB_QDR) &&
		    (ppd->lflags & (QIBL_LINKINIT | QIBL_LINKARMED |
				    QIBL_LINKACTIVE)) &&
		    ppd->cpspec->qdr_dfe_time &&
		    time_is_before_jiffies(ppd->cpspec->qdr_dfe_time)) {
			ppd->cpspec->qdr_dfe_on = 0;

			qib_write_kreg_port(ppd, krp_static_adapt_dis(2),
					    ppd->dd->cspec->r1 ?
					    QDR_STATIC_ADAPT_INIT_R1 :
					    QDR_STATIC_ADAPT_INIT);
			force_h1(ppd);
		}
	}
	mod_timer(&dd->stats_timer, jiffies + HZ * ACTIVITY_TIMER);
}

/*
 * If we were using MSIx, try to fallback to INTx.
 */
static int qib_7322_intr_fallback(struct qib_devdata *dd)
{
	if (!dd->cspec->num_msix_entries)
		return 0; /* already using INTx */

	qib_devinfo(dd->pcidev,
		"MSIx interrupt not detected, trying INTx interrupts\n");
	qib_7322_nomsix(dd);
	qib_enable_intx(dd->pcidev);
	qib_setup_7322_interrupt(dd, 0);
	return 1;
}

/*
 * Reset the XGXS (between serdes and IBC).  Slightly less intrusive
 * than resetting the IBC or external link state, and useful in some
 * cases to cause some retraining.  To do this right, we reset IBC
 * as well, then return to previous state (which may be still in reset)
 * NOTE: some callers of this "know" this writes the current value
 * of cpspec->ibcctrl_a as part of it's operation, so if that changes,
 * check all callers.
 */
static void qib_7322_mini_pcs_reset(struct qib_pportdata *ppd)
{
	u64 val;
	struct qib_devdata *dd = ppd->dd;
	const u64 reset_bits = SYM_MASK(IBPCSConfig_0, xcv_rreset) |
		SYM_MASK(IBPCSConfig_0, xcv_treset) |
		SYM_MASK(IBPCSConfig_0, tx_rx_reset);

	val = qib_read_kreg_port(ppd, krp_ib_pcsconfig);
	qib_write_kreg(dd, kr_hwerrmask,
		       dd->cspec->hwerrmask & ~HWE_MASK(statusValidNoEop));
	qib_write_kreg_port(ppd, krp_ibcctrl_a,
			    ppd->cpspec->ibcctrl_a &
			    ~SYM_MASK(IBCCtrlA_0, IBLinkEn));

	qib_write_kreg_port(ppd, krp_ib_pcsconfig, val | reset_bits);
	qib_read_kreg32(dd, kr_scratch);
	qib_write_kreg_port(ppd, krp_ib_pcsconfig, val & ~reset_bits);
	qib_write_kreg_port(ppd, krp_ibcctrl_a, ppd->cpspec->ibcctrl_a);
	qib_write_kreg(dd, kr_scratch, 0ULL);
	qib_write_kreg(dd, kr_hwerrclear,
		       SYM_MASK(HwErrClear, statusValidNoEopClear));
	qib_write_kreg(dd, kr_hwerrmask, dd->cspec->hwerrmask);
}

/*
 * This code for non-IBTA-compliant IB speed negotiation is only known to
 * work for the SDR to DDR transition, and only between an HCA and a switch
 * with recent firmware.  It is based on observed heuristics, rather than
 * actual knowledge of the non-compliant speed negotiation.
 * It has a number of hard-coded fields, since the hope is to rewrite this
 * when a spec is available on how the negoation is intended to work.
 */
static void autoneg_7322_sendpkt(struct qib_pportdata *ppd, u32 *hdr,
				 u32 dcnt, u32 *data)
{
	int i;
	u64 pbc;
	u32 __iomem *piobuf;
	u32 pnum, control, len;
	struct qib_devdata *dd = ppd->dd;

	i = 0;
	len = 7 + dcnt + 1; /* 7 dword header, dword data, icrc */
	control = qib_7322_setpbc_control(ppd, len, 0, 15);
	pbc = ((u64) control << 32) | len;
	while (!(piobuf = qib_7322_getsendbuf(ppd, pbc, &pnum))) {
		if (i++ > 15)
			return;
		udelay(2);
	}
	/* disable header check on this packet, since it can't be valid */
	dd->f_txchk_change(dd, pnum, 1, TXCHK_CHG_TYPE_DIS1, NULL);
	writeq(pbc, piobuf);
	qib_flush_wc();
	qib_pio_copy(piobuf + 2, hdr, 7);
	qib_pio_copy(piobuf + 9, data, dcnt);
	if (dd->flags & QIB_USE_SPCL_TRIG) {
		u32 spcl_off = (pnum >= dd->piobcnt2k) ? 2047 : 1023;

		qib_flush_wc();
		__raw_writel(0xaebecede, piobuf + spcl_off);
	}
	qib_flush_wc();
	qib_sendbuf_done(dd, pnum);
	/* and re-enable hdr check */
	dd->f_txchk_change(dd, pnum, 1, TXCHK_CHG_TYPE_ENAB1, NULL);
}

/*
 * _start packet gets sent twice at start, _done gets sent twice at end
 */
static void qib_autoneg_7322_send(struct qib_pportdata *ppd, int which)
{
	struct qib_devdata *dd = ppd->dd;
	static u32 swapped;
	u32 dw, i, hcnt, dcnt, *data;
	static u32 hdr[7] = { 0xf002ffff, 0x48ffff, 0x6400abba };
	static u32 madpayload_start[0x40] = {
		0x1810103, 0x1, 0x0, 0x0, 0x2c90000, 0x2c9, 0x0, 0x0,
		0xffffffff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
		0x1, 0x1388, 0x15e, 0x1, /* rest 0's */
		};
	static u32 madpayload_done[0x40] = {
		0x1810103, 0x1, 0x0, 0x0, 0x2c90000, 0x2c9, 0x0, 0x0,
		0xffffffff, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
		0x40000001, 0x1388, 0x15e, /* rest 0's */
		};

	dcnt = ARRAY_SIZE(madpayload_start);
	hcnt = ARRAY_SIZE(hdr);
	if (!swapped) {
		/* for maintainability, do it at runtime */
		for (i = 0; i < hcnt; i++) {
			dw = (__force u32) cpu_to_be32(hdr[i]);
			hdr[i] = dw;
		}
		for (i = 0; i < dcnt; i++) {
			dw = (__force u32) cpu_to_be32(madpayload_start[i]);
			madpayload_start[i] = dw;
			dw = (__force u32) cpu_to_be32(madpayload_done[i]);
			madpayload_done[i] = dw;
		}
		swapped = 1;
	}

	data = which ? madpayload_done : madpayload_start;

	autoneg_7322_sendpkt(ppd, hdr, dcnt, data);
	qib_read_kreg64(dd, kr_scratch);
	udelay(2);
	autoneg_7322_sendpkt(ppd, hdr, dcnt, data);
	qib_read_kreg64(dd, kr_scratch);
	udelay(2);
}

/*
 * Do the absolute minimum to cause an IB speed change, and make it
 * ready, but don't actually trigger the change.   The caller will
 * do that when ready (if link is in Polling training state, it will
 * happen immediately, otherwise when link next goes down)
 *
 * This routine should only be used as part of the DDR autonegotation
 * code for devices that are not compliant with IB 1.2 (or code that
 * fixes things up for same).
 *
 * When link has gone down, and autoneg enabled, or autoneg has
 * failed and we give up until next time we set both speeds, and
 * then we want IBTA enabled as well as "use max enabled speed.
 */
static void set_7322_ibspeed_fast(struct qib_pportdata *ppd, u32 speed)
{
	u64 newctrlb;
	newctrlb = ppd->cpspec->ibcctrl_b & ~(IBA7322_IBC_SPEED_MASK |
				    IBA7322_IBC_IBTA_1_2_MASK |
				    IBA7322_IBC_MAX_SPEED_MASK);

	if (speed & (speed - 1)) /* multiple speeds */
		newctrlb |= (speed << IBA7322_IBC_SPEED_LSB) |
				    IBA7322_IBC_IBTA_1_2_MASK |
				    IBA7322_IBC_MAX_SPEED_MASK;
	else
		newctrlb |= speed == QIB_IB_QDR ?
			IBA7322_IBC_SPEED_QDR | IBA7322_IBC_IBTA_1_2_MASK :
			((speed == QIB_IB_DDR ?
			  IBA7322_IBC_SPEED_DDR : IBA7322_IBC_SPEED_SDR));

	if (newctrlb == ppd->cpspec->ibcctrl_b)
		return;

	ppd->cpspec->ibcctrl_b = newctrlb;
	qib_write_kreg_port(ppd, krp_ibcctrl_b, ppd->cpspec->ibcctrl_b);
	qib_write_kreg(ppd->dd, kr_scratch, 0);
}

/*
 * This routine is only used when we are not talking to another
 * IB 1.2-compliant device that we think can do DDR.
 * (This includes all existing switch chips as of Oct 2007.)
 * 1.2-compliant devices go directly to DDR prior to reaching INIT
 */
static void try_7322_autoneg(struct qib_pportdata *ppd)
{
	unsigned long flags;

	spin_lock_irqsave(&ppd->lflags_lock, flags);
	ppd->lflags |= QIBL_IB_AUTONEG_INPROG;
	spin_unlock_irqrestore(&ppd->lflags_lock, flags);
	qib_autoneg_7322_send(ppd, 0);
	set_7322_ibspeed_fast(ppd, QIB_IB_DDR);
	qib_7322_mini_pcs_reset(ppd);
	/* 2 msec is minimum length of a poll cycle */
	queue_delayed_work(ib_wq, &ppd->cpspec->autoneg_work,
			   msecs_to_jiffies(2));
}

/*
 * Handle the empirically determined mechanism for auto-negotiation
 * of DDR speed with switches.
 */
static void autoneg_7322_work(struct work_struct *work)
{
	struct qib_pportdata *ppd;
	struct qib_devdata *dd;
	u64 startms;
	u32 i;
	unsigned long flags;

	ppd = container_of(work, struct qib_chippport_specific,
			    autoneg_work.work)->ppd;
	dd = ppd->dd;

	startms = jiffies_to_msecs(jiffies);

	/*
	 * Busy wait for this first part, it should be at most a
	 * few hundred usec, since we scheduled ourselves for 2msec.
	 */
	for (i = 0; i < 25; i++) {
		if (SYM_FIELD(ppd->lastibcstat, IBCStatusA_0, LinkState)
		     == IB_7322_LT_STATE_POLLQUIET) {
			qib_set_linkstate(ppd, QIB_IB_LINKDOWN_DISABLE);
			break;
		}
		udelay(100);
	}

	if (!(ppd->lflags & QIBL_IB_AUTONEG_INPROG))
		goto done; /* we got there early or told to stop */

	/* we expect this to timeout */
	if (wait_event_timeout(ppd->cpspec->autoneg_wait,
			       !(ppd->lflags & QIBL_IB_AUTONEG_INPROG),
			       msecs_to_jiffies(90)))
		goto done;
	qib_7322_mini_pcs_reset(ppd);

	/* we expect this to timeout */
	if (wait_event_timeout(ppd->cpspec->autoneg_wait,
			       !(ppd->lflags & QIBL_IB_AUTONEG_INPROG),
			       msecs_to_jiffies(1700)))
		goto done;
	qib_7322_mini_pcs_reset(ppd);

	set_7322_ibspeed_fast(ppd, QIB_IB_SDR);

	/*
	 * Wait up to 250 msec for link to train and get to INIT at DDR;
	 * this should terminate early.
	 */
	wait_event_timeout(ppd->cpspec->autoneg_wait,
		!(ppd->lflags & QIBL_IB_AUTONEG_INPROG),
		msecs_to_jiffies(250));
done:
	if (ppd->lflags & QIBL_IB_AUTONEG_INPROG) {
		spin_lock_irqsave(&ppd->lflags_lock, flags);
		ppd->lflags &= ~QIBL_IB_AUTONEG_INPROG;
		if (ppd->cpspec->autoneg_tries == AUTONEG_TRIES) {
			ppd->lflags |= QIBL_IB_AUTONEG_FAILED;
			ppd->cpspec->autoneg_tries = 0;
		}
		spin_unlock_irqrestore(&ppd->lflags_lock, flags);
		set_7322_ibspeed_fast(ppd, ppd->link_speed_enabled);
	}
}

/*
 * This routine is used to request IPG set in the QLogic switch.
 * Only called if r1.
 */
static void try_7322_ipg(struct qib_pportdata *ppd)
{
	struct qib_ibport *ibp = &ppd->ibport_data;
	struct ib_mad_send_buf *send_buf;
	struct ib_mad_agent *agent;
	struct ib_smp *smp;
	unsigned delay;
	int ret;

	agent = ibp->send_agent;
	if (!agent)
		goto retry;

	send_buf = ib_create_send_mad(agent, 0, 0, 0, IB_MGMT_MAD_HDR,
				      IB_MGMT_MAD_DATA, GFP_ATOMIC);
	if (IS_ERR(send_buf))
		goto retry;

	if (!ibp->smi_ah) {
		struct ib_ah *ah;

		ah = qib_create_qp0_ah(ibp, be16_to_cpu(IB_LID_PERMISSIVE));
		if (IS_ERR(ah))
			ret = PTR_ERR(ah);
		else {
			send_buf->ah = ah;
			ibp->smi_ah = to_iah(ah);
			ret = 0;
		}
	} else {
		send_buf->ah = &ibp->smi_ah->ibah;
		ret = 0;
	}

	smp = send_buf->mad;
	smp->base_version = IB_MGMT_BASE_VERSION;
	smp->mgmt_class = IB_MGMT_CLASS_SUBN_DIRECTED_ROUTE;
	smp->class_version = 1;
	smp->method = IB_MGMT_METHOD_SEND;
	smp->hop_cnt = 1;
	smp->attr_id = QIB_VENDOR_IPG;
	smp->attr_mod = 0;

	if (!ret)
		ret = ib_post_send_mad(send_buf, NULL);
	if (ret)
		ib_free_send_mad(send_buf);
retry:
	delay = 2 << ppd->cpspec->ipg_tries;
	queue_delayed_work(ib_wq, &ppd->cpspec->ipg_work,
			   msecs_to_jiffies(delay));
}

/*
 * Timeout handler for setting IPG.
 * Only called if r1.
 */
static void ipg_7322_work(struct work_struct *work)
{
	struct qib_pportdata *ppd;

	ppd = container_of(work, struct qib_chippport_specific,
			   ipg_work.work)->ppd;
	if ((ppd->lflags & (QIBL_LINKINIT | QIBL_LINKARMED | QIBL_LINKACTIVE))
	    && ++ppd->cpspec->ipg_tries <= 10)
		try_7322_ipg(ppd);
}

static u32 qib_7322_iblink_state(u64 ibcs)
{
	u32 state = (u32)SYM_FIELD(ibcs, IBCStatusA_0, LinkState);

	switch (state) {
	case IB_7322_L_STATE_INIT:
		state = IB_PORT_INIT;
		break;
	case IB_7322_L_STATE_ARM:
		state = IB_PORT_ARMED;
		break;
	case IB_7322_L_STATE_ACTIVE:
		/* fall through */
	case IB_7322_L_STATE_ACT_DEFER:
		state = IB_PORT_ACTIVE;
		break;
	default: /* fall through */
	case IB_7322_L_STATE_DOWN:
		state = IB_PORT_DOWN;
		break;
	}
	return state;
}

/* returns the IBTA port state, rather than the IBC link training state */
static u8 qib_7322_phys_portstate(u64 ibcs)
{
	u8 state = (u8)SYM_FIELD(ibcs, IBCStatusA_0, LinkTrainingState);
	return qib_7322_physportstate[state];
}

static int qib_7322_ib_updown(struct qib_pportdata *ppd, int ibup, u64 ibcs)
{
	int ret = 0, symadj = 0;
	unsigned long flags;
	int mult;

	spin_lock_irqsave(&ppd->lflags_lock, flags);
	ppd->lflags &= ~QIBL_IB_FORCE_NOTIFY;
	spin_unlock_irqrestore(&ppd->lflags_lock, flags);

	/* Update our picture of width and speed from chip */
	if (ibcs & SYM_MASK(IBCStatusA_0, LinkSpeedQDR)) {
		ppd->link_speed_active = QIB_IB_QDR;
		mult = 4;
	} else if (ibcs & SYM_MASK(IBCStatusA_0, LinkSpeedActive)) {
		ppd->link_speed_active = QIB_IB_DDR;
		mult = 2;
	} else {
		ppd->link_speed_active = QIB_IB_SDR;
		mult = 1;
	}
	if (ibcs & SYM_MASK(IBCStatusA_0, LinkWidthActive)) {
		ppd->link_width_active = IB_WIDTH_4X;
		mult *= 4;
	} else
		ppd->link_width_active = IB_WIDTH_1X;
	ppd->delay_mult = ib_rate_to_delay[mult_to_ib_rate(mult)];

	if (!ibup) {
		u64 clr;

		/* Link went down. */
		/* do IPG MAD again after linkdown, even if last time failed */
		ppd->cpspec->ipg_tries = 0;
		clr = qib_read_kreg_port(ppd, krp_ibcstatus_b) &
			(SYM_MASK(IBCStatusB_0, heartbeat_timed_out) |
			 SYM_MASK(IBCStatusB_0, heartbeat_crosstalk));
		if (clr)
			qib_write_kreg_port(ppd, krp_ibcstatus_b, clr);
		if (!(ppd->lflags & (QIBL_IB_AUTONEG_FAILED |
				     QIBL_IB_AUTONEG_INPROG)))
			set_7322_ibspeed_fast(ppd, ppd->link_speed_enabled);
		if (!(ppd->lflags & QIBL_IB_AUTONEG_INPROG)) {
			struct qib_qsfp_data *qd =
				&ppd->cpspec->qsfp_data;
			/* unlock the Tx settings, speed may change */
			qib_write_kreg_port(ppd, krp_tx_deemph_override,
				SYM_MASK(IBSD_TX_DEEMPHASIS_OVERRIDE_0,
				reset_tx_deemphasis_override));
			qib_cancel_sends(ppd);
			/* on link down, ensure sane pcs state */
			qib_7322_mini_pcs_reset(ppd);
			/* schedule the qsfp refresh which should turn the link
			   off */
			if (ppd->dd->flags & QIB_HAS_QSFP) {
				qd->t_insert = jiffies;
				queue_work(ib_wq, &qd->work);
			}
			spin_lock_irqsave(&ppd->sdma_lock, flags);
			if (__qib_sdma_running(ppd))
				__qib_sdma_process_event(ppd,
					qib_sdma_event_e70_go_idle);
			spin_unlock_irqrestore(&ppd->sdma_lock, flags);
		}
		clr = read_7322_creg32_port(ppd, crp_iblinkdown);
		if (clr == ppd->cpspec->iblnkdownsnap)
			ppd->cpspec->iblnkdowndelta++;
	} else {
		if (qib_compat_ddr_negotiate &&
		    !(ppd->lflags & (QIBL_IB_AUTONEG_FAILED |
				     QIBL_IB_AUTONEG_INPROG)) &&
		    ppd->link_speed_active == QIB_IB_SDR &&
		    (ppd->link_speed_enabled & QIB_IB_DDR)
		    && ppd->cpspec->autoneg_tries < AUTONEG_TRIES) {
			/* we are SDR, and auto-negotiation enabled */
			++ppd->cpspec->autoneg_tries;
			if (!ppd->cpspec->ibdeltainprog) {
				ppd->cpspec->ibdeltainprog = 1;
				ppd->cpspec->ibsymdelta +=
					read_7322_creg32_port(ppd,
						crp_ibsymbolerr) -
						ppd->cpspec->ibsymsnap;
				ppd->cpspec->iblnkerrdelta +=
					read_7322_creg32_port(ppd,
						crp_iblinkerrrecov) -
						ppd->cpspec->iblnkerrsnap;
			}
			try_7322_autoneg(ppd);
			ret = 1; /* no other IB status change processing */
		} else if ((ppd->lflags & QIBL_IB_AUTONEG_INPROG) &&
			   ppd->link_speed_active == QIB_IB_SDR) {
			qib_autoneg_7322_send(ppd, 1);
			set_7322_ibspeed_fast(ppd, QIB_IB_DDR);
			qib_7322_mini_pcs_reset(ppd);
			udelay(2);
			ret = 1; /* no other IB status change processing */
		} else if ((ppd->lflags & QIBL_IB_AUTONEG_INPROG) &&
			   (ppd->link_speed_active & QIB_IB_DDR)) {
			spin_lock_irqsave(&ppd->lflags_lock, flags);
			ppd->lflags &= ~(QIBL_IB_AUTONEG_INPROG |
					 QIBL_IB_AUTONEG_FAILED);
			spin_unlock_irqrestore(&ppd->lflags_lock, flags);
			ppd->cpspec->autoneg_tries = 0;
			/* re-enable SDR, for next link down */
			set_7322_ibspeed_fast(ppd, ppd->link_speed_enabled);
			wake_up(&ppd->cpspec->autoneg_wait);
			symadj = 1;
		} else if (ppd->lflags & QIBL_IB_AUTONEG_FAILED) {
			/*
			 * Clear autoneg failure flag, and do setup
			 * so we'll try next time link goes down and
			 * back to INIT (possibly connected to a
			 * different device).
			 */
			spin_lock_irqsave(&ppd->lflags_lock, flags);
			ppd->lflags &= ~QIBL_IB_AUTONEG_FAILED;
			spin_unlock_irqrestore(&ppd->lflags_lock, flags);
			ppd->cpspec->ibcctrl_b |= IBA7322_IBC_IBTA_1_2_MASK;
			symadj = 1;
		}
		if (!(ppd->lflags & QIBL_IB_AUTONEG_INPROG)) {
			symadj = 1;
			if (ppd->dd->cspec->r1 && ppd->cpspec->ipg_tries <= 10)
				try_7322_ipg(ppd);
			if (!ppd->cpspec->recovery_init)
				setup_7322_link_recovery(ppd, 0);
			ppd->cpspec->qdr_dfe_time = jiffies +
				msecs_to_jiffies(QDR_DFE_DISABLE_DELAY);
		}
		ppd->cpspec->ibmalfusesnap = 0;
		ppd->cpspec->ibmalfsnap = read_7322_creg32_port(ppd,
			crp_errlink);
	}
	if (symadj) {
		ppd->cpspec->iblnkdownsnap =
			read_7322_creg32_port(ppd, crp_iblinkdown);
		if (ppd->cpspec->ibdeltainprog) {
			ppd->cpspec->ibdeltainprog = 0;
			ppd->cpspec->ibsymdelta += read_7322_creg32_port(ppd,
				crp_ibsymbolerr) - ppd->cpspec->ibsymsnap;
			ppd->cpspec->iblnkerrdelta += read_7322_creg32_port(ppd,
				crp_iblinkerrrecov) - ppd->cpspec->iblnkerrsnap;
		}
	} else if (!ibup && qib_compat_ddr_negotiate &&
		   !ppd->cpspec->ibdeltainprog &&
			!(ppd->lflags & QIBL_IB_AUTONEG_INPROG)) {
		ppd->cpspec->ibdeltainprog = 1;
		ppd->cpspec->ibsymsnap = read_7322_creg32_port(ppd,
			crp_ibsymbolerr);
		ppd->cpspec->iblnkerrsnap = read_7322_creg32_port(ppd,
			crp_iblinkerrrecov);
	}

	if (!ret)
		qib_setup_7322_setextled(ppd, ibup);
	return ret;
}

/*
 * Does read/modify/write to appropriate registers to
 * set output and direction bits selected by mask.
 * these are in their canonical postions (e.g. lsb of
 * dir will end up in D48 of extctrl on existing chips).
 * returns contents of GP Inputs.
 */
static int gpio_7322_mod(struct qib_devdata *dd, u32 out, u32 dir, u32 mask)
{